blob: ae94d1e66618df8be1b3c89fe509021c72373ab5 [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"
Micah Villmow3574eca2012-10-08 16:38:25 +000047#include "llvm/DataLayout.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,
Bill Wendling12931302012-09-26 04:04:19 +000092 EVT PartVT, EVT ValueVT, const Value *V);
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,
Bill Wendling12931302012-09-26 04:04:19 +0000102 const Value *V,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000103 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Chris Lattner3ac18842010-08-24 23:20:40 +0000104 if (ValueVT.isVector())
Bill Wendling12931302012-09-26 04:04:19 +0000105 return getCopyFromPartsVector(DAG, DL, Parts, NumParts,
106 PartVT, ValueVT, V);
Michael J. Spencere70c5262010-10-16 08:25:21 +0000107
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000108 assert(NumParts > 0 && "No parts to assemble!");
Dan Gohmane9530ec2009-01-15 16:58:17 +0000109 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000110 SDValue Val = Parts[0];
111
112 if (NumParts > 1) {
113 // Assemble the value from multiple parts.
Chris Lattner3ac18842010-08-24 23:20:40 +0000114 if (ValueVT.isInteger()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000115 unsigned PartBits = PartVT.getSizeInBits();
116 unsigned ValueBits = ValueVT.getSizeInBits();
117
118 // Assemble the power of 2 part.
119 unsigned RoundParts = NumParts & (NumParts - 1) ?
120 1 << Log2_32(NumParts) : NumParts;
121 unsigned RoundBits = PartBits * RoundParts;
Owen Andersone50ed302009-08-10 22:56:29 +0000122 EVT RoundVT = RoundBits == ValueBits ?
Owen Anderson23b9b192009-08-12 00:36:31 +0000123 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000124 SDValue Lo, Hi;
125
Owen Anderson23b9b192009-08-12 00:36:31 +0000126 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000127
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000128 if (RoundParts > 2) {
Chris Lattner3ac18842010-08-24 23:20:40 +0000129 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
Bill Wendling12931302012-09-26 04:04:19 +0000130 PartVT, HalfVT, V);
Chris Lattner3ac18842010-08-24 23:20:40 +0000131 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
Bill Wendling12931302012-09-26 04:04:19 +0000132 RoundParts / 2, PartVT, HalfVT, V);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000133 } else {
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000134 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
135 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000136 }
Bill Wendling3ea3c242009-12-22 02:10:19 +0000137
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000138 if (TLI.isBigEndian())
139 std::swap(Lo, Hi);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000140
Chris Lattner3ac18842010-08-24 23:20:40 +0000141 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000142
143 if (RoundParts < NumParts) {
144 // Assemble the trailing non-power-of-2 part.
145 unsigned OddParts = NumParts - RoundParts;
Owen Anderson23b9b192009-08-12 00:36:31 +0000146 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
Chris Lattner3ac18842010-08-24 23:20:40 +0000147 Hi = getCopyFromParts(DAG, DL,
Bill Wendling12931302012-09-26 04:04:19 +0000148 Parts + RoundParts, OddParts, PartVT, OddVT, V);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000149
150 // Combine the round and odd parts.
151 Lo = Val;
152 if (TLI.isBigEndian())
153 std::swap(Lo, Hi);
Owen Anderson23b9b192009-08-12 00:36:31 +0000154 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Chris Lattner3ac18842010-08-24 23:20:40 +0000155 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
156 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000157 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands92abc622009-01-31 15:50:11 +0000158 TLI.getPointerTy()));
Chris Lattner3ac18842010-08-24 23:20:40 +0000159 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
160 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000161 }
Eli Friedman2ac8b322009-05-20 06:02:09 +0000162 } else if (PartVT.isFloatingPoint()) {
163 // FP split into multiple FP parts (for ppcf128)
Owen Anderson825b72b2009-08-11 20:47:22 +0000164 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
Eli Friedman2ac8b322009-05-20 06:02:09 +0000165 "Unexpected split");
166 SDValue Lo, Hi;
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000167 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
168 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
Eli Friedman2ac8b322009-05-20 06:02:09 +0000169 if (TLI.isBigEndian())
170 std::swap(Lo, Hi);
Chris Lattner3ac18842010-08-24 23:20:40 +0000171 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
Eli Friedman2ac8b322009-05-20 06:02:09 +0000172 } else {
173 // FP split into integer parts (soft fp)
174 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
175 !PartVT.isVector() && "Unexpected split");
Owen Anderson23b9b192009-08-12 00:36:31 +0000176 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
Bill Wendling12931302012-09-26 04:04:19 +0000177 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT, V);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000178 }
179 }
180
181 // There is now one part, held in Val. Correct it to match ValueVT.
182 PartVT = Val.getValueType();
183
184 if (PartVT == ValueVT)
185 return Val;
186
Chris Lattner3ac18842010-08-24 23:20:40 +0000187 if (PartVT.isInteger() && ValueVT.isInteger()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000188 if (ValueVT.bitsLT(PartVT)) {
189 // For a truncate, see if we have any information to
190 // indicate whether the truncated bits will always be
191 // zero or sign-extension.
192 if (AssertOp != ISD::DELETED_NODE)
Chris Lattner3ac18842010-08-24 23:20:40 +0000193 Val = DAG.getNode(AssertOp, DL, PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000194 DAG.getValueType(ValueVT));
Chris Lattner3ac18842010-08-24 23:20:40 +0000195 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000196 }
Chris Lattner3ac18842010-08-24 23:20:40 +0000197 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000198 }
199
200 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Chris Lattner3ac18842010-08-24 23:20:40 +0000201 // FP_ROUND's are always exact here.
202 if (ValueVT.bitsLT(Val.getValueType()))
203 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
Pete Cooperf57e1c22012-01-17 01:54:07 +0000204 DAG.getTargetConstant(1, TLI.getPointerTy()));
Bill Wendling3ea3c242009-12-22 02:10:19 +0000205
Chris Lattner3ac18842010-08-24 23:20:40 +0000206 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000207 }
208
Bill Wendling4533cac2010-01-28 21:51:40 +0000209 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000210 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000211
Torok Edwinc23197a2009-07-14 16:55:14 +0000212 llvm_unreachable("Unknown mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000213}
214
Bill Wendling12931302012-09-26 04:04:19 +0000215/// getCopyFromPartsVector - Create a value that contains the specified legal
216/// parts combined into the value they represent. If the parts combine to a
217/// type larger then ValueVT then AssertOp can be used to specify whether the
218/// extra bits are known to be zero (ISD::AssertZext) or sign extended from
219/// ValueVT (ISD::AssertSext).
Chris Lattner3ac18842010-08-24 23:20:40 +0000220static SDValue getCopyFromPartsVector(SelectionDAG &DAG, DebugLoc DL,
221 const SDValue *Parts, unsigned NumParts,
Bill Wendling12931302012-09-26 04:04:19 +0000222 EVT PartVT, EVT ValueVT, const Value *V) {
Chris Lattner3ac18842010-08-24 23:20:40 +0000223 assert(ValueVT.isVector() && "Not a vector value");
224 assert(NumParts > 0 && "No parts to assemble!");
225 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
226 SDValue Val = Parts[0];
Michael J. Spencere70c5262010-10-16 08:25:21 +0000227
Chris Lattner3ac18842010-08-24 23:20:40 +0000228 // Handle a multi-element vector.
229 if (NumParts > 1) {
230 EVT IntermediateVT, RegisterVT;
231 unsigned NumIntermediates;
232 unsigned NumRegs =
233 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
234 NumIntermediates, RegisterVT);
235 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
236 NumParts = NumRegs; // Silence a compiler warning.
237 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
238 assert(RegisterVT == Parts[0].getValueType() &&
239 "Part type doesn't match part!");
Michael J. Spencere70c5262010-10-16 08:25:21 +0000240
Chris Lattner3ac18842010-08-24 23:20:40 +0000241 // Assemble the parts into intermediate operands.
242 SmallVector<SDValue, 8> Ops(NumIntermediates);
243 if (NumIntermediates == NumParts) {
244 // If the register was not expanded, truncate or copy the value,
245 // as appropriate.
246 for (unsigned i = 0; i != NumParts; ++i)
247 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
Bill Wendling12931302012-09-26 04:04:19 +0000248 PartVT, IntermediateVT, V);
Chris Lattner3ac18842010-08-24 23:20:40 +0000249 } else if (NumParts > 0) {
250 // If the intermediate type was expanded, build the intermediate
251 // operands from the parts.
252 assert(NumParts % NumIntermediates == 0 &&
253 "Must expand into a divisible number of parts!");
254 unsigned Factor = NumParts / NumIntermediates;
255 for (unsigned i = 0; i != NumIntermediates; ++i)
256 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
Bill Wendling12931302012-09-26 04:04:19 +0000257 PartVT, IntermediateVT, V);
Chris Lattner3ac18842010-08-24 23:20:40 +0000258 }
Michael J. Spencere70c5262010-10-16 08:25:21 +0000259
Chris Lattner3ac18842010-08-24 23:20:40 +0000260 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
261 // intermediate operands.
262 Val = DAG.getNode(IntermediateVT.isVector() ?
263 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, DL,
264 ValueVT, &Ops[0], NumIntermediates);
265 }
Michael J. Spencere70c5262010-10-16 08:25:21 +0000266
Chris Lattner3ac18842010-08-24 23:20:40 +0000267 // There is now one part, held in Val. Correct it to match ValueVT.
268 PartVT = Val.getValueType();
Michael J. Spencere70c5262010-10-16 08:25:21 +0000269
Chris Lattner3ac18842010-08-24 23:20:40 +0000270 if (PartVT == ValueVT)
271 return Val;
Michael J. Spencere70c5262010-10-16 08:25:21 +0000272
Chris Lattnere6f7c262010-08-25 22:49:25 +0000273 if (PartVT.isVector()) {
274 // If the element type of the source/dest vectors are the same, but the
275 // parts vector has more elements than the value vector, then we have a
276 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
277 // elements we want.
278 if (PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
279 assert(PartVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
280 "Cannot narrow, it would be a lossy transformation");
281 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
282 DAG.getIntPtrConstant(0));
Michael J. Spencere70c5262010-10-16 08:25:21 +0000283 }
284
Chris Lattnere6f7c262010-08-25 22:49:25 +0000285 // Vector/Vector bitcast.
Nadav Rotem0b666362011-06-04 20:58:08 +0000286 if (ValueVT.getSizeInBits() == PartVT.getSizeInBits())
287 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
288
289 assert(PartVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
290 "Cannot handle this kind of promotion");
291 // Promoted vector extract
Nadav Rotemb05f14b2011-06-12 14:49:38 +0000292 bool Smaller = ValueVT.bitsLE(PartVT);
293 return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
294 DL, ValueVT, Val);
Nadav Rotem0b666362011-06-04 20:58:08 +0000295
Chris Lattnere6f7c262010-08-25 22:49:25 +0000296 }
Eric Christopher471e4222011-06-08 23:55:35 +0000297
Eric Christopher9aaa02a2011-06-01 19:55:10 +0000298 // Trivial bitcast if the types are the same size and the destination
299 // vector type is legal.
300 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits() &&
301 TLI.isTypeLegal(ValueVT))
302 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
Michael J. Spencere70c5262010-10-16 08:25:21 +0000303
Nadav Rotemb05f14b2011-06-12 14:49:38 +0000304 // Handle cases such as i8 -> <1 x i1>
Bill Wendling12931302012-09-26 04:04:19 +0000305 if (ValueVT.getVectorNumElements() != 1) {
306 LLVMContext &Ctx = *DAG.getContext();
307 Twine ErrMsg("non-trivial scalar-to-vector conversion");
308 if (const Instruction *I = dyn_cast_or_null<Instruction>(V)) {
309 if (const CallInst *CI = dyn_cast<CallInst>(I))
310 if (isa<InlineAsm>(CI->getCalledValue()))
311 ErrMsg = ErrMsg + ", possible invalid constraint for vector type";
312 Ctx.emitError(I, ErrMsg);
313 } else {
314 Ctx.emitError(ErrMsg);
315 }
316 report_fatal_error("Cannot handle scalar-to-vector conversion!");
317 }
Nadav Rotemb05f14b2011-06-12 14:49:38 +0000318
319 if (ValueVT.getVectorNumElements() == 1 &&
320 ValueVT.getVectorElementType() != PartVT) {
321 bool Smaller = ValueVT.bitsLE(PartVT);
322 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
323 DL, ValueVT.getScalarType(), Val);
324 }
325
Chris Lattner3ac18842010-08-24 23:20:40 +0000326 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
327}
328
Chris Lattnera13b8602010-08-24 23:10:06 +0000329static void getCopyToPartsVector(SelectionDAG &DAG, DebugLoc dl,
330 SDValue Val, SDValue *Parts, unsigned NumParts,
Bill Wendlingf18eb582012-09-26 06:16:18 +0000331 EVT PartVT, const Value *V);
Michael J. Spencere70c5262010-10-16 08:25:21 +0000332
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000333/// getCopyToParts - Create a series of nodes that contain the specified value
334/// split into legal parts. If the parts contain more bits than Val, then, for
335/// integers, ExtendKind can be used to specify how to generate the extra bits.
Chris Lattnera13b8602010-08-24 23:10:06 +0000336static void getCopyToParts(SelectionDAG &DAG, DebugLoc DL,
Bill Wendling3ea3c242009-12-22 02:10:19 +0000337 SDValue Val, SDValue *Parts, unsigned NumParts,
Bill Wendlingf18eb582012-09-26 06:16:18 +0000338 EVT PartVT, const Value *V,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000339 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Owen Andersone50ed302009-08-10 22:56:29 +0000340 EVT ValueVT = Val.getValueType();
Michael J. Spencere70c5262010-10-16 08:25:21 +0000341
Chris Lattnera13b8602010-08-24 23:10:06 +0000342 // Handle the vector case separately.
343 if (ValueVT.isVector())
Bill Wendlingf18eb582012-09-26 06:16:18 +0000344 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT, V);
Michael J. Spencere70c5262010-10-16 08:25:21 +0000345
Chris Lattnera13b8602010-08-24 23:10:06 +0000346 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000347 unsigned PartBits = PartVT.getSizeInBits();
Dale Johannesen8a36f502009-02-25 22:39:13 +0000348 unsigned OrigNumParts = NumParts;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000349 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
350
Chris Lattnera13b8602010-08-24 23:10:06 +0000351 if (NumParts == 0)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000352 return;
353
Chris Lattnera13b8602010-08-24 23:10:06 +0000354 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
355 if (PartVT == ValueVT) {
356 assert(NumParts == 1 && "No-op copy with multiple parts!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000357 Parts[0] = Val;
358 return;
359 }
360
Chris Lattnera13b8602010-08-24 23:10:06 +0000361 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
362 // If the parts cover more bits than the value has, promote the value.
363 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
364 assert(NumParts == 1 && "Do not know what to promote to!");
365 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
366 } else {
Bill Wendling9e8ceb02012-02-23 23:25:25 +0000367 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
368 ValueVT.isInteger() &&
Michael J. Spencere70c5262010-10-16 08:25:21 +0000369 "Unknown mismatch!");
Chris Lattnera13b8602010-08-24 23:10:06 +0000370 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
371 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
Bill Wendling9e8ceb02012-02-23 23:25:25 +0000372 if (PartVT == MVT::x86mmx)
373 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattnera13b8602010-08-24 23:10:06 +0000374 }
375 } else if (PartBits == ValueVT.getSizeInBits()) {
376 // Different types of the same size.
377 assert(NumParts == 1 && PartVT != ValueVT);
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000378 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattnera13b8602010-08-24 23:10:06 +0000379 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
380 // If the parts cover less bits than value has, truncate the value.
Bill Wendling9e8ceb02012-02-23 23:25:25 +0000381 assert((PartVT.isInteger() || PartVT == MVT::x86mmx) &&
382 ValueVT.isInteger() &&
Chris Lattnera13b8602010-08-24 23:10:06 +0000383 "Unknown mismatch!");
384 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
385 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
Bill Wendling9e8ceb02012-02-23 23:25:25 +0000386 if (PartVT == MVT::x86mmx)
387 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattnera13b8602010-08-24 23:10:06 +0000388 }
389
390 // The value may have changed - recompute ValueVT.
391 ValueVT = Val.getValueType();
392 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
393 "Failed to tile the value with PartVT!");
394
395 if (NumParts == 1) {
Bill Wendlingf18eb582012-09-26 06:16:18 +0000396 if (PartVT != ValueVT) {
397 LLVMContext &Ctx = *DAG.getContext();
398 Twine ErrMsg("scalar-to-vector conversion failed");
399 if (const Instruction *I = dyn_cast_or_null<Instruction>(V)) {
400 if (const CallInst *CI = dyn_cast<CallInst>(I))
401 if (isa<InlineAsm>(CI->getCalledValue()))
402 ErrMsg = ErrMsg + ", possible invalid constraint for vector type";
403 Ctx.emitError(I, ErrMsg);
404 } else {
405 Ctx.emitError(ErrMsg);
406 }
407 }
408
Chris Lattnera13b8602010-08-24 23:10:06 +0000409 Parts[0] = Val;
410 return;
411 }
412
413 // Expand the value into multiple parts.
414 if (NumParts & (NumParts - 1)) {
415 // The number of parts is not a power of 2. Split off and copy the tail.
416 assert(PartVT.isInteger() && ValueVT.isInteger() &&
417 "Do not know what to expand to!");
418 unsigned RoundParts = 1 << Log2_32(NumParts);
419 unsigned RoundBits = RoundParts * PartBits;
420 unsigned OddParts = NumParts - RoundParts;
421 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
422 DAG.getIntPtrConstant(RoundBits));
Bill Wendlingf18eb582012-09-26 06:16:18 +0000423 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT, V);
Chris Lattnera13b8602010-08-24 23:10:06 +0000424
425 if (TLI.isBigEndian())
426 // The odd parts were reversed by getCopyToParts - unreverse them.
427 std::reverse(Parts + RoundParts, Parts + NumParts);
428
429 NumParts = RoundParts;
430 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
431 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
432 }
433
434 // The number of parts is a power of 2. Repeatedly bisect the value using
435 // EXTRACT_ELEMENT.
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000436 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
Chris Lattnera13b8602010-08-24 23:10:06 +0000437 EVT::getIntegerVT(*DAG.getContext(),
438 ValueVT.getSizeInBits()),
439 Val);
440
441 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
442 for (unsigned i = 0; i < NumParts; i += StepSize) {
443 unsigned ThisBits = StepSize * PartBits / 2;
444 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
445 SDValue &Part0 = Parts[i];
446 SDValue &Part1 = Parts[i+StepSize/2];
447
448 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
449 ThisVT, Part0, DAG.getIntPtrConstant(1));
450 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
451 ThisVT, Part0, DAG.getIntPtrConstant(0));
452
453 if (ThisBits == PartBits && ThisVT != PartVT) {
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000454 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
455 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
Chris Lattnera13b8602010-08-24 23:10:06 +0000456 }
457 }
458 }
459
460 if (TLI.isBigEndian())
461 std::reverse(Parts, Parts + OrigNumParts);
462}
463
464
465/// getCopyToPartsVector - Create a series of nodes that contain the specified
466/// value split into legal parts.
467static void getCopyToPartsVector(SelectionDAG &DAG, DebugLoc DL,
468 SDValue Val, SDValue *Parts, unsigned NumParts,
Bill Wendlingf18eb582012-09-26 06:16:18 +0000469 EVT PartVT, const Value *V) {
Chris Lattnera13b8602010-08-24 23:10:06 +0000470 EVT ValueVT = Val.getValueType();
471 assert(ValueVT.isVector() && "Not a vector");
472 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Michael J. Spencere70c5262010-10-16 08:25:21 +0000473
Chris Lattnera13b8602010-08-24 23:10:06 +0000474 if (NumParts == 1) {
Chris Lattnere6f7c262010-08-25 22:49:25 +0000475 if (PartVT == ValueVT) {
476 // Nothing to do.
477 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
478 // Bitconvert vector->vector case.
Wesley Peckbf17cfa2010-11-23 03:31:01 +0000479 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
Chris Lattnere6f7c262010-08-25 22:49:25 +0000480 } else if (PartVT.isVector() &&
Nadav Rotemb05f14b2011-06-12 14:49:38 +0000481 PartVT.getVectorElementType() == ValueVT.getVectorElementType() &&
Chris Lattnere6f7c262010-08-25 22:49:25 +0000482 PartVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
483 EVT ElementVT = PartVT.getVectorElementType();
484 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
485 // undef elements.
486 SmallVector<SDValue, 16> Ops;
487 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
488 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
489 ElementVT, Val, DAG.getIntPtrConstant(i)));
Michael J. Spencere70c5262010-10-16 08:25:21 +0000490
Chris Lattnere6f7c262010-08-25 22:49:25 +0000491 for (unsigned i = ValueVT.getVectorNumElements(),
492 e = PartVT.getVectorNumElements(); i != e; ++i)
493 Ops.push_back(DAG.getUNDEF(ElementVT));
494
495 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, &Ops[0], Ops.size());
496
497 // FIXME: Use CONCAT for 2x -> 4x.
Michael J. Spencere70c5262010-10-16 08:25:21 +0000498
Chris Lattnere6f7c262010-08-25 22:49:25 +0000499 //SDValue UndefElts = DAG.getUNDEF(VectorTy);
500 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
Nadav Rotem0b666362011-06-04 20:58:08 +0000501 } else if (PartVT.isVector() &&
502 PartVT.getVectorElementType().bitsGE(
Nadav Rotemb05f14b2011-06-12 14:49:38 +0000503 ValueVT.getVectorElementType()) &&
Nadav Rotem0b666362011-06-04 20:58:08 +0000504 PartVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
505
506 // Promoted vector extract
Nadav Rotemc6341e62011-06-19 08:49:38 +0000507 bool Smaller = PartVT.bitsLE(ValueVT);
508 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
509 DL, PartVT, Val);
Nadav Rotem0b666362011-06-04 20:58:08 +0000510 } else{
Chris Lattnere6f7c262010-08-25 22:49:25 +0000511 // Vector -> scalar conversion.
Nadav Rotemb05f14b2011-06-12 14:49:38 +0000512 assert(ValueVT.getVectorNumElements() == 1 &&
Chris Lattnere6f7c262010-08-25 22:49:25 +0000513 "Only trivial vector-to-scalar conversions should get here!");
514 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
515 PartVT, Val, DAG.getIntPtrConstant(0));
Nadav Rotemb05f14b2011-06-12 14:49:38 +0000516
517 bool Smaller = ValueVT.bitsLE(PartVT);
518 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
519 DL, PartVT, Val);
Chris Lattnera13b8602010-08-24 23:10:06 +0000520 }
Michael J. Spencere70c5262010-10-16 08:25:21 +0000521
Chris Lattnera13b8602010-08-24 23:10:06 +0000522 Parts[0] = Val;
523 return;
524 }
Michael J. Spencere70c5262010-10-16 08:25:21 +0000525
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000526 // Handle a multi-element vector.
Owen Andersone50ed302009-08-10 22:56:29 +0000527 EVT IntermediateVT, RegisterVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000528 unsigned NumIntermediates;
Owen Anderson23b9b192009-08-12 00:36:31 +0000529 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
Devang Patel8f09bea2010-08-26 20:32:32 +0000530 IntermediateVT,
531 NumIntermediates, RegisterVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000532 unsigned NumElements = ValueVT.getVectorNumElements();
Michael J. Spencere70c5262010-10-16 08:25:21 +0000533
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000534 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
535 NumParts = NumRegs; // Silence a compiler warning.
536 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
Michael J. Spencere70c5262010-10-16 08:25:21 +0000537
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000538 // Split the vector into intermediate operands.
539 SmallVector<SDValue, 8> Ops(NumIntermediates);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000540 for (unsigned i = 0; i != NumIntermediates; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000541 if (IntermediateVT.isVector())
Chris Lattnera13b8602010-08-24 23:10:06 +0000542 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000543 IntermediateVT, Val,
Chris Lattnera13b8602010-08-24 23:10:06 +0000544 DAG.getIntPtrConstant(i * (NumElements / NumIntermediates)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000545 else
Chris Lattnera13b8602010-08-24 23:10:06 +0000546 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
Chris Lattnere6f7c262010-08-25 22:49:25 +0000547 IntermediateVT, Val, DAG.getIntPtrConstant(i));
Bill Wendling3ea3c242009-12-22 02:10:19 +0000548 }
Michael J. Spencere70c5262010-10-16 08:25:21 +0000549
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000550 // Split the intermediate operands into legal parts.
551 if (NumParts == NumIntermediates) {
552 // If the register was not expanded, promote or copy the value,
553 // as appropriate.
554 for (unsigned i = 0; i != NumParts; ++i)
Bill Wendlingf18eb582012-09-26 06:16:18 +0000555 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT, V);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000556 } else if (NumParts > 0) {
557 // If the intermediate type was expanded, split each the value into
558 // legal parts.
559 assert(NumParts % NumIntermediates == 0 &&
560 "Must expand into a divisible number of parts!");
561 unsigned Factor = NumParts / NumIntermediates;
562 for (unsigned i = 0; i != NumIntermediates; ++i)
Bill Wendlingf18eb582012-09-26 06:16:18 +0000563 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT, V);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000564 }
565}
566
Dan Gohman462f6b52010-05-29 17:53:24 +0000567namespace {
568 /// RegsForValue - This struct represents the registers (physical or virtual)
569 /// that a particular set of values is assigned, and the type information
570 /// about the value. The most common situation is to represent one value at a
571 /// time, but struct or array values are handled element-wise as multiple
572 /// values. The splitting of aggregates is performed recursively, so that we
573 /// never have aggregate-typed registers. The values at this point do not
574 /// necessarily have legal types, so each value may require one or more
575 /// registers of some legal type.
576 ///
577 struct RegsForValue {
578 /// ValueVTs - The value types of the values, which may not be legal, and
579 /// may need be promoted or synthesized from one or more registers.
580 ///
581 SmallVector<EVT, 4> ValueVTs;
582
583 /// RegVTs - The value types of the registers. This is the same size as
584 /// ValueVTs and it records, for each value, what the type of the assigned
585 /// register or registers are. (Individual values are never synthesized
586 /// from more than one type of register.)
587 ///
588 /// With virtual registers, the contents of RegVTs is redundant with TLI's
589 /// getRegisterType member function, however when with physical registers
590 /// it is necessary to have a separate record of the types.
591 ///
592 SmallVector<EVT, 4> RegVTs;
593
594 /// Regs - This list holds the registers assigned to the values.
595 /// Each legal or promoted value requires one register, and each
596 /// expanded value requires multiple registers.
597 ///
598 SmallVector<unsigned, 4> Regs;
599
600 RegsForValue() {}
601
602 RegsForValue(const SmallVector<unsigned, 4> &regs,
603 EVT regvt, EVT valuevt)
604 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
605
Dan Gohman462f6b52010-05-29 17:53:24 +0000606 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000607 unsigned Reg, Type *Ty) {
Dan Gohman462f6b52010-05-29 17:53:24 +0000608 ComputeValueVTs(tli, Ty, ValueVTs);
609
610 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
611 EVT ValueVT = ValueVTs[Value];
612 unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
613 EVT RegisterVT = tli.getRegisterType(Context, ValueVT);
614 for (unsigned i = 0; i != NumRegs; ++i)
615 Regs.push_back(Reg + i);
616 RegVTs.push_back(RegisterVT);
617 Reg += NumRegs;
618 }
619 }
620
621 /// areValueTypesLegal - Return true if types of all the values are legal.
622 bool areValueTypesLegal(const TargetLowering &TLI) {
623 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
624 EVT RegisterVT = RegVTs[Value];
625 if (!TLI.isTypeLegal(RegisterVT))
626 return false;
627 }
628 return true;
629 }
630
631 /// append - Add the specified values to this one.
632 void append(const RegsForValue &RHS) {
633 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
634 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
635 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
636 }
637
638 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
639 /// this value and returns the result as a ValueVTs value. This uses
640 /// Chain/Flag as the input and updates them for the output Chain/Flag.
641 /// If the Flag pointer is NULL, no flag is used.
642 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
643 DebugLoc dl,
Bill Wendling12931302012-09-26 04:04:19 +0000644 SDValue &Chain, SDValue *Flag,
645 const Value *V = 0) const;
Dan Gohman462f6b52010-05-29 17:53:24 +0000646
647 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
648 /// specified value into the registers specified by this object. This uses
649 /// Chain/Flag as the input and updates them for the output Chain/Flag.
650 /// If the Flag pointer is NULL, no flag is used.
651 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Bill Wendlingf18eb582012-09-26 06:16:18 +0000652 SDValue &Chain, SDValue *Flag, const Value *V) const;
Dan Gohman462f6b52010-05-29 17:53:24 +0000653
654 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
655 /// operand list. This adds the code marker, matching input operand index
656 /// (if applicable), and includes the number of values added into it.
657 void AddInlineAsmOperands(unsigned Kind,
658 bool HasMatching, unsigned MatchingIdx,
659 SelectionDAG &DAG,
660 std::vector<SDValue> &Ops) const;
661 };
662}
663
664/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
665/// this value and returns the result as a ValueVT value. This uses
666/// Chain/Flag as the input and updates them for the output Chain/Flag.
667/// If the Flag pointer is NULL, no flag is used.
668SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
669 FunctionLoweringInfo &FuncInfo,
670 DebugLoc dl,
Bill Wendling12931302012-09-26 04:04:19 +0000671 SDValue &Chain, SDValue *Flag,
672 const Value *V) const {
Dan Gohman7da5d3f2010-07-26 18:15:41 +0000673 // A Value with type {} or [0 x %t] needs no registers.
674 if (ValueVTs.empty())
675 return SDValue();
676
Dan Gohman462f6b52010-05-29 17:53:24 +0000677 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
678
679 // Assemble the legal parts into the final values.
680 SmallVector<SDValue, 4> Values(ValueVTs.size());
681 SmallVector<SDValue, 8> Parts;
682 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
683 // Copy the legal parts from the registers.
684 EVT ValueVT = ValueVTs[Value];
685 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
686 EVT RegisterVT = RegVTs[Value];
687
688 Parts.resize(NumRegs);
689 for (unsigned i = 0; i != NumRegs; ++i) {
690 SDValue P;
691 if (Flag == 0) {
692 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
693 } else {
694 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
695 *Flag = P.getValue(2);
696 }
697
698 Chain = P.getValue(1);
Chris Lattnerd5b4db92010-12-13 01:11:17 +0000699 Parts[i] = P;
Dan Gohman462f6b52010-05-29 17:53:24 +0000700
701 // If the source register was virtual and if we know something about it,
702 // add an assert node.
Chris Lattnerd5b4db92010-12-13 01:11:17 +0000703 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
Cameron Zwariche1497b92011-02-24 10:00:08 +0000704 !RegisterVT.isInteger() || RegisterVT.isVector())
Chris Lattnerd5b4db92010-12-13 01:11:17 +0000705 continue;
Cameron Zwariche1497b92011-02-24 10:00:08 +0000706
707 const FunctionLoweringInfo::LiveOutInfo *LOI =
708 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
709 if (!LOI)
710 continue;
Dan Gohman462f6b52010-05-29 17:53:24 +0000711
Chris Lattnerd5b4db92010-12-13 01:11:17 +0000712 unsigned RegSize = RegisterVT.getSizeInBits();
Cameron Zwariche1497b92011-02-24 10:00:08 +0000713 unsigned NumSignBits = LOI->NumSignBits;
714 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
Dan Gohman462f6b52010-05-29 17:53:24 +0000715
Chris Lattnerd5b4db92010-12-13 01:11:17 +0000716 // FIXME: We capture more information than the dag can represent. For
717 // now, just use the tightest assertzext/assertsext possible.
718 bool isSExt = true;
719 EVT FromVT(MVT::Other);
720 if (NumSignBits == RegSize)
721 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
722 else if (NumZeroBits >= RegSize-1)
723 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
724 else if (NumSignBits > RegSize-8)
725 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
726 else if (NumZeroBits >= RegSize-8)
727 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
728 else if (NumSignBits > RegSize-16)
729 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
730 else if (NumZeroBits >= RegSize-16)
731 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
732 else if (NumSignBits > RegSize-32)
733 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
734 else if (NumZeroBits >= RegSize-32)
735 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
736 else
737 continue;
Dan Gohman462f6b52010-05-29 17:53:24 +0000738
Chris Lattnerd5b4db92010-12-13 01:11:17 +0000739 // Add an assertion node.
740 assert(FromVT != MVT::Other);
741 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
742 RegisterVT, P, DAG.getValueType(FromVT));
Dan Gohman462f6b52010-05-29 17:53:24 +0000743 }
744
745 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
Bill Wendling12931302012-09-26 04:04:19 +0000746 NumRegs, RegisterVT, ValueVT, V);
Dan Gohman462f6b52010-05-29 17:53:24 +0000747 Part += NumRegs;
748 Parts.clear();
749 }
750
751 return DAG.getNode(ISD::MERGE_VALUES, dl,
752 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
753 &Values[0], ValueVTs.size());
754}
755
756/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
757/// specified value into the registers specified by this object. This uses
758/// Chain/Flag as the input and updates them for the output Chain/Flag.
759/// If the Flag pointer is NULL, no flag is used.
760void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Bill Wendlingf18eb582012-09-26 06:16:18 +0000761 SDValue &Chain, SDValue *Flag,
762 const Value *V) const {
Dan Gohman462f6b52010-05-29 17:53:24 +0000763 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
764
765 // Get the list of the values's legal parts.
766 unsigned NumRegs = Regs.size();
767 SmallVector<SDValue, 8> Parts(NumRegs);
768 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
769 EVT ValueVT = ValueVTs[Value];
770 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
771 EVT RegisterVT = RegVTs[Value];
772
Chris Lattner3ac18842010-08-24 23:20:40 +0000773 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
Bill Wendlingf18eb582012-09-26 06:16:18 +0000774 &Parts[Part], NumParts, RegisterVT, V);
Dan Gohman462f6b52010-05-29 17:53:24 +0000775 Part += NumParts;
776 }
777
778 // Copy the parts into the registers.
779 SmallVector<SDValue, 8> Chains(NumRegs);
780 for (unsigned i = 0; i != NumRegs; ++i) {
781 SDValue Part;
782 if (Flag == 0) {
783 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
784 } else {
785 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
786 *Flag = Part.getValue(1);
787 }
788
789 Chains[i] = Part.getValue(0);
790 }
791
792 if (NumRegs == 1 || Flag)
793 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
794 // flagged to it. That is the CopyToReg nodes and the user are considered
795 // a single scheduling unit. If we create a TokenFactor and return it as
796 // chain, then the TokenFactor is both a predecessor (operand) of the
797 // user as well as a successor (the TF operands are flagged to the user).
798 // c1, f1 = CopyToReg
799 // c2, f2 = CopyToReg
800 // c3 = TokenFactor c1, c2
801 // ...
802 // = op c3, ..., f2
803 Chain = Chains[NumRegs-1];
804 else
805 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
806}
807
808/// AddInlineAsmOperands - Add this value to the specified inlineasm node
809/// operand list. This adds the code marker and includes the number of
810/// values added into it.
811void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
812 unsigned MatchingIdx,
813 SelectionDAG &DAG,
814 std::vector<SDValue> &Ops) const {
815 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
816
817 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
818 if (HasMatching)
819 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
Jakob Stoklund Olesen459b74b2011-10-12 23:37:29 +0000820 else if (!Regs.empty() &&
821 TargetRegisterInfo::isVirtualRegister(Regs.front())) {
822 // Put the register class of the virtual registers in the flag word. That
823 // way, later passes can recompute register class constraints for inline
824 // assembly as well as normal instructions.
825 // Don't do this for tied operands that can use the regclass information
826 // from the def.
827 const MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
828 const TargetRegisterClass *RC = MRI.getRegClass(Regs.front());
829 Flag = InlineAsm::getFlagWordForRegClass(Flag, RC->getID());
830 }
831
Dan Gohman462f6b52010-05-29 17:53:24 +0000832 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
833 Ops.push_back(Res);
834
835 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
836 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
837 EVT RegisterVT = RegVTs[Value];
838 for (unsigned i = 0; i != NumRegs; ++i) {
839 assert(Reg < Regs.size() && "Mismatch in # registers expected");
840 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
841 }
842 }
843}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000844
Owen Anderson243eb9e2011-12-08 22:15:21 +0000845void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa,
846 const TargetLibraryInfo *li) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000847 AA = &aa;
848 GFI = gfi;
Owen Anderson243eb9e2011-12-08 22:15:21 +0000849 LibInfo = li;
Micah Villmow3574eca2012-10-08 16:38:25 +0000850 TD = DAG.getTarget().getDataLayout();
Richard Smithcb1f68d2012-08-22 00:42:39 +0000851 Context = DAG.getContext();
Bill Wendling4ed1fb02011-10-15 01:00:26 +0000852 LPadToCallSiteMap.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000853}
854
Dan Gohmanb02b62a2010-04-14 18:24:06 +0000855/// clear - Clear out the current SelectionDAG and the associated
Dan Gohman2048b852009-11-23 18:04:58 +0000856/// state and prepare this SelectionDAGBuilder object to be used
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000857/// for a new block. This doesn't clear out information about
858/// additional blocks that are needed to complete switch lowering
859/// or PHI node updating; that information is cleared out as it is
860/// consumed.
Dan Gohman2048b852009-11-23 18:04:58 +0000861void SelectionDAGBuilder::clear() {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000862 NodeMap.clear();
Devang Patel9126c0d2010-06-01 19:59:01 +0000863 UnusedArgNodeMap.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000864 PendingLoads.clear();
865 PendingExports.clear();
Chris Lattnera4f2bb02010-04-02 20:17:23 +0000866 CurDebugLoc = DebugLoc();
Dan Gohman98ca4f22009-08-05 01:29:28 +0000867 HasTailCall = false;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000868}
869
Devang Patel23385752011-05-23 17:44:13 +0000870/// clearDanglingDebugInfo - Clear the dangling debug information
Benjamin Kramerd9b0b022012-06-02 10:20:22 +0000871/// map. This function is separated from the clear so that debug
Devang Patel23385752011-05-23 17:44:13 +0000872/// information that is dangling in a basic block can be properly
873/// resolved in a different basic block. This allows the
874/// SelectionDAG to resolve dangling debug information attached
875/// to PHI nodes.
876void SelectionDAGBuilder::clearDanglingDebugInfo() {
877 DanglingDebugInfoMap.clear();
878}
879
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000880/// getRoot - Return the current virtual root of the Selection DAG,
881/// flushing any PendingLoad items. This must be done before emitting
882/// a store or any other node that may need to be ordered after any
883/// prior load instructions.
884///
Dan Gohman2048b852009-11-23 18:04:58 +0000885SDValue SelectionDAGBuilder::getRoot() {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000886 if (PendingLoads.empty())
887 return DAG.getRoot();
888
889 if (PendingLoads.size() == 1) {
890 SDValue Root = PendingLoads[0];
891 DAG.setRoot(Root);
892 PendingLoads.clear();
893 return Root;
894 }
895
896 // Otherwise, we have to make a token factor node.
Owen Anderson825b72b2009-08-11 20:47:22 +0000897 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000898 &PendingLoads[0], PendingLoads.size());
899 PendingLoads.clear();
900 DAG.setRoot(Root);
901 return Root;
902}
903
904/// getControlRoot - Similar to getRoot, but instead of flushing all the
905/// PendingLoad items, flush all the PendingExports items. It is necessary
906/// to do this before emitting a terminator instruction.
907///
Dan Gohman2048b852009-11-23 18:04:58 +0000908SDValue SelectionDAGBuilder::getControlRoot() {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000909 SDValue Root = DAG.getRoot();
910
911 if (PendingExports.empty())
912 return Root;
913
914 // Turn all of the CopyToReg chains into one factored node.
915 if (Root.getOpcode() != ISD::EntryToken) {
916 unsigned i = 0, e = PendingExports.size();
917 for (; i != e; ++i) {
918 assert(PendingExports[i].getNode()->getNumOperands() > 1);
919 if (PendingExports[i].getNode()->getOperand(0) == Root)
920 break; // Don't add the root if we already indirectly depend on it.
921 }
922
923 if (i == e)
924 PendingExports.push_back(Root);
925 }
926
Owen Anderson825b72b2009-08-11 20:47:22 +0000927 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000928 &PendingExports[0],
929 PendingExports.size());
930 PendingExports.clear();
931 DAG.setRoot(Root);
932 return Root;
933}
934
Bill Wendling4533cac2010-01-28 21:51:40 +0000935void SelectionDAGBuilder::AssignOrderingToNode(const SDNode *Node) {
936 if (DAG.GetOrdering(Node) != 0) return; // Already has ordering.
937 DAG.AssignOrdering(Node, SDNodeOrder);
938
939 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)
940 AssignOrderingToNode(Node->getOperand(I).getNode());
941}
942
Dan Gohman46510a72010-04-15 01:51:59 +0000943void SelectionDAGBuilder::visit(const Instruction &I) {
Dan Gohmanc105a2b2010-04-22 20:55:53 +0000944 // Set up outgoing PHI node register values before emitting the terminator.
945 if (isa<TerminatorInst>(&I))
946 HandlePHINodesInSuccessorBlocks(I.getParent());
947
Dan Gohman8ba3aa72010-04-20 00:48:35 +0000948 CurDebugLoc = I.getDebugLoc();
949
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000950 visit(I.getOpcode(), I);
Dan Gohman8ba3aa72010-04-20 00:48:35 +0000951
Dan Gohman92884f72010-04-20 15:03:56 +0000952 if (!isa<TerminatorInst>(&I) && !HasTailCall)
953 CopyToExportRegsIfNeeded(&I);
954
Dan Gohman8ba3aa72010-04-20 00:48:35 +0000955 CurDebugLoc = DebugLoc();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000956}
957
Dan Gohmanba5be5c2010-04-20 15:00:41 +0000958void SelectionDAGBuilder::visitPHI(const PHINode &) {
959 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
960}
961
Dan Gohman46510a72010-04-15 01:51:59 +0000962void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000963 // Note: this doesn't use InstVisitor, because it has to work with
964 // ConstantExpr's in addition to instructions.
965 switch (Opcode) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000966 default: llvm_unreachable("Unknown instruction type encountered!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000967 // Build the switch statement using the Instruction.def file.
968#define HANDLE_INST(NUM, OPCODE, CLASS) \
Galina Kistanova72ea0c92012-07-19 04:50:12 +0000969 case Instruction::OPCODE: visit##OPCODE((const CLASS&)I); break;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000970#include "llvm/Instruction.def"
971 }
Bill Wendling4533cac2010-01-28 21:51:40 +0000972
973 // Assign the ordering to the freshly created DAG nodes.
974 if (NodeMap.count(&I)) {
975 ++SDNodeOrder;
976 AssignOrderingToNode(getValue(&I).getNode());
977 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000978}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000979
Dale Johannesenbdc09d92010-07-16 00:02:08 +0000980// resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
981// generate the debug data structures now that we've seen its definition.
982void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
983 SDValue Val) {
984 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
Devang Patel4cf81c42010-08-26 23:35:15 +0000985 if (DDI.getDI()) {
986 const DbgValueInst *DI = DDI.getDI();
Dale Johannesenbdc09d92010-07-16 00:02:08 +0000987 DebugLoc dl = DDI.getdl();
988 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
Devang Patel4cf81c42010-08-26 23:35:15 +0000989 MDNode *Variable = DI->getVariable();
990 uint64_t Offset = DI->getOffset();
Dale Johannesenbdc09d92010-07-16 00:02:08 +0000991 SDDbgValue *SDV;
992 if (Val.getNode()) {
Devang Patel78a06e52010-08-25 20:39:26 +0000993 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, Val)) {
Dale Johannesenbdc09d92010-07-16 00:02:08 +0000994 SDV = DAG.getDbgValue(Variable, Val.getNode(),
995 Val.getResNo(), Offset, dl, DbgSDNodeOrder);
996 DAG.AddDbgValue(SDV, Val.getNode(), false);
997 }
Owen Anderson95771af2011-02-25 21:41:48 +0000998 } else
Eric Christopher0822e012012-02-23 03:39:43 +0000999 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Dale Johannesenbdc09d92010-07-16 00:02:08 +00001000 DanglingDebugInfoMap[V] = DanglingDebugInfo();
1001 }
1002}
1003
Nick Lewycky8de34002011-09-30 22:19:53 +00001004/// getValue - Return an SDValue for the given Value.
Dan Gohman2048b852009-11-23 18:04:58 +00001005SDValue SelectionDAGBuilder::getValue(const Value *V) {
Dan Gohman28a17352010-07-01 01:59:43 +00001006 // If we already have an SDValue for this value, use it. It's important
1007 // to do this first, so that we don't create a CopyFromReg if we already
1008 // have a regular SDValue.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001009 SDValue &N = NodeMap[V];
1010 if (N.getNode()) return N;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001011
Dan Gohman28a17352010-07-01 01:59:43 +00001012 // If there's a virtual register allocated and initialized for this
1013 // value, use it.
1014 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
1015 if (It != FuncInfo.ValueMap.end()) {
1016 unsigned InReg = It->second;
1017 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
1018 SDValue Chain = DAG.getEntryNode();
Bill Wendling12931302012-09-26 04:04:19 +00001019 N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain, NULL, V);
Devang Patel8f314282011-01-25 18:09:58 +00001020 resolveDanglingDebugInfo(V, N);
1021 return N;
Dan Gohman28a17352010-07-01 01:59:43 +00001022 }
1023
1024 // Otherwise create a new SDValue and remember it.
1025 SDValue Val = getValueImpl(V);
1026 NodeMap[V] = Val;
Dale Johannesenbdc09d92010-07-16 00:02:08 +00001027 resolveDanglingDebugInfo(V, Val);
Dan Gohman28a17352010-07-01 01:59:43 +00001028 return Val;
1029}
1030
1031/// getNonRegisterValue - Return an SDValue for the given Value, but
1032/// don't look in FuncInfo.ValueMap for a virtual register.
1033SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
1034 // If we already have an SDValue for this value, use it.
1035 SDValue &N = NodeMap[V];
1036 if (N.getNode()) return N;
1037
1038 // Otherwise create a new SDValue and remember it.
1039 SDValue Val = getValueImpl(V);
1040 NodeMap[V] = Val;
Dale Johannesenbdc09d92010-07-16 00:02:08 +00001041 resolveDanglingDebugInfo(V, Val);
Dan Gohman28a17352010-07-01 01:59:43 +00001042 return Val;
1043}
1044
Dale Johannesenbdc09d92010-07-16 00:02:08 +00001045/// getValueImpl - Helper function for getValue and getNonRegisterValue.
Dan Gohman28a17352010-07-01 01:59:43 +00001046/// Create an SDValue for the given value.
1047SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
Dan Gohman383b5f62010-04-17 15:32:28 +00001048 if (const Constant *C = dyn_cast<Constant>(V)) {
Owen Andersone50ed302009-08-10 22:56:29 +00001049 EVT VT = TLI.getValueType(V->getType(), true);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001050
Dan Gohman383b5f62010-04-17 15:32:28 +00001051 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohman28a17352010-07-01 01:59:43 +00001052 return DAG.getConstant(*CI, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001053
Dan Gohman383b5f62010-04-17 15:32:28 +00001054 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
Devang Patel0d881da2010-07-06 22:08:15 +00001055 return DAG.getGlobalAddress(GV, getCurDebugLoc(), VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001056
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001057 if (isa<ConstantPointerNull>(C))
Dan Gohman28a17352010-07-01 01:59:43 +00001058 return DAG.getConstant(0, TLI.getPointerTy());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001059
Dan Gohman383b5f62010-04-17 15:32:28 +00001060 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohman28a17352010-07-01 01:59:43 +00001061 return DAG.getConstantFP(*CFP, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001062
Nate Begeman9008ca62009-04-27 18:41:29 +00001063 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
Dan Gohman28a17352010-07-01 01:59:43 +00001064 return DAG.getUNDEF(VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001065
Dan Gohman383b5f62010-04-17 15:32:28 +00001066 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001067 visit(CE->getOpcode(), *CE);
1068 SDValue N1 = NodeMap[V];
Dan Gohmanac7d05c2010-04-16 16:55:18 +00001069 assert(N1.getNode() && "visit didn't populate the NodeMap!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001070 return N1;
1071 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001072
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001073 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1074 SmallVector<SDValue, 4> Constants;
1075 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1076 OI != OE; ++OI) {
1077 SDNode *Val = getValue(*OI).getNode();
Dan Gohmaned48caf2009-09-08 01:44:02 +00001078 // If the operand is an empty aggregate, there are no values.
1079 if (!Val) continue;
1080 // Add each leaf value from the operand to the Constants list
1081 // to form a flattened list of all the values.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001082 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1083 Constants.push_back(SDValue(Val, i));
1084 }
Bill Wendling87710f02009-12-21 23:47:40 +00001085
Bill Wendling4533cac2010-01-28 21:51:40 +00001086 return DAG.getMergeValues(&Constants[0], Constants.size(),
1087 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001088 }
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001089
1090 if (const ConstantDataSequential *CDS =
1091 dyn_cast<ConstantDataSequential>(C)) {
1092 SmallVector<SDValue, 4> Ops;
Chris Lattner0f193b82012-01-25 01:27:20 +00001093 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001094 SDNode *Val = getValue(CDS->getElementAsConstant(i)).getNode();
1095 // Add each leaf value from the operand to the Constants list
1096 // to form a flattened list of all the values.
1097 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1098 Ops.push_back(SDValue(Val, i));
1099 }
1100
1101 if (isa<ArrayType>(CDS->getType()))
1102 return DAG.getMergeValues(&Ops[0], Ops.size(), getCurDebugLoc());
1103 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
1104 VT, &Ops[0], Ops.size());
1105 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001106
Duncan Sands1df98592010-02-16 11:11:14 +00001107 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001108 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1109 "Unknown struct or array constant!");
1110
Owen Andersone50ed302009-08-10 22:56:29 +00001111 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001112 ComputeValueVTs(TLI, C->getType(), ValueVTs);
1113 unsigned NumElts = ValueVTs.size();
1114 if (NumElts == 0)
1115 return SDValue(); // empty struct
1116 SmallVector<SDValue, 4> Constants(NumElts);
1117 for (unsigned i = 0; i != NumElts; ++i) {
Owen Andersone50ed302009-08-10 22:56:29 +00001118 EVT EltVT = ValueVTs[i];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001119 if (isa<UndefValue>(C))
Dale Johannesene8d72302009-02-06 23:05:02 +00001120 Constants[i] = DAG.getUNDEF(EltVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001121 else if (EltVT.isFloatingPoint())
1122 Constants[i] = DAG.getConstantFP(0, EltVT);
1123 else
1124 Constants[i] = DAG.getConstant(0, EltVT);
1125 }
Bill Wendling87710f02009-12-21 23:47:40 +00001126
Bill Wendling4533cac2010-01-28 21:51:40 +00001127 return DAG.getMergeValues(&Constants[0], NumElts,
1128 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001129 }
1130
Dan Gohman383b5f62010-04-17 15:32:28 +00001131 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
Dan Gohman29cbade2009-11-20 23:18:13 +00001132 return DAG.getBlockAddress(BA, VT);
Dan Gohman8c2b5252009-10-30 01:27:03 +00001133
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001134 VectorType *VecTy = cast<VectorType>(V->getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001135 unsigned NumElements = VecTy->getNumElements();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001136
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001137 // Now that we know the number and type of the elements, get that number of
1138 // elements into the Ops array based on what kind of constant it is.
1139 SmallVector<SDValue, 16> Ops;
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001140 if (const ConstantVector *CV = dyn_cast<ConstantVector>(C)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001141 for (unsigned i = 0; i != NumElements; ++i)
Chris Lattner1ee0ecf2012-01-24 13:41:11 +00001142 Ops.push_back(getValue(CV->getOperand(i)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001143 } else {
Nate Begeman9008ca62009-04-27 18:41:29 +00001144 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
Owen Andersone50ed302009-08-10 22:56:29 +00001145 EVT EltVT = TLI.getValueType(VecTy->getElementType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001146
1147 SDValue Op;
Nate Begeman9008ca62009-04-27 18:41:29 +00001148 if (EltVT.isFloatingPoint())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001149 Op = DAG.getConstantFP(0, EltVT);
1150 else
1151 Op = DAG.getConstant(0, EltVT);
1152 Ops.assign(NumElements, Op);
1153 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001154
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001155 // Create a BUILD_VECTOR node.
Bill Wendling4533cac2010-01-28 21:51:40 +00001156 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
1157 VT, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001158 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001159
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001160 // If this is a static alloca, generate it as the frameindex instead of
1161 // computation.
1162 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1163 DenseMap<const AllocaInst*, int>::iterator SI =
1164 FuncInfo.StaticAllocaMap.find(AI);
1165 if (SI != FuncInfo.StaticAllocaMap.end())
1166 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1167 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001168
Dan Gohman28a17352010-07-01 01:59:43 +00001169 // If this is an instruction which fast-isel has deferred, select it now.
1170 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
Dan Gohman84023e02010-07-10 09:00:22 +00001171 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1172 RegsForValue RFV(*DAG.getContext(), TLI, InReg, Inst->getType());
1173 SDValue Chain = DAG.getEntryNode();
Bill Wendling12931302012-09-26 04:04:19 +00001174 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain, NULL, V);
Dan Gohman28a17352010-07-01 01:59:43 +00001175 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001176
Dan Gohman28a17352010-07-01 01:59:43 +00001177 llvm_unreachable("Can't get register for value!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001178}
1179
Dan Gohman46510a72010-04-15 01:51:59 +00001180void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
Dan Gohman98ca4f22009-08-05 01:29:28 +00001181 SDValue Chain = getControlRoot();
1182 SmallVector<ISD::OutputArg, 8> Outs;
Dan Gohmanc9403652010-07-07 15:54:55 +00001183 SmallVector<SDValue, 8> OutVals;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00001184
Dan Gohman7451d3e2010-05-29 17:03:36 +00001185 if (!FuncInfo.CanLowerReturn) {
1186 unsigned DemoteReg = FuncInfo.DemoteRegister;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001187 const Function *F = I.getParent()->getParent();
1188
1189 // Emit a store of the return value through the virtual register.
1190 // Leave Outs empty so that LowerReturn won't try to load return
1191 // registers the usual way.
1192 SmallVector<EVT, 1> PtrValueVTs;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00001193 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001194 PtrValueVTs);
1195
1196 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1197 SDValue RetOp = getValue(I.getOperand(0));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00001198
Owen Andersone50ed302009-08-10 22:56:29 +00001199 SmallVector<EVT, 4> ValueVTs;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001200 SmallVector<uint64_t, 4> Offsets;
1201 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
Dan Gohman7ea1ca62008-10-21 20:00:42 +00001202 unsigned NumValues = ValueVTs.size();
Dan Gohman7ea1ca62008-10-21 20:00:42 +00001203
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001204 SmallVector<SDValue, 4> Chains(NumValues);
Bill Wendling87710f02009-12-21 23:47:40 +00001205 for (unsigned i = 0; i != NumValues; ++i) {
Chris Lattnera13b8602010-08-24 23:10:06 +00001206 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(),
1207 RetPtr.getValueType(), RetPtr,
1208 DAG.getIntPtrConstant(Offsets[i]));
Bill Wendling87710f02009-12-21 23:47:40 +00001209 Chains[i] =
1210 DAG.getStore(Chain, getCurDebugLoc(),
1211 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
Chris Lattner84bd98a2010-09-21 18:58:22 +00001212 // FIXME: better loc info would be nice.
1213 Add, MachinePointerInfo(), false, false, 0);
Bill Wendling87710f02009-12-21 23:47:40 +00001214 }
1215
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001216 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
1217 MVT::Other, &Chains[0], NumValues);
Chris Lattner25d58372010-02-28 18:53:13 +00001218 } else if (I.getNumOperands() != 0) {
1219 SmallVector<EVT, 4> ValueVTs;
1220 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
1221 unsigned NumValues = ValueVTs.size();
1222 if (NumValues) {
1223 SDValue RetOp = getValue(I.getOperand(0));
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001224 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1225 EVT VT = ValueVTs[j];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001226
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001227 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001228
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001229 const Function *F = I.getParent()->getParent();
Bill Wendling67658342012-10-09 07:45:08 +00001230 if (F->getRetAttributes().hasAttribute(Attributes::SExt))
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001231 ExtendKind = ISD::SIGN_EXTEND;
Bill Wendling67658342012-10-09 07:45:08 +00001232 else if (F->getRetAttributes().hasAttribute(Attributes::ZExt))
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001233 ExtendKind = ISD::ZERO_EXTEND;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001234
Cameron Zwarich7bbf0ee2011-03-17 14:53:37 +00001235 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1236 VT = TLI.getTypeForExtArgOrReturn(*DAG.getContext(), VT, ExtendKind);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001237
1238 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
1239 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
1240 SmallVector<SDValue, 4> Parts(NumParts);
Bill Wendling46ada192010-03-02 01:55:18 +00001241 getCopyToParts(DAG, getCurDebugLoc(),
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001242 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
Bill Wendlingf18eb582012-09-26 06:16:18 +00001243 &Parts[0], NumParts, PartVT, &I, ExtendKind);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001244
1245 // 'inreg' on function refers to return value
1246 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Bill Wendling67658342012-10-09 07:45:08 +00001247 if (F->getRetAttributes().hasAttribute(Attributes::InReg))
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001248 Flags.setInReg();
1249
1250 // Propagate extension type if any
Cameron Zwarich8df6bf52011-03-16 22:20:07 +00001251 if (ExtendKind == ISD::SIGN_EXTEND)
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001252 Flags.setSExt();
Cameron Zwarich8df6bf52011-03-16 22:20:07 +00001253 else if (ExtendKind == ISD::ZERO_EXTEND)
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00001254 Flags.setZExt();
1255
Dan Gohmanc9403652010-07-07 15:54:55 +00001256 for (unsigned i = 0; i < NumParts; ++i) {
1257 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
Manman Ren0a1544d2012-11-01 23:49:58 +00001258 /*isfixed=*/true, 0, 0));
Dan Gohmanc9403652010-07-07 15:54:55 +00001259 OutVals.push_back(Parts[i]);
1260 }
Evan Cheng3927f432009-03-25 20:20:11 +00001261 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001262 }
1263 }
Dan Gohman98ca4f22009-08-05 01:29:28 +00001264
1265 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00001266 CallingConv::ID CallConv =
1267 DAG.getMachineFunction().getFunction()->getCallingConv();
Dan Gohman98ca4f22009-08-05 01:29:28 +00001268 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
Dan Gohmanc9403652010-07-07 15:54:55 +00001269 Outs, OutVals, getCurDebugLoc(), DAG);
Dan Gohman5e866062009-08-06 15:37:27 +00001270
1271 // Verify that the target's LowerReturn behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +00001272 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00001273 "LowerReturn didn't return a valid chain!");
1274
1275 // Update the DAG with the new chain value resulting from return lowering.
Dan Gohman98ca4f22009-08-05 01:29:28 +00001276 DAG.setRoot(Chain);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001277}
1278
Dan Gohmanad62f532009-04-23 23:13:24 +00001279/// CopyToExportRegsIfNeeded - If the given value has virtual registers
1280/// created for it, emit nodes to copy the value into the virtual
1281/// registers.
Dan Gohman46510a72010-04-15 01:51:59 +00001282void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
Rafael Espindola3fa82832011-05-13 15:18:06 +00001283 // Skip empty types
1284 if (V->getType()->isEmptyTy())
1285 return;
1286
Dan Gohman33b7a292010-04-16 17:15:02 +00001287 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1288 if (VMI != FuncInfo.ValueMap.end()) {
1289 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1290 CopyValueToVirtualRegister(V, VMI->second);
Dan Gohmanad62f532009-04-23 23:13:24 +00001291 }
1292}
1293
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001294/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1295/// the current basic block, add it to ValueMap now so that we'll get a
1296/// CopyTo/FromReg.
Dan Gohman46510a72010-04-15 01:51:59 +00001297void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001298 // No need to export constants.
1299 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001300
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001301 // Already exported?
1302 if (FuncInfo.isExportedInst(V)) return;
1303
1304 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1305 CopyValueToVirtualRegister(V, Reg);
1306}
1307
Dan Gohman46510a72010-04-15 01:51:59 +00001308bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
Dan Gohman2048b852009-11-23 18:04:58 +00001309 const BasicBlock *FromBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001310 // The operands of the setcc have to be in this block. We don't know
1311 // how to export them from some other block.
Dan Gohman46510a72010-04-15 01:51:59 +00001312 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001313 // Can export from current BB.
1314 if (VI->getParent() == FromBB)
1315 return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001316
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001317 // Is already exported, noop.
1318 return FuncInfo.isExportedInst(V);
1319 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001320
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001321 // If this is an argument, we can export it if the BB is the entry block or
1322 // if it is already exported.
1323 if (isa<Argument>(V)) {
1324 if (FromBB == &FromBB->getParent()->getEntryBlock())
1325 return true;
1326
1327 // Otherwise, can only export this if it is already exported.
1328 return FuncInfo.isExportedInst(V);
1329 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001330
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001331 // Otherwise, constants can always be exported.
1332 return true;
1333}
1334
Jakub Staszak7cc2b072011-06-16 20:22:37 +00001335/// Return branch probability calculated by BranchProbabilityInfo for IR blocks.
Jakub Staszak25101bb2011-12-20 20:03:10 +00001336uint32_t SelectionDAGBuilder::getEdgeWeight(const MachineBasicBlock *Src,
1337 const MachineBasicBlock *Dst) const {
Jakub Staszak7cc2b072011-06-16 20:22:37 +00001338 BranchProbabilityInfo *BPI = FuncInfo.BPI;
1339 if (!BPI)
1340 return 0;
Jakub Staszak95ece8e2011-07-29 20:05:36 +00001341 const BasicBlock *SrcBB = Src->getBasicBlock();
1342 const BasicBlock *DstBB = Dst->getBasicBlock();
Jakub Staszak7cc2b072011-06-16 20:22:37 +00001343 return BPI->getEdgeWeight(SrcBB, DstBB);
1344}
1345
Jakub Staszakc8f34de2011-07-29 22:25:21 +00001346void SelectionDAGBuilder::
1347addSuccessorWithWeight(MachineBasicBlock *Src, MachineBasicBlock *Dst,
1348 uint32_t Weight /* = 0 */) {
1349 if (!Weight)
1350 Weight = getEdgeWeight(Src, Dst);
1351 Src->addSuccessor(Dst, Weight);
Jakub Staszak7cc2b072011-06-16 20:22:37 +00001352}
1353
1354
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001355static bool InBlock(const Value *V, const BasicBlock *BB) {
1356 if (const Instruction *I = dyn_cast<Instruction>(V))
1357 return I->getParent() == BB;
1358 return true;
1359}
1360
Dan Gohmanc2277342008-10-17 21:16:08 +00001361/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1362/// This function emits a branch and is used at the leaves of an OR or an
1363/// AND operator tree.
1364///
1365void
Dan Gohman46510a72010-04-15 01:51:59 +00001366SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
Dan Gohman2048b852009-11-23 18:04:58 +00001367 MachineBasicBlock *TBB,
1368 MachineBasicBlock *FBB,
Dan Gohman99be8ae2010-04-19 22:41:47 +00001369 MachineBasicBlock *CurBB,
1370 MachineBasicBlock *SwitchBB) {
Dan Gohmanc2277342008-10-17 21:16:08 +00001371 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001372
Dan Gohmanc2277342008-10-17 21:16:08 +00001373 // If the leaf of the tree is a comparison, merge the condition into
1374 // the caseblock.
Dan Gohman46510a72010-04-15 01:51:59 +00001375 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
Dan Gohmanc2277342008-10-17 21:16:08 +00001376 // The operands of the cmp have to be in this block. We don't know
1377 // how to export them from some other block. If this is the first block
1378 // of the sequence, no exporting is needed.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001379 if (CurBB == SwitchBB ||
Dan Gohmanc2277342008-10-17 21:16:08 +00001380 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1381 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001382 ISD::CondCode Condition;
Dan Gohman46510a72010-04-15 01:51:59 +00001383 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001384 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohman46510a72010-04-15 01:51:59 +00001385 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001386 Condition = getFCmpCondCode(FC->getPredicate());
Nick Lewycky8a8d4792011-12-02 22:16:29 +00001387 if (TM.Options.NoNaNsFPMath)
1388 Condition = getFCmpCodeWithoutNaN(Condition);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001389 } else {
1390 Condition = ISD::SETEQ; // silence warning.
Torok Edwinc23197a2009-07-14 16:55:14 +00001391 llvm_unreachable("Unknown compare instruction");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001392 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001393
1394 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001395 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1396 SwitchCases.push_back(CB);
1397 return;
1398 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001399 }
1400
1401 // Create a CaseBlock record representing this branch.
Owen Anderson5defacc2009-07-31 17:39:07 +00001402 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
Dan Gohmanc2277342008-10-17 21:16:08 +00001403 NULL, TBB, FBB, CurBB);
1404 SwitchCases.push_back(CB);
1405}
1406
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001407/// FindMergedConditions - If Cond is an expression like
Dan Gohman46510a72010-04-15 01:51:59 +00001408void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
Dan Gohman2048b852009-11-23 18:04:58 +00001409 MachineBasicBlock *TBB,
1410 MachineBasicBlock *FBB,
1411 MachineBasicBlock *CurBB,
Dan Gohman99be8ae2010-04-19 22:41:47 +00001412 MachineBasicBlock *SwitchBB,
Dan Gohman2048b852009-11-23 18:04:58 +00001413 unsigned Opc) {
Dan Gohmanc2277342008-10-17 21:16:08 +00001414 // If this node is not part of the or/and tree, emit it as a branch.
Dan Gohman46510a72010-04-15 01:51:59 +00001415 const Instruction *BOp = dyn_cast<Instruction>(Cond);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001416 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohmanc2277342008-10-17 21:16:08 +00001417 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1418 BOp->getParent() != CurBB->getBasicBlock() ||
1419 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1420 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
Dan Gohman99be8ae2010-04-19 22:41:47 +00001421 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001422 return;
1423 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001424
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001425 // Create TmpBB after CurBB.
1426 MachineFunction::iterator BBI = CurBB;
1427 MachineFunction &MF = DAG.getMachineFunction();
1428 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1429 CurBB->getParent()->insert(++BBI, TmpBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001430
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001431 if (Opc == Instruction::Or) {
1432 // Codegen X | Y as:
1433 // jmp_if_X TBB
1434 // jmp TmpBB
1435 // TmpBB:
1436 // jmp_if_Y TBB
1437 // jmp FBB
1438 //
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001439
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001440 // Emit the LHS condition.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001441 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001442
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001443 // Emit the RHS condition into TmpBB.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001444 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001445 } else {
1446 assert(Opc == Instruction::And && "Unknown merge op!");
1447 // Codegen X & Y as:
1448 // jmp_if_X TmpBB
1449 // jmp FBB
1450 // TmpBB:
1451 // jmp_if_Y TBB
1452 // jmp FBB
1453 //
1454 // This requires creation of TmpBB after CurBB.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001455
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001456 // Emit the LHS condition.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001457 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001458
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001459 // Emit the RHS condition into TmpBB.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001460 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001461 }
1462}
1463
1464/// If the set of cases should be emitted as a series of branches, return true.
1465/// If we should emit this as a bunch of and/or'd together conditions, return
1466/// false.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001467bool
Dan Gohman2048b852009-11-23 18:04:58 +00001468SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001469 if (Cases.size() != 2) return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001470
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001471 // If this is two comparisons of the same values or'd or and'd together, they
1472 // will get folded into a single comparison, so don't emit two blocks.
1473 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1474 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1475 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1476 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1477 return false;
1478 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001479
Chris Lattner133ce872010-01-02 00:00:03 +00001480 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1481 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1482 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1483 Cases[0].CC == Cases[1].CC &&
1484 isa<Constant>(Cases[0].CmpRHS) &&
1485 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1486 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1487 return false;
1488 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1489 return false;
1490 }
Michael J. Spencere70c5262010-10-16 08:25:21 +00001491
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001492 return true;
1493}
1494
Dan Gohman46510a72010-04-15 01:51:59 +00001495void SelectionDAGBuilder::visitBr(const BranchInst &I) {
Dan Gohman84023e02010-07-10 09:00:22 +00001496 MachineBasicBlock *BrMBB = FuncInfo.MBB;
Dan Gohman99be8ae2010-04-19 22:41:47 +00001497
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001498 // Update machine-CFG edges.
1499 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1500
1501 // Figure out which block is immediately after the current one.
1502 MachineBasicBlock *NextBlock = 0;
Dan Gohman99be8ae2010-04-19 22:41:47 +00001503 MachineFunction::iterator BBI = BrMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001504 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001505 NextBlock = BBI;
1506
1507 if (I.isUnconditional()) {
1508 // Update machine-CFG edges.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001509 BrMBB->addSuccessor(Succ0MBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001510
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001511 // If this is not a fall-through branch, emit the branch.
Bill Wendling4533cac2010-01-28 21:51:40 +00001512 if (Succ0MBB != NextBlock)
1513 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001514 MVT::Other, getControlRoot(),
Bill Wendling4533cac2010-01-28 21:51:40 +00001515 DAG.getBasicBlock(Succ0MBB)));
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001516
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001517 return;
1518 }
1519
1520 // If this condition is one of the special cases we handle, do special stuff
1521 // now.
Dan Gohman46510a72010-04-15 01:51:59 +00001522 const Value *CondVal = I.getCondition();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001523 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1524
1525 // If this is a series of conditions that are or'd or and'd together, emit
1526 // this as a sequence of branches instead of setcc's with and/or operations.
Chris Lattnerde189be2010-11-30 18:12:52 +00001527 // As long as jumps are not expensive, this should improve performance.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001528 // For example, instead of something like:
1529 // cmp A, B
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001530 // C = seteq
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001531 // cmp D, E
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001532 // F = setle
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001533 // or C, F
1534 // jnz foo
1535 // Emit:
1536 // cmp A, B
1537 // je foo
1538 // cmp D, E
1539 // jle foo
1540 //
Dan Gohman46510a72010-04-15 01:51:59 +00001541 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
Owen Anderson95771af2011-02-25 21:41:48 +00001542 if (!TLI.isJumpExpensive() &&
Chris Lattnerde189be2010-11-30 18:12:52 +00001543 BOp->hasOneUse() &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001544 (BOp->getOpcode() == Instruction::And ||
1545 BOp->getOpcode() == Instruction::Or)) {
Dan Gohman99be8ae2010-04-19 22:41:47 +00001546 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1547 BOp->getOpcode());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001548 // If the compares in later blocks need to use values not currently
1549 // exported from this block, export them now. This block should always
1550 // be the first entry.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001551 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001552
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001553 // Allow some cases to be rejected.
1554 if (ShouldEmitAsBranches(SwitchCases)) {
1555 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1556 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1557 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1558 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001559
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001560 // Emit the branch for this block.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001561 visitSwitchCase(SwitchCases[0], BrMBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001562 SwitchCases.erase(SwitchCases.begin());
1563 return;
1564 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001565
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001566 // Okay, we decided not to do this, remove any inserted MBB's and clear
1567 // SwitchCases.
1568 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001569 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001570
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001571 SwitchCases.clear();
1572 }
1573 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001574
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001575 // Create a CaseBlock record representing this branch.
Owen Anderson5defacc2009-07-31 17:39:07 +00001576 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
Dan Gohman99be8ae2010-04-19 22:41:47 +00001577 NULL, Succ0MBB, Succ1MBB, BrMBB);
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001578
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001579 // Use visitSwitchCase to actually insert the fast branch sequence for this
1580 // cond branch.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001581 visitSwitchCase(CB, BrMBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001582}
1583
1584/// visitSwitchCase - Emits the necessary code to represent a single node in
1585/// the binary search tree resulting from lowering a switch instruction.
Dan Gohman99be8ae2010-04-19 22:41:47 +00001586void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1587 MachineBasicBlock *SwitchBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001588 SDValue Cond;
1589 SDValue CondLHS = getValue(CB.CmpLHS);
Dale Johannesenf5d97892009-02-04 01:48:28 +00001590 DebugLoc dl = getCurDebugLoc();
Anton Korobeynikov23218582008-12-23 22:25:27 +00001591
1592 // Build the setcc now.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001593 if (CB.CmpMHS == NULL) {
1594 // Fold "(X == true)" to X and "(X == false)" to !X to
1595 // handle common cases produced by branch lowering.
Owen Anderson5defacc2009-07-31 17:39:07 +00001596 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
Owen Andersonf53c3712009-07-21 02:47:59 +00001597 CB.CC == ISD::SETEQ)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001598 Cond = CondLHS;
Owen Anderson5defacc2009-07-31 17:39:07 +00001599 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
Owen Andersonf53c3712009-07-21 02:47:59 +00001600 CB.CC == ISD::SETEQ) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001601 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001602 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001603 } else
Owen Anderson825b72b2009-08-11 20:47:22 +00001604 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001605 } else {
Stepan Dyatkovskiyc187df22012-05-17 08:56:30 +00001606 assert(CB.CC == ISD::SETCC_INVALID &&
1607 "Condition is undefined for to-the-range belonging check.");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001608
Anton Korobeynikov23218582008-12-23 22:25:27 +00001609 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1610 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001611
1612 SDValue CmpOp = getValue(CB.CmpMHS);
Owen Andersone50ed302009-08-10 22:56:29 +00001613 EVT VT = CmpOp.getValueType();
Stepan Dyatkovskiyc187df22012-05-17 08:56:30 +00001614
1615 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(false)) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001616 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
Stepan Dyatkovskiyc187df22012-05-17 08:56:30 +00001617 ISD::SETULE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001618 } else {
Dale Johannesenf5d97892009-02-04 01:48:28 +00001619 SDValue SUB = DAG.getNode(ISD::SUB, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001620 VT, CmpOp, DAG.getConstant(Low, VT));
Owen Anderson825b72b2009-08-11 20:47:22 +00001621 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001622 DAG.getConstant(High-Low, VT), ISD::SETULE);
1623 }
1624 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001625
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001626 // Update successor info
Jakub Staszakc8f34de2011-07-29 22:25:21 +00001627 addSuccessorWithWeight(SwitchBB, CB.TrueBB, CB.TrueWeight);
Jakob Stoklund Olesene7fdef42012-08-20 21:39:52 +00001628 // TrueBB and FalseBB are always different unless the incoming IR is
1629 // degenerate. This only happens when running llc on weird IR.
1630 if (CB.TrueBB != CB.FalseBB)
1631 addSuccessorWithWeight(SwitchBB, CB.FalseBB, CB.FalseWeight);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001632
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001633 // Set NextBlock to be the MBB immediately after the current one, if any.
1634 // This is used to avoid emitting unnecessary branches to the next block.
1635 MachineBasicBlock *NextBlock = 0;
Dan Gohman99be8ae2010-04-19 22:41:47 +00001636 MachineFunction::iterator BBI = SwitchBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001637 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001638 NextBlock = BBI;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001639
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001640 // If the lhs block is the next block, invert the condition so that we can
1641 // fall through to the lhs instead of the rhs block.
1642 if (CB.TrueBB == NextBlock) {
1643 std::swap(CB.TrueBB, CB.FalseBB);
1644 SDValue True = DAG.getConstant(1, Cond.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001645 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001646 }
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001647
Dale Johannesenf5d97892009-02-04 01:48:28 +00001648 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00001649 MVT::Other, getControlRoot(), Cond,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001650 DAG.getBasicBlock(CB.TrueBB));
Bill Wendling87710f02009-12-21 23:47:40 +00001651
Evan Cheng266a99d2010-09-23 06:51:55 +00001652 // Insert the false branch. Do this even if it's a fall through branch,
1653 // this makes it easier to do DAG optimizations which require inverting
1654 // the branch condition.
1655 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1656 DAG.getBasicBlock(CB.FalseBB));
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001657
1658 DAG.setRoot(BrCond);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001659}
1660
1661/// visitJumpTable - Emit JumpTable node in the current MBB
Dan Gohman2048b852009-11-23 18:04:58 +00001662void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001663 // Emit the code for the jump table
1664 assert(JT.Reg != -1U && "Should lower JT Header first!");
Owen Andersone50ed302009-08-10 22:56:29 +00001665 EVT PTy = TLI.getPointerTy();
Dale Johannesena04b7572009-02-03 23:04:43 +00001666 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1667 JT.Reg, PTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001668 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001669 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1670 MVT::Other, Index.getValue(1),
1671 Table, Index);
1672 DAG.setRoot(BrJumpTable);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001673}
1674
1675/// visitJumpTableHeader - This function emits necessary code to produce index
1676/// in the JumpTable from switch case.
Dan Gohman2048b852009-11-23 18:04:58 +00001677void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
Dan Gohman99be8ae2010-04-19 22:41:47 +00001678 JumpTableHeader &JTH,
1679 MachineBasicBlock *SwitchBB) {
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001680 // Subtract the lowest switch case value from the value being switched on and
1681 // conditional branch to default mbb if the result is greater than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001682 // difference between smallest and largest cases.
1683 SDValue SwitchOp = getValue(JTH.SValue);
Owen Andersone50ed302009-08-10 22:56:29 +00001684 EVT VT = SwitchOp.getValueType();
Bill Wendling87710f02009-12-21 23:47:40 +00001685 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001686 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001687
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001688 // The SDNode we just created, which holds the value being switched on minus
Dan Gohmanf451cb82010-02-10 16:03:48 +00001689 // the smallest case value, needs to be copied to a virtual register so it
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001690 // can be used as an index into the jump table in a subsequent basic block.
1691 // This value may be smaller or larger than the target's pointer type, and
1692 // therefore require extension or truncating.
Bill Wendling87710f02009-12-21 23:47:40 +00001693 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001694
Dan Gohman89496d02010-07-02 00:10:16 +00001695 unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001696 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1697 JumpTableReg, SwitchOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001698 JT.Reg = JumpTableReg;
1699
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001700 // Emit the range check for the jump table, and branch to the default block
1701 // for the switch statement if the value being switched on exceeds the largest
1702 // case in the switch.
Dale Johannesenf5d97892009-02-04 01:48:28 +00001703 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00001704 TLI.getSetCCResultType(Sub.getValueType()), Sub,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001705 DAG.getConstant(JTH.Last-JTH.First,VT),
1706 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001707
1708 // Set NextBlock to be the MBB immediately after the current one, if any.
1709 // This is used to avoid emitting unnecessary branches to the next block.
1710 MachineBasicBlock *NextBlock = 0;
Dan Gohman99be8ae2010-04-19 22:41:47 +00001711 MachineFunction::iterator BBI = SwitchBB;
Bill Wendling87710f02009-12-21 23:47:40 +00001712
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001713 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001714 NextBlock = BBI;
1715
Dale Johannesen66978ee2009-01-31 02:22:37 +00001716 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001717 MVT::Other, CopyTo, CMP,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001718 DAG.getBasicBlock(JT.Default));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001719
Bill Wendling4533cac2010-01-28 21:51:40 +00001720 if (JT.MBB != NextBlock)
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001721 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1722 DAG.getBasicBlock(JT.MBB));
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001723
Bill Wendling87710f02009-12-21 23:47:40 +00001724 DAG.setRoot(BrCond);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001725}
1726
1727/// visitBitTestHeader - This function emits necessary code to produce value
1728/// suitable for "bit tests"
Dan Gohman99be8ae2010-04-19 22:41:47 +00001729void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1730 MachineBasicBlock *SwitchBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001731 // Subtract the minimum value
1732 SDValue SwitchOp = getValue(B.SValue);
Owen Andersone50ed302009-08-10 22:56:29 +00001733 EVT VT = SwitchOp.getValueType();
Bill Wendling87710f02009-12-21 23:47:40 +00001734 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001735 DAG.getConstant(B.First, VT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001736
1737 // Check range
Dale Johannesenf5d97892009-02-04 01:48:28 +00001738 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00001739 TLI.getSetCCResultType(Sub.getValueType()),
1740 Sub, DAG.getConstant(B.Range, VT),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001741 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001742
Evan Chengd08e5b42011-01-06 01:02:44 +00001743 // Determine the type of the test operands.
1744 bool UsePtrType = false;
1745 if (!TLI.isTypeLegal(VT))
1746 UsePtrType = true;
1747 else {
1748 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
Eli Friedman5c75af62011-10-12 22:46:45 +00001749 if (!isUIntN(VT.getSizeInBits(), B.Cases[i].Mask)) {
Evan Chengd08e5b42011-01-06 01:02:44 +00001750 // Switch table case range are encoded into series of masks.
1751 // Just use pointer type, it's guaranteed to fit.
1752 UsePtrType = true;
1753 break;
1754 }
1755 }
1756 if (UsePtrType) {
1757 VT = TLI.getPointerTy();
1758 Sub = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), VT);
1759 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001760
Evan Chengd08e5b42011-01-06 01:02:44 +00001761 B.RegVT = VT;
1762 B.Reg = FuncInfo.CreateReg(VT);
Dale Johannesena04b7572009-02-03 23:04:43 +00001763 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
Evan Chengd08e5b42011-01-06 01:02:44 +00001764 B.Reg, Sub);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001765
1766 // Set NextBlock to be the MBB immediately after the current one, if any.
1767 // This is used to avoid emitting unnecessary branches to the next block.
1768 MachineBasicBlock *NextBlock = 0;
Dan Gohman99be8ae2010-04-19 22:41:47 +00001769 MachineFunction::iterator BBI = SwitchBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001770 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001771 NextBlock = BBI;
1772
1773 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1774
Jakub Staszak7cc2b072011-06-16 20:22:37 +00001775 addSuccessorWithWeight(SwitchBB, B.Default);
1776 addSuccessorWithWeight(SwitchBB, MBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001777
Dale Johannesen66978ee2009-01-31 02:22:37 +00001778 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001779 MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001780 DAG.getBasicBlock(B.Default));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001781
Evan Cheng8c1f4322010-09-23 18:32:19 +00001782 if (MBB != NextBlock)
1783 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1784 DAG.getBasicBlock(MBB));
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001785
Bill Wendling87710f02009-12-21 23:47:40 +00001786 DAG.setRoot(BrRange);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001787}
1788
1789/// visitBitTestCase - this function produces one "bit test"
Evan Chengd08e5b42011-01-06 01:02:44 +00001790void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1791 MachineBasicBlock* NextMBB,
Manman Ren1a710fd2012-08-24 18:14:27 +00001792 uint32_t BranchWeightToNext,
Dan Gohman2048b852009-11-23 18:04:58 +00001793 unsigned Reg,
Dan Gohman99be8ae2010-04-19 22:41:47 +00001794 BitTestCase &B,
1795 MachineBasicBlock *SwitchBB) {
Evan Chengd08e5b42011-01-06 01:02:44 +00001796 EVT VT = BB.RegVT;
1797 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1798 Reg, VT);
Dan Gohman8e0163a2010-06-24 02:06:24 +00001799 SDValue Cmp;
Benjamin Kramer3ff25512011-07-14 01:38:42 +00001800 unsigned PopCount = CountPopulation_64(B.Mask);
1801 if (PopCount == 1) {
Dan Gohman8e0163a2010-06-24 02:06:24 +00001802 // Testing for a single bit; just compare the shift count with what it
1803 // would need to be to shift a 1 bit in that position.
1804 Cmp = DAG.getSetCC(getCurDebugLoc(),
Evan Chengd08e5b42011-01-06 01:02:44 +00001805 TLI.getSetCCResultType(VT),
Dan Gohman8e0163a2010-06-24 02:06:24 +00001806 ShiftOp,
Evan Chengd08e5b42011-01-06 01:02:44 +00001807 DAG.getConstant(CountTrailingZeros_64(B.Mask), VT),
Dan Gohman8e0163a2010-06-24 02:06:24 +00001808 ISD::SETEQ);
Benjamin Kramer3ff25512011-07-14 01:38:42 +00001809 } else if (PopCount == BB.Range) {
1810 // There is only one zero bit in the range, test for it directly.
1811 Cmp = DAG.getSetCC(getCurDebugLoc(),
1812 TLI.getSetCCResultType(VT),
1813 ShiftOp,
1814 DAG.getConstant(CountTrailingOnes_64(B.Mask), VT),
1815 ISD::SETNE);
Dan Gohman8e0163a2010-06-24 02:06:24 +00001816 } else {
1817 // Make desired shift
Evan Chengd08e5b42011-01-06 01:02:44 +00001818 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(), VT,
1819 DAG.getConstant(1, VT), ShiftOp);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001820
Dan Gohman8e0163a2010-06-24 02:06:24 +00001821 // Emit bit tests and jumps
1822 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
Evan Chengd08e5b42011-01-06 01:02:44 +00001823 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
Dan Gohman8e0163a2010-06-24 02:06:24 +00001824 Cmp = DAG.getSetCC(getCurDebugLoc(),
Evan Chengd08e5b42011-01-06 01:02:44 +00001825 TLI.getSetCCResultType(VT),
1826 AndOp, DAG.getConstant(0, VT),
Dan Gohman8e0163a2010-06-24 02:06:24 +00001827 ISD::SETNE);
1828 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001829
Manman Ren1a710fd2012-08-24 18:14:27 +00001830 // The branch weight from SwitchBB to B.TargetBB is B.ExtraWeight.
1831 addSuccessorWithWeight(SwitchBB, B.TargetBB, B.ExtraWeight);
1832 // The branch weight from SwitchBB to NextMBB is BranchWeightToNext.
1833 addSuccessorWithWeight(SwitchBB, NextMBB, BranchWeightToNext);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001834
Dale Johannesen66978ee2009-01-31 02:22:37 +00001835 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001836 MVT::Other, getControlRoot(),
Dan Gohman8e0163a2010-06-24 02:06:24 +00001837 Cmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001838
1839 // Set NextBlock to be the MBB immediately after the current one, if any.
1840 // This is used to avoid emitting unnecessary branches to the next block.
1841 MachineBasicBlock *NextBlock = 0;
Dan Gohman99be8ae2010-04-19 22:41:47 +00001842 MachineFunction::iterator BBI = SwitchBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001843 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001844 NextBlock = BBI;
1845
Evan Cheng8c1f4322010-09-23 18:32:19 +00001846 if (NextMBB != NextBlock)
1847 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1848 DAG.getBasicBlock(NextMBB));
Bill Wendling0777e922009-12-21 21:59:52 +00001849
Bill Wendling87710f02009-12-21 23:47:40 +00001850 DAG.setRoot(BrAnd);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001851}
1852
Dan Gohman46510a72010-04-15 01:51:59 +00001853void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
Dan Gohman84023e02010-07-10 09:00:22 +00001854 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
Dan Gohman99be8ae2010-04-19 22:41:47 +00001855
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001856 // Retrieve successors.
1857 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1858 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1859
Gabor Greifb67e6b32009-01-15 11:10:44 +00001860 const Value *Callee(I.getCalledValue());
Nuno Lopes85b40892012-06-28 22:30:12 +00001861 const Function *Fn = dyn_cast<Function>(Callee);
Gabor Greifb67e6b32009-01-15 11:10:44 +00001862 if (isa<InlineAsm>(Callee))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001863 visitInlineAsm(&I);
Nuno Lopes85b40892012-06-28 22:30:12 +00001864 else if (Fn && Fn->isIntrinsic()) {
1865 assert(Fn->getIntrinsicID() == Intrinsic::donothing);
Nuno Lopes4532bf62012-07-18 00:07:17 +00001866 // Ignore invokes to @llvm.donothing: jump directly to the next BB.
Nuno Lopes85b40892012-06-28 22:30:12 +00001867 } else
Gabor Greifb67e6b32009-01-15 11:10:44 +00001868 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001869
1870 // If the value of the invoke is used outside of its defining block, make it
1871 // available as a virtual register.
Dan Gohmanad62f532009-04-23 23:13:24 +00001872 CopyToExportRegsIfNeeded(&I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001873
1874 // Update successor info
Chandler Carruthf2645682011-11-22 11:37:46 +00001875 addSuccessorWithWeight(InvokeMBB, Return);
1876 addSuccessorWithWeight(InvokeMBB, LandingPad);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001877
1878 // Drop into normal successor.
Bill Wendling4533cac2010-01-28 21:51:40 +00001879 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1880 MVT::Other, getControlRoot(),
1881 DAG.getBasicBlock(Return)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001882}
1883
Bill Wendlingdccc03b2011-07-31 06:30:59 +00001884void SelectionDAGBuilder::visitResume(const ResumeInst &RI) {
1885 llvm_unreachable("SelectionDAGBuilder shouldn't visit resume instructions!");
1886}
1887
Bill Wendling2ac0e6b2011-08-17 21:56:44 +00001888void SelectionDAGBuilder::visitLandingPad(const LandingPadInst &LP) {
1889 assert(FuncInfo.MBB->isLandingPad() &&
1890 "Call to landingpad not in landing pad!");
1891
1892 MachineBasicBlock *MBB = FuncInfo.MBB;
1893 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
1894 AddLandingPadInfo(LP, MMI, MBB);
1895
Bill Wendlingbdf9db62012-02-13 23:47:16 +00001896 // If there aren't registers to copy the values into (e.g., during SjLj
1897 // exceptions), then don't bother to create these DAG nodes.
Lang Hames07961342012-02-14 04:45:49 +00001898 if (TLI.getExceptionPointerRegister() == 0 &&
Bill Wendlingbdf9db62012-02-13 23:47:16 +00001899 TLI.getExceptionSelectorRegister() == 0)
1900 return;
1901
Bill Wendling2ac0e6b2011-08-17 21:56:44 +00001902 SmallVector<EVT, 2> ValueVTs;
1903 ComputeValueVTs(TLI, LP.getType(), ValueVTs);
1904
1905 // Insert the EXCEPTIONADDR instruction.
1906 assert(FuncInfo.MBB->isLandingPad() &&
1907 "Call to eh.exception not in landing pad!");
1908 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
1909 SDValue Ops[2];
1910 Ops[0] = DAG.getRoot();
1911 SDValue Op1 = DAG.getNode(ISD::EXCEPTIONADDR, getCurDebugLoc(), VTs, Ops, 1);
1912 SDValue Chain = Op1.getValue(1);
1913
1914 // Insert the EHSELECTION instruction.
1915 VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
1916 Ops[0] = Op1;
1917 Ops[1] = Chain;
1918 SDValue Op2 = DAG.getNode(ISD::EHSELECTION, getCurDebugLoc(), VTs, Ops, 2);
1919 Chain = Op2.getValue(1);
1920 Op2 = DAG.getSExtOrTrunc(Op2, getCurDebugLoc(), MVT::i32);
1921
1922 Ops[0] = Op1;
1923 Ops[1] = Op2;
1924 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
1925 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
1926 &Ops[0], 2);
1927
1928 std::pair<SDValue, SDValue> RetPair = std::make_pair(Res, Chain);
1929 setValue(&LP, RetPair.first);
1930 DAG.setRoot(RetPair.second);
1931}
1932
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001933/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1934/// small case ranges).
Dan Gohman2048b852009-11-23 18:04:58 +00001935bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
1936 CaseRecVector& WorkList,
Dan Gohman46510a72010-04-15 01:51:59 +00001937 const Value* SV,
Dan Gohman99be8ae2010-04-19 22:41:47 +00001938 MachineBasicBlock *Default,
1939 MachineBasicBlock *SwitchBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001940 // Size is the number of Cases represented by this range.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001941 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001942 if (Size > 3)
Anton Korobeynikov23218582008-12-23 22:25:27 +00001943 return false;
1944
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001945 // Get the MachineFunction which holds the current MBB. This is used when
1946 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001947 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001948
1949 // Figure out which block is immediately after the current one.
1950 MachineBasicBlock *NextBlock = 0;
1951 MachineFunction::iterator BBI = CR.CaseBB;
1952
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001953 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001954 NextBlock = BBI;
1955
Manman Ren1a710fd2012-08-24 18:14:27 +00001956 BranchProbabilityInfo *BPI = FuncInfo.BPI;
Benjamin Kramerce750f02010-11-22 09:45:38 +00001957 // If any two of the cases has the same destination, and if one value
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001958 // is the same as the other, but has one bit unset that the other has set,
1959 // use bit manipulation to do two compares at once. For example:
1960 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Benjamin Kramerce750f02010-11-22 09:45:38 +00001961 // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
1962 // TODO: Handle cases where CR.CaseBB != SwitchBB.
1963 if (Size == 2 && CR.CaseBB == SwitchBB) {
1964 Case &Small = *CR.Range.first;
1965 Case &Big = *(CR.Range.second-1);
1966
1967 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
1968 const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
1969 const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
1970
1971 // Check that there is only one bit different.
1972 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
1973 (SmallValue | BigValue) == BigValue) {
1974 // Isolate the common bit.
1975 APInt CommonBit = BigValue & ~SmallValue;
1976 assert((SmallValue | CommonBit) == BigValue &&
1977 CommonBit.countPopulation() == 1 && "Not a common bit?");
1978
1979 SDValue CondLHS = getValue(SV);
1980 EVT VT = CondLHS.getValueType();
1981 DebugLoc DL = getCurDebugLoc();
1982
1983 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
1984 DAG.getConstant(CommonBit, VT));
1985 SDValue Cond = DAG.getSetCC(DL, MVT::i1,
1986 Or, DAG.getConstant(BigValue, VT),
1987 ISD::SETEQ);
1988
1989 // Update successor info.
Manman Ren1a710fd2012-08-24 18:14:27 +00001990 // Both Small and Big will jump to Small.BB, so we sum up the weights.
1991 addSuccessorWithWeight(SwitchBB, Small.BB,
1992 Small.ExtraWeight + Big.ExtraWeight);
1993 addSuccessorWithWeight(SwitchBB, Default,
1994 // The default destination is the first successor in IR.
1995 BPI ? BPI->getEdgeWeight(SwitchBB->getBasicBlock(), (unsigned)0) : 0);
Benjamin Kramerce750f02010-11-22 09:45:38 +00001996
1997 // Insert the true branch.
1998 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
1999 getControlRoot(), Cond,
2000 DAG.getBasicBlock(Small.BB));
2001
2002 // Insert the false branch.
2003 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
2004 DAG.getBasicBlock(Default));
2005
2006 DAG.setRoot(BrCond);
2007 return true;
2008 }
2009 }
2010 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002011
Benjamin Kramerc511b2a2012-05-26 20:01:32 +00002012 // Order cases by weight so the most likely case will be checked first.
Manman Ren1a710fd2012-08-24 18:14:27 +00002013 uint32_t UnhandledWeights = 0;
Benjamin Kramerc511b2a2012-05-26 20:01:32 +00002014 if (BPI) {
2015 for (CaseItr I = CR.Range.first, IE = CR.Range.second; I != IE; ++I) {
Manman Ren1a710fd2012-08-24 18:14:27 +00002016 uint32_t IWeight = I->ExtraWeight;
2017 UnhandledWeights += IWeight;
Benjamin Kramerc511b2a2012-05-26 20:01:32 +00002018 for (CaseItr J = CR.Range.first; J < I; ++J) {
Manman Ren1a710fd2012-08-24 18:14:27 +00002019 uint32_t JWeight = J->ExtraWeight;
Benjamin Kramerc511b2a2012-05-26 20:01:32 +00002020 if (IWeight > JWeight)
2021 std::swap(*I, *J);
2022 }
2023 }
2024 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002025 // Rearrange the case blocks so that the last one falls through if possible.
Benjamin Kramerc511b2a2012-05-26 20:01:32 +00002026 Case &BackCase = *(CR.Range.second-1);
Benjamin Kramer5db954d2012-05-26 21:19:12 +00002027 if (Size > 1 &&
2028 NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002029 // The last case block won't fall through into 'NextBlock' if we emit the
2030 // branches in this order. See if rearranging a case value would help.
Benjamin Kramerc511b2a2012-05-26 20:01:32 +00002031 // We start at the bottom as it's the case with the least weight.
Benjamin Kramercf1d69d2012-05-27 10:56:55 +00002032 for (Case *I = &*(CR.Range.second-2), *E = &*CR.Range.first-1; I != E; --I){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002033 if (I->BB == NextBlock) {
2034 std::swap(*I, BackCase);
2035 break;
2036 }
2037 }
2038 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002039
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002040 // Create a CaseBlock record representing a conditional branch to
2041 // the Case's target mbb if the value being switched on SV is equal
2042 // to C.
2043 MachineBasicBlock *CurBlock = CR.CaseBB;
2044 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2045 MachineBasicBlock *FallThrough;
2046 if (I != E-1) {
2047 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
2048 CurMF->insert(BBI, FallThrough);
Dan Gohman8e5c0da2009-04-09 02:33:36 +00002049
2050 // Put SV in a virtual register to make it available from the new blocks.
2051 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002052 } else {
2053 // If the last case doesn't match, go to the default block.
2054 FallThrough = Default;
2055 }
2056
Dan Gohman46510a72010-04-15 01:51:59 +00002057 const Value *RHS, *LHS, *MHS;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002058 ISD::CondCode CC;
2059 if (I->High == I->Low) {
2060 // This is just small small case range :) containing exactly 1 case
2061 CC = ISD::SETEQ;
2062 LHS = SV; RHS = I->High; MHS = NULL;
2063 } else {
Stepan Dyatkovskiyc187df22012-05-17 08:56:30 +00002064 CC = ISD::SETCC_INVALID;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002065 LHS = I->Low; MHS = SV; RHS = I->High;
2066 }
Jakub Staszakc8f34de2011-07-29 22:25:21 +00002067
Manman Ren1a710fd2012-08-24 18:14:27 +00002068 // The false weight should be sum of all un-handled cases.
2069 UnhandledWeights -= I->ExtraWeight;
Jakub Staszakc8f34de2011-07-29 22:25:21 +00002070 CaseBlock CB(CC, LHS, RHS, MHS, /* truebb */ I->BB, /* falsebb */ FallThrough,
2071 /* me */ CurBlock,
Manman Ren1a710fd2012-08-24 18:14:27 +00002072 /* trueweight */ I->ExtraWeight,
2073 /* falseweight */ UnhandledWeights);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002074
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002075 // If emitting the first comparison, just call visitSwitchCase to emit the
2076 // code into the current block. Otherwise, push the CaseBlock onto the
2077 // vector to be later processed by SDISel, and insert the node's MBB
2078 // before the next MBB.
Dan Gohman99be8ae2010-04-19 22:41:47 +00002079 if (CurBlock == SwitchBB)
2080 visitSwitchCase(CB, SwitchBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002081 else
2082 SwitchCases.push_back(CB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002083
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002084 CurBlock = FallThrough;
2085 }
2086
2087 return true;
2088}
2089
2090static inline bool areJTsAllowed(const TargetLowering &TLI) {
Evan Cheng769951f2012-07-02 22:39:56 +00002091 return TLI.supportJumpTables() &&
Owen Anderson825b72b2009-08-11 20:47:22 +00002092 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
2093 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002094}
Anton Korobeynikov23218582008-12-23 22:25:27 +00002095
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002096static APInt ComputeRange(const APInt &First, const APInt &Last) {
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002097 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
Stepan Dyatkovskiyc187df22012-05-17 08:56:30 +00002098 APInt LastExt = Last.zext(BitWidth), FirstExt = First.zext(BitWidth);
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002099 return (LastExt - FirstExt + 1ULL);
2100}
2101
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002102/// handleJTSwitchCase - Emit jumptable for current switch case range
Chris Lattnerc3ab3882011-09-09 22:06:59 +00002103bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec &CR,
2104 CaseRecVector &WorkList,
2105 const Value *SV,
2106 MachineBasicBlock *Default,
Dan Gohman99be8ae2010-04-19 22:41:47 +00002107 MachineBasicBlock *SwitchBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002108 Case& FrontCase = *CR.Range.first;
2109 Case& BackCase = *(CR.Range.second-1);
2110
Chris Lattnere880efe2009-11-07 07:50:34 +00002111 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2112 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002113
Chris Lattnere880efe2009-11-07 07:50:34 +00002114 APInt TSize(First.getBitWidth(), 0);
Chris Lattnerc3ab3882011-09-09 22:06:59 +00002115 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002116 TSize += I->size();
2117
Sebastian Pop1a37d7e2012-09-25 20:35:36 +00002118 if (!areJTsAllowed(TLI) || TSize.ult(TLI.getMinimumJumpTableEntries()))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002119 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002120
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002121 APInt Range = ComputeRange(First, Last);
Jakob Stoklund Olesen79443912011-10-26 01:47:48 +00002122 // The density is TSize / Range. Require at least 40%.
2123 // It should not be possible for IntTSize to saturate for sane code, but make
2124 // sure we handle Range saturation correctly.
2125 uint64_t IntRange = Range.getLimitedValue(UINT64_MAX/10);
2126 uint64_t IntTSize = TSize.getLimitedValue(UINT64_MAX/10);
2127 if (IntTSize * 10 < IntRange * 4)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002128 return false;
2129
David Greene4b69d992010-01-05 01:24:57 +00002130 DEBUG(dbgs() << "Lowering jump table\n"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002131 << "First entry: " << First << ". Last entry: " << Last << '\n'
Jakob Stoklund Olesen79443912011-10-26 01:47:48 +00002132 << "Range: " << Range << ". Size: " << TSize << ".\n\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002133
2134 // Get the MachineFunction which holds the current MBB. This is used when
2135 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00002136 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002137
2138 // Figure out which block is immediately after the current one.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002139 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands51498522009-09-06 18:03:32 +00002140 ++BBI;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002141
2142 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2143
2144 // Create a new basic block to hold the code for loading the address
2145 // of the jump table, and jumping to it. Update successor information;
2146 // we will either branch to the default case for the switch, or the jump
2147 // table.
2148 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2149 CurMF->insert(BBI, JumpTableBB);
Jakub Staszak7cc2b072011-06-16 20:22:37 +00002150
2151 addSuccessorWithWeight(CR.CaseBB, Default);
2152 addSuccessorWithWeight(CR.CaseBB, JumpTableBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002153
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002154 // Build a vector of destination BBs, corresponding to each target
2155 // of the jump table. If the value of the jump table slot corresponds to
2156 // a case statement, push the case's BB onto the vector, otherwise, push
2157 // the default BB.
2158 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002159 APInt TEI = First;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002160 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Chris Lattner071c62f2010-01-25 23:26:13 +00002161 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
2162 const APInt &High = cast<ConstantInt>(I->High)->getValue();
Anton Korobeynikov23218582008-12-23 22:25:27 +00002163
Stepan Dyatkovskiyc187df22012-05-17 08:56:30 +00002164 if (Low.ule(TEI) && TEI.ule(High)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002165 DestBBs.push_back(I->BB);
2166 if (TEI==High)
2167 ++I;
2168 } else {
2169 DestBBs.push_back(Default);
2170 }
2171 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002172
Manman Ren1a710fd2012-08-24 18:14:27 +00002173 // Calculate weight for each unique destination in CR.
2174 DenseMap<MachineBasicBlock*, uint32_t> DestWeights;
2175 if (FuncInfo.BPI)
2176 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
2177 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2178 DestWeights.find(I->BB);
2179 if (Itr != DestWeights.end())
2180 Itr->second += I->ExtraWeight;
2181 else
2182 DestWeights[I->BB] = I->ExtraWeight;
2183 }
2184
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002185 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002186 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
2187 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002188 E = DestBBs.end(); I != E; ++I) {
2189 if (!SuccsHandled[(*I)->getNumber()]) {
2190 SuccsHandled[(*I)->getNumber()] = true;
Manman Ren1a710fd2012-08-24 18:14:27 +00002191 DenseMap<MachineBasicBlock*, uint32_t>::iterator Itr =
2192 DestWeights.find(*I);
2193 addSuccessorWithWeight(JumpTableBB, *I,
2194 Itr != DestWeights.end() ? Itr->second : 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002195 }
2196 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002197
Bob Wilsond1ec31d2010-03-18 18:42:41 +00002198 // Create a jump table index for this jump table.
Chris Lattner071c62f2010-01-25 23:26:13 +00002199 unsigned JTEncoding = TLI.getJumpTableEncoding();
2200 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
Bob Wilsond1ec31d2010-03-18 18:42:41 +00002201 ->createJumpTableIndex(DestBBs);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002202
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002203 // Set the jump table information so that we can codegen it as a second
2204 // MachineBasicBlock
2205 JumpTable JT(-1U, JTI, JumpTableBB, Default);
Dan Gohman99be8ae2010-04-19 22:41:47 +00002206 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
2207 if (CR.CaseBB == SwitchBB)
2208 visitJumpTableHeader(JT, JTH, SwitchBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002209
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002210 JTCases.push_back(JumpTableBlock(JTH, JT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002211 return true;
2212}
2213
2214/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2215/// 2 subtrees.
Dan Gohman2048b852009-11-23 18:04:58 +00002216bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
2217 CaseRecVector& WorkList,
Dan Gohman46510a72010-04-15 01:51:59 +00002218 const Value* SV,
Dan Gohman99be8ae2010-04-19 22:41:47 +00002219 MachineBasicBlock *Default,
2220 MachineBasicBlock *SwitchBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002221 // Get the MachineFunction which holds the current MBB. This is used when
2222 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00002223 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002224
2225 // Figure out which block is immediately after the current one.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002226 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands51498522009-09-06 18:03:32 +00002227 ++BBI;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002228
2229 Case& FrontCase = *CR.Range.first;
2230 Case& BackCase = *(CR.Range.second-1);
2231 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2232
2233 // Size is the number of Cases represented by this range.
2234 unsigned Size = CR.Range.second - CR.Range.first;
2235
Chris Lattnere880efe2009-11-07 07:50:34 +00002236 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2237 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002238 double FMetric = 0;
2239 CaseItr Pivot = CR.Range.first + Size/2;
2240
2241 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2242 // (heuristically) allow us to emit JumpTable's later.
Chris Lattnere880efe2009-11-07 07:50:34 +00002243 APInt TSize(First.getBitWidth(), 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002244 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2245 I!=E; ++I)
2246 TSize += I->size();
2247
Chris Lattnere880efe2009-11-07 07:50:34 +00002248 APInt LSize = FrontCase.size();
2249 APInt RSize = TSize-LSize;
David Greene4b69d992010-01-05 01:24:57 +00002250 DEBUG(dbgs() << "Selecting best pivot: \n"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002251 << "First: " << First << ", Last: " << Last <<'\n'
2252 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002253 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2254 J!=E; ++I, ++J) {
Chris Lattnere880efe2009-11-07 07:50:34 +00002255 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
2256 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002257 APInt Range = ComputeRange(LEnd, RBegin);
Stepan Dyatkovskiyc2c52a62012-05-15 06:50:18 +00002258 assert((Range - 2ULL).isNonNegative() &&
2259 "Invalid case distance");
Chris Lattnerc3e4e592011-04-09 06:57:13 +00002260 // Use volatile double here to avoid excess precision issues on some hosts,
2261 // e.g. that use 80-bit X87 registers.
2262 volatile double LDensity =
2263 (double)LSize.roundToDouble() /
Chris Lattnere880efe2009-11-07 07:50:34 +00002264 (LEnd - First + 1ULL).roundToDouble();
Chris Lattnerc3e4e592011-04-09 06:57:13 +00002265 volatile double RDensity =
2266 (double)RSize.roundToDouble() /
Chris Lattnere880efe2009-11-07 07:50:34 +00002267 (Last - RBegin + 1ULL).roundToDouble();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002268 double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002269 // Should always split in some non-trivial place
David Greene4b69d992010-01-05 01:24:57 +00002270 DEBUG(dbgs() <<"=>Step\n"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002271 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
2272 << "LDensity: " << LDensity
2273 << ", RDensity: " << RDensity << '\n'
2274 << "Metric: " << Metric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002275 if (FMetric < Metric) {
2276 Pivot = J;
2277 FMetric = Metric;
David Greene4b69d992010-01-05 01:24:57 +00002278 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002279 }
2280
2281 LSize += J->size();
2282 RSize -= J->size();
2283 }
2284 if (areJTsAllowed(TLI)) {
2285 // If our case is dense we *really* should handle it earlier!
2286 assert((FMetric > 0) && "Should handle dense range earlier!");
2287 } else {
2288 Pivot = CR.Range.first + Size/2;
2289 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002290
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002291 CaseRange LHSR(CR.Range.first, Pivot);
2292 CaseRange RHSR(Pivot, CR.Range.second);
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00002293 const Constant *C = Pivot->Low;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002294 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002295
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002296 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002297 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002298 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002299 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002300 // Pivot's Value, then we can branch directly to the LHS's Target,
2301 // rather than creating a leaf node for it.
2302 if ((LHSR.second - LHSR.first) == 1 &&
2303 LHSR.first->High == CR.GE &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00002304 cast<ConstantInt>(C)->getValue() ==
2305 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002306 TrueBB = LHSR.first->BB;
2307 } else {
2308 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2309 CurMF->insert(BBI, TrueBB);
2310 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00002311
2312 // Put SV in a virtual register to make it available from the new blocks.
2313 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002314 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002315
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002316 // Similar to the optimization above, if the Value being switched on is
2317 // known to be less than the Constant CR.LT, and the current Case Value
2318 // is CR.LT - 1, then we can branch directly to the target block for
2319 // the current Case Value, rather than emitting a RHS leaf node for it.
2320 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00002321 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
2322 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002323 FalseBB = RHSR.first->BB;
2324 } else {
2325 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2326 CurMF->insert(BBI, FalseBB);
2327 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00002328
2329 // Put SV in a virtual register to make it available from the new blocks.
2330 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002331 }
2332
2333 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002334 // the LHS node if the value being switched on SV is less than C.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002335 // Otherwise, branch to LHS.
Stepan Dyatkovskiyc187df22012-05-17 08:56:30 +00002336 CaseBlock CB(ISD::SETULT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002337
Dan Gohman99be8ae2010-04-19 22:41:47 +00002338 if (CR.CaseBB == SwitchBB)
2339 visitSwitchCase(CB, SwitchBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002340 else
2341 SwitchCases.push_back(CB);
2342
2343 return true;
2344}
2345
2346/// handleBitTestsSwitchCase - if current case range has few destination and
2347/// range span less, than machine word bitwidth, encode case range into series
2348/// of masks and emit bit tests with these masks.
Dan Gohman2048b852009-11-23 18:04:58 +00002349bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2350 CaseRecVector& WorkList,
Dan Gohman46510a72010-04-15 01:51:59 +00002351 const Value* SV,
Dan Gohman99be8ae2010-04-19 22:41:47 +00002352 MachineBasicBlock* Default,
2353 MachineBasicBlock *SwitchBB){
Owen Andersone50ed302009-08-10 22:56:29 +00002354 EVT PTy = TLI.getPointerTy();
Owen Anderson77547be2009-08-10 18:56:59 +00002355 unsigned IntPtrBits = PTy.getSizeInBits();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002356
2357 Case& FrontCase = *CR.Range.first;
2358 Case& BackCase = *(CR.Range.second-1);
2359
2360 // Get the MachineFunction which holds the current MBB. This is used when
2361 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00002362 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002363
Anton Korobeynikovd34167a2009-05-08 18:51:34 +00002364 // If target does not have legal shift left, do not emit bit tests at all.
2365 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
2366 return false;
2367
Anton Korobeynikov23218582008-12-23 22:25:27 +00002368 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002369 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2370 I!=E; ++I) {
2371 // Single case counts one, case range - two.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002372 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002373 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002374
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002375 // Count unique destinations
2376 SmallSet<MachineBasicBlock*, 4> Dests;
2377 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2378 Dests.insert(I->BB);
2379 if (Dests.size() > 3)
2380 // Don't bother the code below, if there are too much unique destinations
2381 return false;
2382 }
David Greene4b69d992010-01-05 01:24:57 +00002383 DEBUG(dbgs() << "Total number of unique destinations: "
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002384 << Dests.size() << '\n'
2385 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00002386
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002387 // Compute span of values.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002388 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2389 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002390 APInt cmpRange = maxValue - minValue;
2391
David Greene4b69d992010-01-05 01:24:57 +00002392 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002393 << "Low bound: " << minValue << '\n'
2394 << "High bound: " << maxValue << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00002395
Dan Gohmane0567812010-04-08 23:03:40 +00002396 if (cmpRange.uge(IntPtrBits) ||
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002397 (!(Dests.size() == 1 && numCmps >= 3) &&
2398 !(Dests.size() == 2 && numCmps >= 5) &&
2399 !(Dests.size() >= 3 && numCmps >= 6)))
2400 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002401
David Greene4b69d992010-01-05 01:24:57 +00002402 DEBUG(dbgs() << "Emitting bit tests\n");
Anton Korobeynikov23218582008-12-23 22:25:27 +00002403 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2404
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002405 // Optimize the case where all the case values fit in a
2406 // word without having to subtract minValue. In this case,
2407 // we can optimize away the subtraction.
Stepan Dyatkovskiyc187df22012-05-17 08:56:30 +00002408 if (maxValue.ult(IntPtrBits)) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00002409 cmpRange = maxValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002410 } else {
Anton Korobeynikov23218582008-12-23 22:25:27 +00002411 lowBound = minValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002412 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002413
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002414 CaseBitsVector CasesBits;
2415 unsigned i, count = 0;
2416
2417 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2418 MachineBasicBlock* Dest = I->BB;
2419 for (i = 0; i < count; ++i)
2420 if (Dest == CasesBits[i].BB)
2421 break;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002422
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002423 if (i == count) {
2424 assert((count < 3) && "Too much destinations to test!");
Manman Ren1a710fd2012-08-24 18:14:27 +00002425 CasesBits.push_back(CaseBits(0, Dest, 0, 0/*Weight*/));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002426 count++;
2427 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002428
2429 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2430 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2431
2432 uint64_t lo = (lowValue - lowBound).getZExtValue();
2433 uint64_t hi = (highValue - lowBound).getZExtValue();
Manman Ren1a710fd2012-08-24 18:14:27 +00002434 CasesBits[i].ExtraWeight += I->ExtraWeight;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002435
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002436 for (uint64_t j = lo; j <= hi; j++) {
2437 CasesBits[i].Mask |= 1ULL << j;
2438 CasesBits[i].Bits++;
2439 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002440
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002441 }
2442 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov23218582008-12-23 22:25:27 +00002443
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002444 BitTestInfo BTC;
2445
2446 // Figure out which block is immediately after the current one.
2447 MachineFunction::iterator BBI = CR.CaseBB;
2448 ++BBI;
2449
2450 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2451
David Greene4b69d992010-01-05 01:24:57 +00002452 DEBUG(dbgs() << "Cases:\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002453 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
David Greene4b69d992010-01-05 01:24:57 +00002454 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002455 << ", Bits: " << CasesBits[i].Bits
2456 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002457
2458 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2459 CurMF->insert(BBI, CaseBB);
2460 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2461 CaseBB,
Manman Ren1a710fd2012-08-24 18:14:27 +00002462 CasesBits[i].BB, CasesBits[i].ExtraWeight));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00002463
2464 // Put SV in a virtual register to make it available from the new blocks.
2465 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002466 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002467
2468 BitTestBlock BTB(lowBound, cmpRange, SV,
Evan Chengd08e5b42011-01-06 01:02:44 +00002469 -1U, MVT::Other, (CR.CaseBB == SwitchBB),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002470 CR.CaseBB, Default, BTC);
2471
Dan Gohman99be8ae2010-04-19 22:41:47 +00002472 if (CR.CaseBB == SwitchBB)
2473 visitBitTestHeader(BTB, SwitchBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002474
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002475 BitTestCases.push_back(BTB);
2476
2477 return true;
2478}
2479
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002480/// Clusterify - Transform simple list of Cases into list of CaseRange's
Dan Gohman2048b852009-11-23 18:04:58 +00002481size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2482 const SwitchInst& SI) {
Stepan Dyatkovskiy05cfe2e2012-05-18 08:32:28 +00002483
2484 /// Use a shorter form of declaration, and also
2485 /// show the we want to use CRSBuilder as Clusterifier.
Stepan Dyatkovskiy4319a552012-06-02 07:26:00 +00002486 typedef IntegersSubsetMapping<MachineBasicBlock> Clusterifier;
Stepan Dyatkovskiy05cfe2e2012-05-18 08:32:28 +00002487
2488 Clusterifier TheClusterifier;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002489
Manman Ren1a710fd2012-08-24 18:14:27 +00002490 BranchProbabilityInfo *BPI = FuncInfo.BPI;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002491 // Start with "simple" cases
Stepan Dyatkovskiy3d3abe02012-03-11 06:09:17 +00002492 for (SwitchInst::ConstCaseIt i = SI.case_begin(), e = SI.case_end();
Stepan Dyatkovskiyc10fa6c2012-03-08 07:06:20 +00002493 i != e; ++i) {
2494 const BasicBlock *SuccBB = i.getCaseSuccessor();
Jakub Staszakc8f34de2011-07-29 22:25:21 +00002495 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SuccBB];
2496
Manman Ren1a710fd2012-08-24 18:14:27 +00002497 TheClusterifier.add(i.getCaseValueEx(), SMBB,
2498 BPI ? BPI->getEdgeWeight(SI.getParent(), i.getSuccessorIndex()) : 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002499 }
Stepan Dyatkovskiy05cfe2e2012-05-18 08:32:28 +00002500
2501 TheClusterifier.optimize();
2502
Stepan Dyatkovskiy05cfe2e2012-05-18 08:32:28 +00002503 size_t numCmps = 0;
2504 for (Clusterifier::RangeIterator i = TheClusterifier.begin(),
2505 e = TheClusterifier.end(); i != e; ++i, ++numCmps) {
Stepan Dyatkovskiy66d79ce2012-07-04 05:53:05 +00002506 Clusterifier::Cluster &C = *i;
Manman Ren1a710fd2012-08-24 18:14:27 +00002507 // Update edge weight for the cluster.
2508 unsigned W = C.first.Weight;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002509
Stepan Dyatkovskiy484fc932012-05-28 12:39:09 +00002510 // FIXME: Currently work with ConstantInt based numbers.
2511 // Changing it to APInt based is a pretty heavy for this commit.
Stepan Dyatkovskiy66d79ce2012-07-04 05:53:05 +00002512 Cases.push_back(Case(C.first.getLow().toConstantInt(),
2513 C.first.getHigh().toConstantInt(), C.second, W));
Stepan Dyatkovskiy05cfe2e2012-05-18 08:32:28 +00002514
Stepan Dyatkovskiy66d79ce2012-07-04 05:53:05 +00002515 if (C.first.getLow() != C.first.getHigh())
Stepan Dyatkovskiy05cfe2e2012-05-18 08:32:28 +00002516 // A range counts double, since it requires two compares.
2517 ++numCmps;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002518 }
2519
2520 return numCmps;
2521}
2522
Jakob Stoklund Olesen2622f462010-09-30 19:44:31 +00002523void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2524 MachineBasicBlock *Last) {
2525 // Update JTCases.
2526 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2527 if (JTCases[i].first.HeaderBB == First)
2528 JTCases[i].first.HeaderBB = Last;
2529
2530 // Update BitTestCases.
2531 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2532 if (BitTestCases[i].Parent == First)
2533 BitTestCases[i].Parent = Last;
2534}
2535
Dan Gohman46510a72010-04-15 01:51:59 +00002536void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
Dan Gohman84023e02010-07-10 09:00:22 +00002537 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
Dan Gohman99be8ae2010-04-19 22:41:47 +00002538
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002539 // Figure out which block is immediately after the current one.
2540 MachineBasicBlock *NextBlock = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002541 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2542
2543 // If there is only the default destination, branch to it if it is not the
2544 // next basic block. Otherwise, just fall through.
Stepan Dyatkovskiy24473122012-02-01 07:49:51 +00002545 if (!SI.getNumCases()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002546 // Update machine-CFG edges.
2547
2548 // If this is not a fall-through branch, emit the branch.
Dan Gohman99be8ae2010-04-19 22:41:47 +00002549 SwitchMBB->addSuccessor(Default);
Bill Wendling4533cac2010-01-28 21:51:40 +00002550 if (Default != NextBlock)
2551 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
2552 MVT::Other, getControlRoot(),
2553 DAG.getBasicBlock(Default)));
Bill Wendling49fcff82009-12-21 22:30:11 +00002554
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002555 return;
2556 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002557
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002558 // If there are any non-default case statements, create a vector of Cases
2559 // representing each one, and sort the vector so that we can efficiently
2560 // create a binary search tree from them.
2561 CaseVector Cases;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002562 size_t numCmps = Clusterify(Cases, SI);
David Greene4b69d992010-01-05 01:24:57 +00002563 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002564 << ". Total compares: " << numCmps << '\n');
Duncan Sands17001ce2011-10-18 12:44:00 +00002565 (void)numCmps;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002566
2567 // Get the Value to be switched on and default basic blocks, which will be
2568 // inserted into CaseBlock records, representing basic blocks in the binary
2569 // search tree.
Eli Friedmanbb5a7442011-09-29 20:21:17 +00002570 const Value *SV = SI.getCondition();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002571
2572 // Push the initial CaseRec onto the worklist
2573 CaseRecVector WorkList;
Dan Gohman99be8ae2010-04-19 22:41:47 +00002574 WorkList.push_back(CaseRec(SwitchMBB,0,0,
2575 CaseRange(Cases.begin(),Cases.end())));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002576
2577 while (!WorkList.empty()) {
2578 // Grab a record representing a case range to process off the worklist
2579 CaseRec CR = WorkList.back();
2580 WorkList.pop_back();
2581
Dan Gohman99be8ae2010-04-19 22:41:47 +00002582 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002583 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002584
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002585 // If the range has few cases (two or less) emit a series of specific
2586 // tests.
Dan Gohman99be8ae2010-04-19 22:41:47 +00002587 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002588 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002589
Sebastian Pop1a37d7e2012-09-25 20:35:36 +00002590 // If the switch has more than N blocks, and is at least 40% dense, and the
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002591 // target supports indirect branches, then emit a jump table rather than
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002592 // lowering the switch to a binary tree of conditional branches.
Sebastian Pop1a37d7e2012-09-25 20:35:36 +00002593 // N defaults to 4 and is controlled via TLS.getMinimumJumpTableEntries().
Dan Gohman99be8ae2010-04-19 22:41:47 +00002594 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002595 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002596
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002597 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2598 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
Dan Gohman99be8ae2010-04-19 22:41:47 +00002599 handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002600 }
2601}
2602
Dan Gohman46510a72010-04-15 01:51:59 +00002603void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
Dan Gohman84023e02010-07-10 09:00:22 +00002604 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
Dan Gohman99be8ae2010-04-19 22:41:47 +00002605
Jakob Stoklund Olesen598b24c2010-02-11 00:34:18 +00002606 // Update machine-CFG edges with unique successors.
Nadav Rotemee0ce152012-10-23 21:05:33 +00002607 SmallSet<BasicBlock*, 32> Done;
2608 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i) {
2609 BasicBlock *BB = I.getSuccessor(i);
2610 bool Inserted = Done.insert(BB);
2611 if (!Inserted)
2612 continue;
2613
2614 MachineBasicBlock *Succ = FuncInfo.MBBMap[BB];
Jakub Staszak7cc2b072011-06-16 20:22:37 +00002615 addSuccessorWithWeight(IndirectBrMBB, Succ);
2616 }
Dan Gohmaneef55dc2009-10-27 22:10:34 +00002617
Bill Wendling4533cac2010-01-28 21:51:40 +00002618 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2619 MVT::Other, getControlRoot(),
2620 getValue(I.getAddress())));
Bill Wendling49fcff82009-12-21 22:30:11 +00002621}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002622
Dan Gohman46510a72010-04-15 01:51:59 +00002623void SelectionDAGBuilder::visitFSub(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002624 // -0.0 - X --> fneg
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002625 Type *Ty = I.getType();
Chris Lattner2ca5c862011-02-15 00:14:00 +00002626 if (isa<Constant>(I.getOperand(0)) &&
2627 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2628 SDValue Op2 = getValue(I.getOperand(1));
2629 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2630 Op2.getValueType(), Op2));
2631 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002632 }
Bill Wendling49fcff82009-12-21 22:30:11 +00002633
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002634 visitBinary(I, ISD::FSUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002635}
2636
Dan Gohman46510a72010-04-15 01:51:59 +00002637void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002638 SDValue Op1 = getValue(I.getOperand(0));
2639 SDValue Op2 = getValue(I.getOperand(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00002640 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2641 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002642}
2643
Dan Gohman46510a72010-04-15 01:51:59 +00002644void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002645 SDValue Op1 = getValue(I.getOperand(0));
2646 SDValue Op2 = getValue(I.getOperand(1));
Owen Anderson95771af2011-02-25 21:41:48 +00002647
2648 MVT ShiftTy = TLI.getShiftAmountTy(Op2.getValueType());
2649
Chris Lattnerd3027732011-02-13 09:02:52 +00002650 // Coerce the shift amount to the right type if we can.
2651 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
Chris Lattner915eeb42011-02-13 09:10:56 +00002652 unsigned ShiftSize = ShiftTy.getSizeInBits();
2653 unsigned Op2Size = Op2.getValueType().getSizeInBits();
Chris Lattnerd3027732011-02-13 09:02:52 +00002654 DebugLoc DL = getCurDebugLoc();
Owen Anderson95771af2011-02-25 21:41:48 +00002655
Dan Gohman57fc82d2009-04-09 03:51:29 +00002656 // If the operand is smaller than the shift count type, promote it.
Chris Lattnerd3027732011-02-13 09:02:52 +00002657 if (ShiftSize > Op2Size)
2658 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
Owen Anderson95771af2011-02-25 21:41:48 +00002659
Dan Gohman57fc82d2009-04-09 03:51:29 +00002660 // If the operand is larger than the shift count type but the shift
2661 // count type has enough bits to represent any shift value, truncate
2662 // it now. This is a common case and it exposes the truncate to
2663 // optimization early.
Chris Lattnerd3027732011-02-13 09:02:52 +00002664 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2665 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2666 // Otherwise we'll need to temporarily settle for some other convenient
Chris Lattnere0751182011-02-13 19:09:16 +00002667 // type. Type legalization will make adjustments once the shiftee is split.
Chris Lattnerd3027732011-02-13 09:02:52 +00002668 else
Chris Lattnere0751182011-02-13 19:09:16 +00002669 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002670 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002671
Bill Wendling4533cac2010-01-28 21:51:40 +00002672 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2673 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002674}
2675
Benjamin Kramer9c640302011-07-08 10:31:30 +00002676void SelectionDAGBuilder::visitSDiv(const User &I) {
Benjamin Kramer9c640302011-07-08 10:31:30 +00002677 SDValue Op1 = getValue(I.getOperand(0));
2678 SDValue Op2 = getValue(I.getOperand(1));
2679
2680 // Turn exact SDivs into multiplications.
2681 // FIXME: This should be in DAGCombiner, but it doesn't have access to the
2682 // exact bit.
Benjamin Kramer3492a4a2011-07-08 12:08:24 +00002683 if (isa<BinaryOperator>(&I) && cast<BinaryOperator>(&I)->isExact() &&
2684 !isa<ConstantSDNode>(Op1) &&
Benjamin Kramer9c640302011-07-08 10:31:30 +00002685 isa<ConstantSDNode>(Op2) && !cast<ConstantSDNode>(Op2)->isNullValue())
2686 setValue(&I, TLI.BuildExactSDIV(Op1, Op2, getCurDebugLoc(), DAG));
2687 else
2688 setValue(&I, DAG.getNode(ISD::SDIV, getCurDebugLoc(), Op1.getValueType(),
2689 Op1, Op2));
2690}
2691
Dan Gohman46510a72010-04-15 01:51:59 +00002692void SelectionDAGBuilder::visitICmp(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002693 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
Dan Gohman46510a72010-04-15 01:51:59 +00002694 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002695 predicate = IC->getPredicate();
Dan Gohman46510a72010-04-15 01:51:59 +00002696 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002697 predicate = ICmpInst::Predicate(IC->getPredicate());
2698 SDValue Op1 = getValue(I.getOperand(0));
2699 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002700 ISD::CondCode Opcode = getICmpCondCode(predicate);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002701
Owen Andersone50ed302009-08-10 22:56:29 +00002702 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002703 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002704}
2705
Dan Gohman46510a72010-04-15 01:51:59 +00002706void SelectionDAGBuilder::visitFCmp(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002707 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
Dan Gohman46510a72010-04-15 01:51:59 +00002708 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002709 predicate = FC->getPredicate();
Dan Gohman46510a72010-04-15 01:51:59 +00002710 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002711 predicate = FCmpInst::Predicate(FC->getPredicate());
2712 SDValue Op1 = getValue(I.getOperand(0));
2713 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002714 ISD::CondCode Condition = getFCmpCondCode(predicate);
Nick Lewycky8a8d4792011-12-02 22:16:29 +00002715 if (TM.Options.NoNaNsFPMath)
2716 Condition = getFCmpCodeWithoutNaN(Condition);
Owen Andersone50ed302009-08-10 22:56:29 +00002717 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002718 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002719}
2720
Dan Gohman46510a72010-04-15 01:51:59 +00002721void SelectionDAGBuilder::visitSelect(const User &I) {
Owen Andersone50ed302009-08-10 22:56:29 +00002722 SmallVector<EVT, 4> ValueVTs;
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002723 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2724 unsigned NumValues = ValueVTs.size();
Bill Wendling49fcff82009-12-21 22:30:11 +00002725 if (NumValues == 0) return;
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002726
Bill Wendling49fcff82009-12-21 22:30:11 +00002727 SmallVector<SDValue, 4> Values(NumValues);
2728 SDValue Cond = getValue(I.getOperand(0));
2729 SDValue TrueVal = getValue(I.getOperand(1));
2730 SDValue FalseVal = getValue(I.getOperand(2));
Duncan Sands28b77e92011-09-06 19:07:46 +00002731 ISD::NodeType OpCode = Cond.getValueType().isVector() ?
2732 ISD::VSELECT : ISD::SELECT;
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002733
Bill Wendling4533cac2010-01-28 21:51:40 +00002734 for (unsigned i = 0; i != NumValues; ++i)
Duncan Sands28b77e92011-09-06 19:07:46 +00002735 Values[i] = DAG.getNode(OpCode, getCurDebugLoc(),
2736 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
Chris Lattnerb3e87b22010-03-12 07:15:36 +00002737 Cond,
Bill Wendling49fcff82009-12-21 22:30:11 +00002738 SDValue(TrueVal.getNode(),
2739 TrueVal.getResNo() + i),
2740 SDValue(FalseVal.getNode(),
2741 FalseVal.getResNo() + i));
2742
Bill Wendling4533cac2010-01-28 21:51:40 +00002743 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2744 DAG.getVTList(&ValueVTs[0], NumValues),
2745 &Values[0], NumValues));
Bill Wendling49fcff82009-12-21 22:30:11 +00002746}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002747
Dan Gohman46510a72010-04-15 01:51:59 +00002748void SelectionDAGBuilder::visitTrunc(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002749 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
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::TRUNCATE, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002753}
2754
Dan Gohman46510a72010-04-15 01:51:59 +00002755void SelectionDAGBuilder::visitZExt(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002756 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2757 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2758 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002759 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002760 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002761}
2762
Dan Gohman46510a72010-04-15 01:51:59 +00002763void SelectionDAGBuilder::visitSExt(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002764 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2765 // SExt also can't be a cast to bool for same reason. So, nothing much to do
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::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002769}
2770
Dan Gohman46510a72010-04-15 01:51:59 +00002771void SelectionDAGBuilder::visitFPTrunc(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002772 // FPTrunc 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_ROUND, getCurDebugLoc(),
Pete Cooperf57e1c22012-01-17 01:54:07 +00002776 DestVT, N,
2777 DAG.getTargetConstant(0, TLI.getPointerTy())));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002778}
2779
Dan Gohman46510a72010-04-15 01:51:59 +00002780void SelectionDAGBuilder::visitFPExt(const User &I){
Hal Finkel46bb70c2011-10-18 03:51:57 +00002781 // FPExt is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002782 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002783 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002784 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002785}
2786
Dan Gohman46510a72010-04-15 01:51:59 +00002787void SelectionDAGBuilder::visitFPToUI(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002788 // FPToUI is never a no-op cast, no need to check
2789 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002790 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002791 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002792}
2793
Dan Gohman46510a72010-04-15 01:51:59 +00002794void SelectionDAGBuilder::visitFPToSI(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002795 // FPToSI is never a no-op cast, no need to check
2796 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002797 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002798 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002799}
2800
Dan Gohman46510a72010-04-15 01:51:59 +00002801void SelectionDAGBuilder::visitUIToFP(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002802 // UIToFP is never a no-op cast, no need to check
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.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002806}
2807
Dan Gohman46510a72010-04-15 01:51:59 +00002808void SelectionDAGBuilder::visitSIToFP(const User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002809 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002810 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002811 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002812 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002813}
2814
Dan Gohman46510a72010-04-15 01:51:59 +00002815void SelectionDAGBuilder::visitPtrToInt(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002816 // What to do depends on the size of the integer and the size of the pointer.
2817 // We can either truncate, zero extend, or no-op, accordingly.
2818 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002819 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002820 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002821}
2822
Dan Gohman46510a72010-04-15 01:51:59 +00002823void SelectionDAGBuilder::visitIntToPtr(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002824 // What to do depends on the size of the integer and the size of the pointer.
2825 // We can either truncate, zero extend, or no-op, accordingly.
2826 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002827 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002828 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002829}
2830
Dan Gohman46510a72010-04-15 01:51:59 +00002831void SelectionDAGBuilder::visitBitCast(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002832 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002833 EVT DestVT = TLI.getValueType(I.getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002834
Bill Wendling49fcff82009-12-21 22:30:11 +00002835 // BitCast assures us that source and destination are the same size so this is
Wesley Peckbf17cfa2010-11-23 03:31:01 +00002836 // either a BITCAST or a no-op.
Bill Wendling4533cac2010-01-28 21:51:40 +00002837 if (DestVT != N.getValueType())
Wesley Peckbf17cfa2010-11-23 03:31:01 +00002838 setValue(&I, DAG.getNode(ISD::BITCAST, getCurDebugLoc(),
Bill Wendling4533cac2010-01-28 21:51:40 +00002839 DestVT, N)); // convert types.
2840 else
Bill Wendling49fcff82009-12-21 22:30:11 +00002841 setValue(&I, N); // noop cast.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002842}
2843
Dan Gohman46510a72010-04-15 01:51:59 +00002844void SelectionDAGBuilder::visitInsertElement(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002845 SDValue InVec = getValue(I.getOperand(0));
2846 SDValue InVal = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002847 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00002848 TLI.getPointerTy(),
2849 getValue(I.getOperand(2)));
Bill Wendling4533cac2010-01-28 21:51:40 +00002850 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2851 TLI.getValueType(I.getType()),
2852 InVec, InVal, InIdx));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002853}
2854
Dan Gohman46510a72010-04-15 01:51:59 +00002855void SelectionDAGBuilder::visitExtractElement(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002856 SDValue InVec = getValue(I.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00002857 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00002858 TLI.getPointerTy(),
2859 getValue(I.getOperand(1)));
Bill Wendling4533cac2010-01-28 21:51:40 +00002860 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2861 TLI.getValueType(I.getType()), InVec, InIdx));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002862}
2863
Craig Topper51578342012-01-04 09:23:09 +00002864// Utility for visitShuffleVector - Return true if every element in Mask,
Benjamin Kramerd9b0b022012-06-02 10:20:22 +00002865// beginning from position Pos and ending in Pos+Size, falls within the
Craig Topper51578342012-01-04 09:23:09 +00002866// specified sequential range [L, L+Pos). or is undef.
2867static bool isSequentialInRange(const SmallVectorImpl<int> &Mask,
Craig Topper23de31b2012-04-11 03:06:35 +00002868 unsigned Pos, unsigned Size, int Low) {
2869 for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
Craig Topper51578342012-01-04 09:23:09 +00002870 if (Mask[i] >= 0 && Mask[i] != Low)
Nate Begeman9008ca62009-04-27 18:41:29 +00002871 return false;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002872 return true;
2873}
2874
Dan Gohman46510a72010-04-15 01:51:59 +00002875void SelectionDAGBuilder::visitShuffleVector(const User &I) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002876 SDValue Src1 = getValue(I.getOperand(0));
2877 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002878
Chris Lattner56243b82012-01-26 02:51:13 +00002879 SmallVector<int, 8> Mask;
2880 ShuffleVectorInst::getShuffleMask(cast<Constant>(I.getOperand(2)), Mask);
2881 unsigned MaskNumElts = Mask.size();
2882
Owen Andersone50ed302009-08-10 22:56:29 +00002883 EVT VT = TLI.getValueType(I.getType());
2884 EVT SrcVT = Src1.getValueType();
Nate Begeman5a5ca152009-04-29 05:20:52 +00002885 unsigned SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002886
Mon P Wangc7849c22008-11-16 05:06:27 +00002887 if (SrcNumElts == MaskNumElts) {
Bill Wendling4533cac2010-01-28 21:51:40 +00002888 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2889 &Mask[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002890 return;
2891 }
2892
2893 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002894 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2895 // Mask is longer than the source vectors and is a multiple of the source
2896 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang230e4fa2008-11-21 04:25:21 +00002897 // lengths match.
Craig Topper51578342012-01-04 09:23:09 +00002898 if (SrcNumElts*2 == MaskNumElts) {
2899 // First check for Src1 in low and Src2 in high
2900 if (isSequentialInRange(Mask, 0, SrcNumElts, 0) &&
2901 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, SrcNumElts)) {
2902 // The shuffle is concatenating two vectors together.
2903 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2904 VT, Src1, Src2));
2905 return;
2906 }
2907 // Then check for Src2 in low and Src1 in high
2908 if (isSequentialInRange(Mask, 0, SrcNumElts, SrcNumElts) &&
2909 isSequentialInRange(Mask, SrcNumElts, SrcNumElts, 0)) {
2910 // The shuffle is concatenating two vectors together.
2911 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2912 VT, Src2, Src1));
2913 return;
2914 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002915 }
2916
Mon P Wangc7849c22008-11-16 05:06:27 +00002917 // Pad both vectors with undefs to make them the same length as the mask.
2918 unsigned NumConcat = MaskNumElts / SrcNumElts;
Nate Begeman9008ca62009-04-27 18:41:29 +00002919 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2920 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
Dale Johannesene8d72302009-02-06 23:05:02 +00002921 SDValue UndefVal = DAG.getUNDEF(SrcVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002922
Nate Begeman9008ca62009-04-27 18:41:29 +00002923 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2924 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002925 MOps1[0] = Src1;
2926 MOps2[0] = Src2;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002927
2928 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2929 getCurDebugLoc(), VT,
Nate Begeman9008ca62009-04-27 18:41:29 +00002930 &MOps1[0], NumConcat);
2931 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002932 getCurDebugLoc(), VT,
Nate Begeman9008ca62009-04-27 18:41:29 +00002933 &MOps2[0], NumConcat);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002934
Mon P Wangaeb06d22008-11-10 04:46:22 +00002935 // Readjust mask for new input vector length.
Nate Begeman9008ca62009-04-27 18:41:29 +00002936 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002937 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002938 int Idx = Mask[i];
Craig Topper23de31b2012-04-11 03:06:35 +00002939 if (Idx >= (int)SrcNumElts)
2940 Idx -= SrcNumElts - MaskNumElts;
2941 MappedOps.push_back(Idx);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002942 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002943
Bill Wendling4533cac2010-01-28 21:51:40 +00002944 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2945 &MappedOps[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002946 return;
2947 }
2948
Mon P Wangc7849c22008-11-16 05:06:27 +00002949 if (SrcNumElts > MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002950 // Analyze the access pattern of the vector to see if we can extract
2951 // two subvectors and do the shuffle. The analysis is done by calculating
2952 // the range of elements the mask access on both vectors.
Craig Topper10612dc2012-04-08 23:15:04 +00002953 int MinRange[2] = { static_cast<int>(SrcNumElts),
2954 static_cast<int>(SrcNumElts)};
Mon P Wangc7849c22008-11-16 05:06:27 +00002955 int MaxRange[2] = {-1, -1};
2956
Nate Begeman5a5ca152009-04-29 05:20:52 +00002957 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002958 int Idx = Mask[i];
Craig Topper10612dc2012-04-08 23:15:04 +00002959 unsigned Input = 0;
Nate Begeman9008ca62009-04-27 18:41:29 +00002960 if (Idx < 0)
2961 continue;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002962
Nate Begeman5a5ca152009-04-29 05:20:52 +00002963 if (Idx >= (int)SrcNumElts) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002964 Input = 1;
2965 Idx -= SrcNumElts;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002966 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002967 if (Idx > MaxRange[Input])
2968 MaxRange[Input] = Idx;
2969 if (Idx < MinRange[Input])
2970 MinRange[Input] = Idx;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002971 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002972
Mon P Wangc7849c22008-11-16 05:06:27 +00002973 // Check if the access is smaller than the vector size and can we find
2974 // a reasonable extract index.
Craig Topper10612dc2012-04-08 23:15:04 +00002975 int RangeUse[2] = { -1, -1 }; // 0 = Unused, 1 = Extract, -1 = Can not
2976 // Extract.
Mon P Wangc7849c22008-11-16 05:06:27 +00002977 int StartIdx[2]; // StartIdx to extract from
Craig Topper10612dc2012-04-08 23:15:04 +00002978 for (unsigned Input = 0; Input < 2; ++Input) {
2979 if (MinRange[Input] >= (int)SrcNumElts && MaxRange[Input] < 0) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002980 RangeUse[Input] = 0; // Unused
2981 StartIdx[Input] = 0;
Craig Topperf873dde2012-04-08 17:53:33 +00002982 continue;
Mon P Wang230e4fa2008-11-21 04:25:21 +00002983 }
Craig Topperf873dde2012-04-08 17:53:33 +00002984
2985 // Find a good start index that is a multiple of the mask length. Then
2986 // see if the rest of the elements are in range.
2987 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2988 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2989 StartIdx[Input] + MaskNumElts <= SrcNumElts)
2990 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002991 }
2992
Bill Wendling636e2582009-08-21 18:16:06 +00002993 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
Bill Wendling4533cac2010-01-28 21:51:40 +00002994 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
Mon P Wangc7849c22008-11-16 05:06:27 +00002995 return;
2996 }
Craig Topper10612dc2012-04-08 23:15:04 +00002997 if (RangeUse[0] >= 0 && RangeUse[1] >= 0) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002998 // Extract appropriate subvector and generate a vector shuffle
Craig Topper10612dc2012-04-08 23:15:04 +00002999 for (unsigned Input = 0; Input < 2; ++Input) {
Bill Wendling87710f02009-12-21 23:47:40 +00003000 SDValue &Src = Input == 0 ? Src1 : Src2;
Bill Wendlingb85b6e82009-12-21 22:42:14 +00003001 if (RangeUse[Input] == 0)
Dale Johannesene8d72302009-02-06 23:05:02 +00003002 Src = DAG.getUNDEF(VT);
Bill Wendlingb85b6e82009-12-21 22:42:14 +00003003 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00003004 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003005 Src, DAG.getIntPtrConstant(StartIdx[Input]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00003006 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00003007
Mon P Wangc7849c22008-11-16 05:06:27 +00003008 // Calculate new mask.
Nate Begeman9008ca62009-04-27 18:41:29 +00003009 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00003010 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00003011 int Idx = Mask[i];
Craig Topper23de31b2012-04-11 03:06:35 +00003012 if (Idx >= 0) {
3013 if (Idx < (int)SrcNumElts)
3014 Idx -= StartIdx[0];
3015 else
3016 Idx -= SrcNumElts + StartIdx[1] - MaskNumElts;
3017 }
3018 MappedOps.push_back(Idx);
Mon P Wangc7849c22008-11-16 05:06:27 +00003019 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00003020
Bill Wendling4533cac2010-01-28 21:51:40 +00003021 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
3022 &MappedOps[0]));
Mon P Wangc7849c22008-11-16 05:06:27 +00003023 return;
Mon P Wangaeb06d22008-11-10 04:46:22 +00003024 }
3025 }
3026
Mon P Wangc7849c22008-11-16 05:06:27 +00003027 // We can't use either concat vectors or extract subvectors so fall back to
3028 // replacing the shuffle with extract and build vector.
3029 // to insert and build vector.
Owen Andersone50ed302009-08-10 22:56:29 +00003030 EVT EltVT = VT.getVectorElementType();
3031 EVT PtrVT = TLI.getPointerTy();
Mon P Wangaeb06d22008-11-10 04:46:22 +00003032 SmallVector<SDValue,8> Ops;
Nate Begeman5a5ca152009-04-29 05:20:52 +00003033 for (unsigned i = 0; i != MaskNumElts; ++i) {
Craig Topper23de31b2012-04-11 03:06:35 +00003034 int Idx = Mask[i];
3035 SDValue Res;
3036
3037 if (Idx < 0) {
3038 Res = DAG.getUNDEF(EltVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00003039 } else {
Craig Topper23de31b2012-04-11 03:06:35 +00003040 SDValue &Src = Idx < (int)SrcNumElts ? Src1 : Src2;
3041 if (Idx >= (int)SrcNumElts) Idx -= SrcNumElts;
Bill Wendlingb85b6e82009-12-21 22:42:14 +00003042
Craig Topper23de31b2012-04-11 03:06:35 +00003043 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
3044 EltVT, Src, DAG.getConstant(Idx, PtrVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00003045 }
Craig Topper23de31b2012-04-11 03:06:35 +00003046
3047 Ops.push_back(Res);
Mon P Wangaeb06d22008-11-10 04:46:22 +00003048 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00003049
Bill Wendling4533cac2010-01-28 21:51:40 +00003050 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
3051 VT, &Ops[0], Ops.size()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003052}
3053
Dan Gohman46510a72010-04-15 01:51:59 +00003054void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003055 const Value *Op0 = I.getOperand(0);
3056 const Value *Op1 = I.getOperand(1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003057 Type *AggTy = I.getType();
3058 Type *ValTy = Op1->getType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003059 bool IntoUndef = isa<UndefValue>(Op0);
3060 bool FromUndef = isa<UndefValue>(Op1);
3061
Jay Foadfc6d3a42011-07-13 10:26:04 +00003062 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003063
Owen Andersone50ed302009-08-10 22:56:29 +00003064 SmallVector<EVT, 4> AggValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003065 ComputeValueVTs(TLI, AggTy, AggValueVTs);
Owen Andersone50ed302009-08-10 22:56:29 +00003066 SmallVector<EVT, 4> ValValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003067 ComputeValueVTs(TLI, ValTy, ValValueVTs);
3068
3069 unsigned NumAggValues = AggValueVTs.size();
3070 unsigned NumValValues = ValValueVTs.size();
3071 SmallVector<SDValue, 4> Values(NumAggValues);
3072
3073 SDValue Agg = getValue(Op0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003074 unsigned i = 0;
3075 // Copy the beginning value(s) from the original aggregate.
3076 for (; i != LinearIndex; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00003077 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003078 SDValue(Agg.getNode(), Agg.getResNo() + i);
3079 // Copy values from the inserted value(s).
Rafael Espindola3fa82832011-05-13 15:18:06 +00003080 if (NumValValues) {
3081 SDValue Val = getValue(Op1);
3082 for (; i != LinearIndex + NumValValues; ++i)
3083 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
3084 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
3085 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003086 // Copy remaining value(s) from the original aggregate.
3087 for (; i != NumAggValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00003088 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003089 SDValue(Agg.getNode(), Agg.getResNo() + i);
3090
Bill Wendling4533cac2010-01-28 21:51:40 +00003091 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
3092 DAG.getVTList(&AggValueVTs[0], NumAggValues),
3093 &Values[0], NumAggValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003094}
3095
Dan Gohman46510a72010-04-15 01:51:59 +00003096void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003097 const Value *Op0 = I.getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003098 Type *AggTy = Op0->getType();
3099 Type *ValTy = I.getType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003100 bool OutOfUndef = isa<UndefValue>(Op0);
3101
Jay Foadfc6d3a42011-07-13 10:26:04 +00003102 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.getIndices());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003103
Owen Andersone50ed302009-08-10 22:56:29 +00003104 SmallVector<EVT, 4> ValValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003105 ComputeValueVTs(TLI, ValTy, ValValueVTs);
3106
3107 unsigned NumValValues = ValValueVTs.size();
Rafael Espindola3fa82832011-05-13 15:18:06 +00003108
3109 // Ignore a extractvalue that produces an empty object
3110 if (!NumValValues) {
3111 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
3112 return;
3113 }
3114
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003115 SmallVector<SDValue, 4> Values(NumValValues);
3116
3117 SDValue Agg = getValue(Op0);
3118 // Copy out the selected value(s).
3119 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
3120 Values[i - LinearIndex] =
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00003121 OutOfUndef ?
Dale Johannesene8d72302009-02-06 23:05:02 +00003122 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00003123 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003124
Bill Wendling4533cac2010-01-28 21:51:40 +00003125 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
3126 DAG.getVTList(&ValValueVTs[0], NumValValues),
3127 &Values[0], NumValValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003128}
3129
Dan Gohman46510a72010-04-15 01:51:59 +00003130void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003131 SDValue N = getValue(I.getOperand(0));
Nadav Rotem1c239202012-02-28 14:13:19 +00003132 // Note that the pointer operand may be a vector of pointers. Take the scalar
3133 // element which holds a pointer.
3134 Type *Ty = I.getOperand(0)->getType()->getScalarType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003135
Dan Gohman46510a72010-04-15 01:51:59 +00003136 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003137 OI != E; ++OI) {
Dan Gohman46510a72010-04-15 01:51:59 +00003138 const Value *Idx = *OI;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003139 if (StructType *StTy = dyn_cast<StructType>(Ty)) {
Duncan Sandsb2df01a2012-11-13 13:01:58 +00003140 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003141 if (Field) {
3142 // N = N + Offset
3143 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Dale Johannesen66978ee2009-01-31 02:22:37 +00003144 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Duncan Sandsb2df01a2012-11-13 13:01:58 +00003145 DAG.getConstant(Offset, N.getValueType()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003146 }
Bill Wendlinge1a90422009-12-21 23:10:19 +00003147
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003148 Ty = StTy->getElementType(Field);
3149 } else {
3150 Ty = cast<SequentialType>(Ty)->getElementType();
3151
3152 // If this is a constant subscript, handle it quickly.
Dan Gohman46510a72010-04-15 01:51:59 +00003153 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
Dan Gohmane368b462010-06-18 14:22:04 +00003154 if (CI->isZero()) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003155 uint64_t Offs =
Duncan Sands777d2302009-05-09 07:06:46 +00003156 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Evan Cheng65b52df2009-02-09 21:01:06 +00003157 SDValue OffsVal;
Owen Andersone50ed302009-08-10 22:56:29 +00003158 EVT PTy = TLI.getPointerTy();
Owen Anderson77547be2009-08-10 18:56:59 +00003159 unsigned PtrBits = PTy.getSizeInBits();
Bill Wendlinge1a90422009-12-21 23:10:19 +00003160 if (PtrBits < 64)
Evan Cheng65b52df2009-02-09 21:01:06 +00003161 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
3162 TLI.getPointerTy(),
Owen Anderson825b72b2009-08-11 20:47:22 +00003163 DAG.getConstant(Offs, MVT::i64));
Bill Wendlinge1a90422009-12-21 23:10:19 +00003164 else
Evan Chengb1032a82009-02-09 20:54:38 +00003165 OffsVal = DAG.getIntPtrConstant(Offs);
Bill Wendlinge1a90422009-12-21 23:10:19 +00003166
Dale Johannesen66978ee2009-01-31 02:22:37 +00003167 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Evan Chengb1032a82009-02-09 20:54:38 +00003168 OffsVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003169 continue;
3170 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003171
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003172 // N = N + Idx * ElementSize;
Dan Gohman7abbd042009-10-23 17:57:43 +00003173 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
3174 TD->getTypeAllocSize(Ty));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003175 SDValue IdxN = getValue(Idx);
3176
3177 // If the index is smaller or larger than intptr_t, truncate or extend
3178 // it.
Duncan Sands3a66a682009-10-13 21:04:12 +00003179 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003180
3181 // If this is a multiply by a power of two, turn it into a shl
3182 // immediately. This is a very common case.
3183 if (ElementSize != 1) {
Dan Gohman7abbd042009-10-23 17:57:43 +00003184 if (ElementSize.isPowerOf2()) {
3185 unsigned Amt = ElementSize.logBase2();
Scott Michelfdc40a02009-02-17 22:15:04 +00003186 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003187 N.getValueType(), IdxN,
Nadav Rotem16087692011-12-05 06:29:09 +00003188 DAG.getConstant(Amt, IdxN.getValueType()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003189 } else {
Duncan Sandsb2df01a2012-11-13 13:01:58 +00003190 SDValue Scale = DAG.getConstant(ElementSize, IdxN.getValueType());
Scott Michelfdc40a02009-02-17 22:15:04 +00003191 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003192 N.getValueType(), IdxN, Scale);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003193 }
3194 }
3195
Scott Michelfdc40a02009-02-17 22:15:04 +00003196 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003197 N.getValueType(), N, IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003198 }
3199 }
Bill Wendlinge1a90422009-12-21 23:10:19 +00003200
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003201 setValue(&I, N);
3202}
3203
Dan Gohman46510a72010-04-15 01:51:59 +00003204void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003205 // If this is a fixed sized alloca in the entry block of the function,
3206 // allocate it statically on the stack.
3207 if (FuncInfo.StaticAllocaMap.count(&I))
3208 return; // getValue will auto-populate this.
3209
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003210 Type *Ty = I.getAllocatedType();
Micah Villmow3574eca2012-10-08 16:38:25 +00003211 uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003212 unsigned Align =
Micah Villmow3574eca2012-10-08 16:38:25 +00003213 std::max((unsigned)TLI.getDataLayout()->getPrefTypeAlignment(Ty),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003214 I.getAlignment());
3215
3216 SDValue AllocSize = getValue(I.getArraySize());
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003217
Owen Andersone50ed302009-08-10 22:56:29 +00003218 EVT IntPtr = TLI.getPointerTy();
Dan Gohmanf75a7d32010-05-28 01:14:11 +00003219 if (AllocSize.getValueType() != IntPtr)
3220 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
3221
3222 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), IntPtr,
3223 AllocSize,
3224 DAG.getConstant(TySize, IntPtr));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003225
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003226 // Handle alignment. If the requested alignment is less than or equal to
3227 // the stack alignment, ignore it. If the size is greater than or equal to
3228 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
Anton Korobeynikov16c29b52011-01-10 12:39:04 +00003229 unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003230 if (Align <= StackAlign)
3231 Align = 0;
3232
3233 // Round the size of the allocation up to the stack alignment size
3234 // by add SA-1 to the size.
Scott Michelfdc40a02009-02-17 22:15:04 +00003235 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003236 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003237 DAG.getIntPtrConstant(StackAlign-1));
Bill Wendling856ff412009-12-22 00:12:37 +00003238
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003239 // Mask out the low bits for alignment purposes.
Scott Michelfdc40a02009-02-17 22:15:04 +00003240 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003241 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003242 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
3243
3244 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Owen Anderson825b72b2009-08-11 20:47:22 +00003245 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
Scott Michelfdc40a02009-02-17 22:15:04 +00003246 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00003247 VTs, Ops, 3);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003248 setValue(&I, DSA);
3249 DAG.setRoot(DSA.getValue(1));
Bill Wendling856ff412009-12-22 00:12:37 +00003250
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003251 // Inform the Frame Information that we have just allocated a variable-sized
3252 // object.
Eric Christopher2b8271e2010-07-17 00:28:22 +00003253 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003254}
3255
Dan Gohman46510a72010-04-15 01:51:59 +00003256void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
Eli Friedman327236c2011-08-24 20:50:09 +00003257 if (I.isAtomic())
3258 return visitAtomicLoad(I);
3259
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003260 const Value *SV = I.getOperand(0);
3261 SDValue Ptr = getValue(SV);
3262
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003263 Type *Ty = I.getType();
David Greene1e559442010-02-15 17:00:31 +00003264
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003265 bool isVolatile = I.isVolatile();
David Greene1e559442010-02-15 17:00:31 +00003266 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
Pete Cooperd752e0f2011-11-08 18:42:53 +00003267 bool isInvariant = I.getMetadata("invariant.load") != 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003268 unsigned Alignment = I.getAlignment();
Dan Gohmanf96e4bd2010-10-20 00:31:05 +00003269 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
Rafael Espindola95d594c2012-03-31 18:14:00 +00003270 const MDNode *Ranges = I.getMetadata(LLVMContext::MD_range);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003271
Owen Andersone50ed302009-08-10 22:56:29 +00003272 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003273 SmallVector<uint64_t, 4> Offsets;
3274 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
3275 unsigned NumValues = ValueVTs.size();
3276 if (NumValues == 0)
3277 return;
3278
3279 SDValue Root;
3280 bool ConstantMemory = false;
Andrew Trickde91f3c2010-11-12 17:50:46 +00003281 if (I.isVolatile() || NumValues > MaxParallelChains)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003282 // Serialize volatile loads with other side effects.
3283 Root = getRoot();
Dan Gohmanf96e4bd2010-10-20 00:31:05 +00003284 else if (AA->pointsToConstantMemory(
3285 AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), TBAAInfo))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003286 // Do not serialize (non-volatile) loads of constant memory with anything.
3287 Root = DAG.getEntryNode();
3288 ConstantMemory = true;
3289 } else {
3290 // Do not serialize non-volatile loads against each other.
3291 Root = DAG.getRoot();
3292 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003293
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003294 SmallVector<SDValue, 4> Values(NumValues);
Andrew Trickde91f3c2010-11-12 17:50:46 +00003295 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3296 NumValues));
Owen Andersone50ed302009-08-10 22:56:29 +00003297 EVT PtrVT = Ptr.getValueType();
Andrew Trickde91f3c2010-11-12 17:50:46 +00003298 unsigned ChainI = 0;
3299 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3300 // Serializing loads here may result in excessive register pressure, and
3301 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3302 // could recover a bit by hoisting nodes upward in the chain by recognizing
3303 // they are side-effect free or do not alias. The optimizer should really
3304 // avoid this case by converting large object/array copies to llvm.memcpy
3305 // (MaxParallelChains should always remain as failsafe).
3306 if (ChainI == MaxParallelChains) {
3307 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3308 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3309 MVT::Other, &Chains[0], ChainI);
3310 Root = Chain;
3311 ChainI = 0;
3312 }
Bill Wendling856ff412009-12-22 00:12:37 +00003313 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
3314 PtrVT, Ptr,
3315 DAG.getConstant(Offsets[i], PtrVT));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003316 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
Michael J. Spencere70c5262010-10-16 08:25:21 +00003317 A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
Rafael Espindola95d594c2012-03-31 18:14:00 +00003318 isNonTemporal, isInvariant, Alignment, TBAAInfo,
3319 Ranges);
Bill Wendling856ff412009-12-22 00:12:37 +00003320
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003321 Values[i] = L;
Andrew Trickde91f3c2010-11-12 17:50:46 +00003322 Chains[ChainI] = L.getValue(1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003323 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003324
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003325 if (!ConstantMemory) {
Scott Michelfdc40a02009-02-17 22:15:04 +00003326 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Andrew Trickde91f3c2010-11-12 17:50:46 +00003327 MVT::Other, &Chains[0], ChainI);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003328 if (isVolatile)
3329 DAG.setRoot(Chain);
3330 else
3331 PendingLoads.push_back(Chain);
3332 }
3333
Bill Wendling4533cac2010-01-28 21:51:40 +00003334 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
3335 DAG.getVTList(&ValueVTs[0], NumValues),
3336 &Values[0], NumValues));
Bill Wendling856ff412009-12-22 00:12:37 +00003337}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003338
Dan Gohman46510a72010-04-15 01:51:59 +00003339void SelectionDAGBuilder::visitStore(const StoreInst &I) {
Eli Friedman327236c2011-08-24 20:50:09 +00003340 if (I.isAtomic())
3341 return visitAtomicStore(I);
3342
Dan Gohman46510a72010-04-15 01:51:59 +00003343 const Value *SrcV = I.getOperand(0);
3344 const Value *PtrV = I.getOperand(1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003345
Owen Andersone50ed302009-08-10 22:56:29 +00003346 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003347 SmallVector<uint64_t, 4> Offsets;
3348 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
3349 unsigned NumValues = ValueVTs.size();
3350 if (NumValues == 0)
3351 return;
3352
3353 // Get the lowered operands. Note that we do this after
3354 // checking if NumResults is zero, because with zero results
3355 // the operands won't have values in the map.
3356 SDValue Src = getValue(SrcV);
3357 SDValue Ptr = getValue(PtrV);
3358
3359 SDValue Root = getRoot();
Andrew Trickde91f3c2010-11-12 17:50:46 +00003360 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3361 NumValues));
Owen Andersone50ed302009-08-10 22:56:29 +00003362 EVT PtrVT = Ptr.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003363 bool isVolatile = I.isVolatile();
David Greene1e559442010-02-15 17:00:31 +00003364 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003365 unsigned Alignment = I.getAlignment();
Dan Gohmanf96e4bd2010-10-20 00:31:05 +00003366 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
Bill Wendling856ff412009-12-22 00:12:37 +00003367
Andrew Trickde91f3c2010-11-12 17:50:46 +00003368 unsigned ChainI = 0;
3369 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3370 // See visitLoad comments.
3371 if (ChainI == MaxParallelChains) {
3372 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3373 MVT::Other, &Chains[0], ChainI);
3374 Root = Chain;
3375 ChainI = 0;
3376 }
Bill Wendling856ff412009-12-22 00:12:37 +00003377 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
3378 DAG.getConstant(Offsets[i], PtrVT));
Andrew Trickde91f3c2010-11-12 17:50:46 +00003379 SDValue St = DAG.getStore(Root, getCurDebugLoc(),
3380 SDValue(Src.getNode(), Src.getResNo() + i),
3381 Add, MachinePointerInfo(PtrV, Offsets[i]),
3382 isVolatile, isNonTemporal, Alignment, TBAAInfo);
3383 Chains[ChainI] = St;
Bill Wendling856ff412009-12-22 00:12:37 +00003384 }
3385
Devang Patel7e13efa2010-10-26 22:14:52 +00003386 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Andrew Trickde91f3c2010-11-12 17:50:46 +00003387 MVT::Other, &Chains[0], ChainI);
Devang Patel7e13efa2010-10-26 22:14:52 +00003388 ++SDNodeOrder;
3389 AssignOrderingToNode(StoreNode.getNode());
3390 DAG.setRoot(StoreNode);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003391}
3392
Eli Friedman26689ac2011-08-03 21:06:02 +00003393static SDValue InsertFenceForAtomic(SDValue Chain, AtomicOrdering Order,
Eli Friedman327236c2011-08-24 20:50:09 +00003394 SynchronizationScope Scope,
Eli Friedman26689ac2011-08-03 21:06:02 +00003395 bool Before, DebugLoc dl,
3396 SelectionDAG &DAG,
3397 const TargetLowering &TLI) {
3398 // Fence, if necessary
3399 if (Before) {
Eli Friedman069e2ed2011-08-26 02:59:24 +00003400 if (Order == AcquireRelease || Order == SequentiallyConsistent)
Eli Friedman26689ac2011-08-03 21:06:02 +00003401 Order = Release;
3402 else if (Order == Acquire || Order == Monotonic)
3403 return Chain;
3404 } else {
3405 if (Order == AcquireRelease)
3406 Order = Acquire;
3407 else if (Order == Release || Order == Monotonic)
3408 return Chain;
3409 }
3410 SDValue Ops[3];
3411 Ops[0] = Chain;
Eli Friedman327236c2011-08-24 20:50:09 +00003412 Ops[1] = DAG.getConstant(Order, TLI.getPointerTy());
3413 Ops[2] = DAG.getConstant(Scope, TLI.getPointerTy());
Eli Friedman26689ac2011-08-03 21:06:02 +00003414 return DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3);
3415}
3416
Eli Friedmanff030482011-07-28 21:48:00 +00003417void SelectionDAGBuilder::visitAtomicCmpXchg(const AtomicCmpXchgInst &I) {
Eli Friedman26689ac2011-08-03 21:06:02 +00003418 DebugLoc dl = getCurDebugLoc();
3419 AtomicOrdering Order = I.getOrdering();
Eli Friedman327236c2011-08-24 20:50:09 +00003420 SynchronizationScope Scope = I.getSynchScope();
Eli Friedman26689ac2011-08-03 21:06:02 +00003421
3422 SDValue InChain = getRoot();
3423
3424 if (TLI.getInsertFencesForAtomic())
Eli Friedman327236c2011-08-24 20:50:09 +00003425 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
3426 DAG, TLI);
Eli Friedman26689ac2011-08-03 21:06:02 +00003427
Eli Friedman55ba8162011-07-29 03:05:32 +00003428 SDValue L =
Eli Friedman26689ac2011-08-03 21:06:02 +00003429 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl,
Eli Friedman55ba8162011-07-29 03:05:32 +00003430 getValue(I.getCompareOperand()).getValueType().getSimpleVT(),
Eli Friedman26689ac2011-08-03 21:06:02 +00003431 InChain,
Eli Friedman55ba8162011-07-29 03:05:32 +00003432 getValue(I.getPointerOperand()),
3433 getValue(I.getCompareOperand()),
3434 getValue(I.getNewValOperand()),
3435 MachinePointerInfo(I.getPointerOperand()), 0 /* Alignment */,
Eli Friedman327236c2011-08-24 20:50:09 +00003436 TLI.getInsertFencesForAtomic() ? Monotonic : Order,
3437 Scope);
Eli Friedman26689ac2011-08-03 21:06:02 +00003438
3439 SDValue OutChain = L.getValue(1);
3440
3441 if (TLI.getInsertFencesForAtomic())
Eli Friedman327236c2011-08-24 20:50:09 +00003442 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3443 DAG, TLI);
Eli Friedman26689ac2011-08-03 21:06:02 +00003444
Eli Friedman55ba8162011-07-29 03:05:32 +00003445 setValue(&I, L);
Eli Friedman26689ac2011-08-03 21:06:02 +00003446 DAG.setRoot(OutChain);
Eli Friedmanff030482011-07-28 21:48:00 +00003447}
3448
3449void SelectionDAGBuilder::visitAtomicRMW(const AtomicRMWInst &I) {
Eli Friedman26689ac2011-08-03 21:06:02 +00003450 DebugLoc dl = getCurDebugLoc();
Eli Friedman55ba8162011-07-29 03:05:32 +00003451 ISD::NodeType NT;
3452 switch (I.getOperation()) {
David Blaikie4d6ccb52012-01-20 21:51:11 +00003453 default: llvm_unreachable("Unknown atomicrmw operation");
Eli Friedman55ba8162011-07-29 03:05:32 +00003454 case AtomicRMWInst::Xchg: NT = ISD::ATOMIC_SWAP; break;
3455 case AtomicRMWInst::Add: NT = ISD::ATOMIC_LOAD_ADD; break;
3456 case AtomicRMWInst::Sub: NT = ISD::ATOMIC_LOAD_SUB; break;
3457 case AtomicRMWInst::And: NT = ISD::ATOMIC_LOAD_AND; break;
3458 case AtomicRMWInst::Nand: NT = ISD::ATOMIC_LOAD_NAND; break;
3459 case AtomicRMWInst::Or: NT = ISD::ATOMIC_LOAD_OR; break;
3460 case AtomicRMWInst::Xor: NT = ISD::ATOMIC_LOAD_XOR; break;
3461 case AtomicRMWInst::Max: NT = ISD::ATOMIC_LOAD_MAX; break;
3462 case AtomicRMWInst::Min: NT = ISD::ATOMIC_LOAD_MIN; break;
3463 case AtomicRMWInst::UMax: NT = ISD::ATOMIC_LOAD_UMAX; break;
3464 case AtomicRMWInst::UMin: NT = ISD::ATOMIC_LOAD_UMIN; break;
3465 }
Eli Friedman26689ac2011-08-03 21:06:02 +00003466 AtomicOrdering Order = I.getOrdering();
Eli Friedman327236c2011-08-24 20:50:09 +00003467 SynchronizationScope Scope = I.getSynchScope();
Eli Friedman26689ac2011-08-03 21:06:02 +00003468
3469 SDValue InChain = getRoot();
3470
3471 if (TLI.getInsertFencesForAtomic())
Eli Friedman327236c2011-08-24 20:50:09 +00003472 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
3473 DAG, TLI);
Eli Friedman26689ac2011-08-03 21:06:02 +00003474
Eli Friedman55ba8162011-07-29 03:05:32 +00003475 SDValue L =
Eli Friedman26689ac2011-08-03 21:06:02 +00003476 DAG.getAtomic(NT, dl,
Eli Friedman55ba8162011-07-29 03:05:32 +00003477 getValue(I.getValOperand()).getValueType().getSimpleVT(),
Eli Friedman26689ac2011-08-03 21:06:02 +00003478 InChain,
Eli Friedman55ba8162011-07-29 03:05:32 +00003479 getValue(I.getPointerOperand()),
3480 getValue(I.getValOperand()),
3481 I.getPointerOperand(), 0 /* Alignment */,
Eli Friedman26689ac2011-08-03 21:06:02 +00003482 TLI.getInsertFencesForAtomic() ? Monotonic : Order,
Eli Friedman327236c2011-08-24 20:50:09 +00003483 Scope);
Eli Friedman26689ac2011-08-03 21:06:02 +00003484
3485 SDValue OutChain = L.getValue(1);
3486
3487 if (TLI.getInsertFencesForAtomic())
Eli Friedman327236c2011-08-24 20:50:09 +00003488 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3489 DAG, TLI);
Eli Friedman26689ac2011-08-03 21:06:02 +00003490
Eli Friedman55ba8162011-07-29 03:05:32 +00003491 setValue(&I, L);
Eli Friedman26689ac2011-08-03 21:06:02 +00003492 DAG.setRoot(OutChain);
Eli Friedmanff030482011-07-28 21:48:00 +00003493}
3494
Eli Friedman47f35132011-07-25 23:16:38 +00003495void SelectionDAGBuilder::visitFence(const FenceInst &I) {
Eli Friedman14648462011-07-27 22:21:52 +00003496 DebugLoc dl = getCurDebugLoc();
3497 SDValue Ops[3];
3498 Ops[0] = getRoot();
3499 Ops[1] = DAG.getConstant(I.getOrdering(), TLI.getPointerTy());
3500 Ops[2] = DAG.getConstant(I.getSynchScope(), TLI.getPointerTy());
3501 DAG.setRoot(DAG.getNode(ISD::ATOMIC_FENCE, dl, MVT::Other, Ops, 3));
Eli Friedman47f35132011-07-25 23:16:38 +00003502}
3503
Eli Friedman327236c2011-08-24 20:50:09 +00003504void SelectionDAGBuilder::visitAtomicLoad(const LoadInst &I) {
3505 DebugLoc dl = getCurDebugLoc();
3506 AtomicOrdering Order = I.getOrdering();
3507 SynchronizationScope Scope = I.getSynchScope();
3508
3509 SDValue InChain = getRoot();
3510
Eli Friedmanfd45fa12012-08-17 23:24:29 +00003511 EVT VT = TLI.getValueType(I.getType());
Eli Friedman327236c2011-08-24 20:50:09 +00003512
Eli Friedman596f4472011-09-13 22:19:59 +00003513 if (I.getAlignment() * 8 < VT.getSizeInBits())
Eli Friedmanfe731212011-09-13 20:50:54 +00003514 report_fatal_error("Cannot generate unaligned atomic load");
3515
Eli Friedman327236c2011-08-24 20:50:09 +00003516 SDValue L =
3517 DAG.getAtomic(ISD::ATOMIC_LOAD, dl, VT, VT, InChain,
3518 getValue(I.getPointerOperand()),
3519 I.getPointerOperand(), I.getAlignment(),
3520 TLI.getInsertFencesForAtomic() ? Monotonic : Order,
3521 Scope);
3522
3523 SDValue OutChain = L.getValue(1);
3524
3525 if (TLI.getInsertFencesForAtomic())
3526 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3527 DAG, TLI);
3528
3529 setValue(&I, L);
3530 DAG.setRoot(OutChain);
3531}
3532
3533void SelectionDAGBuilder::visitAtomicStore(const StoreInst &I) {
3534 DebugLoc dl = getCurDebugLoc();
3535
3536 AtomicOrdering Order = I.getOrdering();
3537 SynchronizationScope Scope = I.getSynchScope();
3538
3539 SDValue InChain = getRoot();
3540
Eli Friedmanfd45fa12012-08-17 23:24:29 +00003541 EVT VT = TLI.getValueType(I.getValueOperand()->getType());
Eli Friedmanfe731212011-09-13 20:50:54 +00003542
Eli Friedman596f4472011-09-13 22:19:59 +00003543 if (I.getAlignment() * 8 < VT.getSizeInBits())
Eli Friedmanfe731212011-09-13 20:50:54 +00003544 report_fatal_error("Cannot generate unaligned atomic store");
3545
Eli Friedman327236c2011-08-24 20:50:09 +00003546 if (TLI.getInsertFencesForAtomic())
3547 InChain = InsertFenceForAtomic(InChain, Order, Scope, true, dl,
3548 DAG, TLI);
3549
3550 SDValue OutChain =
Eli Friedmanfe731212011-09-13 20:50:54 +00003551 DAG.getAtomic(ISD::ATOMIC_STORE, dl, VT,
Eli Friedman327236c2011-08-24 20:50:09 +00003552 InChain,
3553 getValue(I.getPointerOperand()),
3554 getValue(I.getValueOperand()),
3555 I.getPointerOperand(), I.getAlignment(),
3556 TLI.getInsertFencesForAtomic() ? Monotonic : Order,
3557 Scope);
3558
3559 if (TLI.getInsertFencesForAtomic())
3560 OutChain = InsertFenceForAtomic(OutChain, Order, Scope, false, dl,
3561 DAG, TLI);
3562
3563 DAG.setRoot(OutChain);
3564}
3565
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003566/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3567/// node.
Dan Gohman46510a72010-04-15 01:51:59 +00003568void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
Dan Gohman2048b852009-11-23 18:04:58 +00003569 unsigned Intrinsic) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003570 bool HasChain = !I.doesNotAccessMemory();
3571 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3572
3573 // Build the operand list.
3574 SmallVector<SDValue, 8> Ops;
3575 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3576 if (OnlyLoad) {
3577 // We don't need to serialize loads against other loads.
3578 Ops.push_back(DAG.getRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003579 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003580 Ops.push_back(getRoot());
3581 }
3582 }
Mon P Wang3efcd4a2008-11-01 20:24:53 +00003583
3584 // Info is set by getTgtMemInstrinsic
3585 TargetLowering::IntrinsicInfo Info;
3586 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
3587
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003588 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Bob Wilson65ffec42010-09-21 17:56:22 +00003589 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3590 Info.opc == ISD::INTRINSIC_W_CHAIN)
Pete Cooperbf421392012-01-16 04:08:12 +00003591 Ops.push_back(DAG.getTargetConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003592
3593 // Add all operands of the call to the operand list.
Gabor Greif0635f352010-06-25 09:38:13 +00003594 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3595 SDValue Op = getValue(I.getArgOperand(i));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003596 Ops.push_back(Op);
3597 }
3598
Owen Andersone50ed302009-08-10 22:56:29 +00003599 SmallVector<EVT, 4> ValueVTs;
Bob Wilson8d919552009-07-31 22:41:21 +00003600 ComputeValueVTs(TLI, I.getType(), ValueVTs);
Bill Wendling856ff412009-12-22 00:12:37 +00003601
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003602 if (HasChain)
Owen Anderson825b72b2009-08-11 20:47:22 +00003603 ValueVTs.push_back(MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003604
Bob Wilson8d919552009-07-31 22:41:21 +00003605 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003606
3607 // Create the node.
3608 SDValue Result;
Mon P Wang3efcd4a2008-11-01 20:24:53 +00003609 if (IsTgtIntrinsic) {
3610 // This is target intrinsic that touches memory
Dale Johannesen66978ee2009-01-31 02:22:37 +00003611 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00003612 VTs, &Ops[0], Ops.size(),
Chris Lattnere9ba5dd2010-09-21 04:57:15 +00003613 Info.memVT,
3614 MachinePointerInfo(Info.ptrVal, Info.offset),
Mon P Wang3efcd4a2008-11-01 20:24:53 +00003615 Info.align, Info.vol,
3616 Info.readMem, Info.writeMem);
Bill Wendling856ff412009-12-22 00:12:37 +00003617 } else if (!HasChain) {
Scott Michelfdc40a02009-02-17 22:15:04 +00003618 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00003619 VTs, &Ops[0], Ops.size());
Benjamin Kramerf0127052010-01-05 13:12:22 +00003620 } else if (!I.getType()->isVoidTy()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00003621 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00003622 VTs, &Ops[0], Ops.size());
Bill Wendling856ff412009-12-22 00:12:37 +00003623 } else {
Scott Michelfdc40a02009-02-17 22:15:04 +00003624 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00003625 VTs, &Ops[0], Ops.size());
Bill Wendling856ff412009-12-22 00:12:37 +00003626 }
3627
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003628 if (HasChain) {
3629 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3630 if (OnlyLoad)
3631 PendingLoads.push_back(Chain);
3632 else
3633 DAG.setRoot(Chain);
3634 }
Bill Wendling856ff412009-12-22 00:12:37 +00003635
Benjamin Kramerf0127052010-01-05 13:12:22 +00003636 if (!I.getType()->isVoidTy()) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00003637 if (VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Owen Andersone50ed302009-08-10 22:56:29 +00003638 EVT VT = TLI.getValueType(PTy);
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003639 Result = DAG.getNode(ISD::BITCAST, getCurDebugLoc(), VT, Result);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003640 }
Bill Wendling856ff412009-12-22 00:12:37 +00003641
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003642 setValue(&I, Result);
Evan Cheng5aef7952012-03-22 19:29:09 +00003643 } else {
3644 // Assign order to result here. If the intrinsic does not produce a result,
3645 // it won't be mapped to a SDNode and visit() will not assign it an order
3646 // number.
3647 ++SDNodeOrder;
3648 AssignOrderingToNode(Result.getNode());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003649 }
3650}
3651
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003652/// GetSignificand - Get the significand and build it into a floating-point
3653/// number with exponent of 1:
3654///
3655/// Op = (Op & 0x007fffff) | 0x3f800000;
3656///
3657/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003658static SDValue
Bill Wendling46ada192010-03-02 01:55:18 +00003659GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
Owen Anderson825b72b2009-08-11 20:47:22 +00003660 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3661 DAG.getConstant(0x007fffff, MVT::i32));
3662 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3663 DAG.getConstant(0x3f800000, MVT::i32));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003664 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003665}
3666
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003667/// GetExponent - Get the exponent:
3668///
Bill Wendlinge9a72862009-01-20 21:17:57 +00003669/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003670///
3671/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003672static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003673GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
Bill Wendling46ada192010-03-02 01:55:18 +00003674 DebugLoc dl) {
Owen Anderson825b72b2009-08-11 20:47:22 +00003675 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3676 DAG.getConstant(0x7f800000, MVT::i32));
3677 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
Duncan Sands92abc622009-01-31 15:50:11 +00003678 DAG.getConstant(23, TLI.getPointerTy()));
Owen Anderson825b72b2009-08-11 20:47:22 +00003679 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3680 DAG.getConstant(127, MVT::i32));
Bill Wendling4533cac2010-01-28 21:51:40 +00003681 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003682}
3683
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003684/// getF32Constant - Get 32-bit floating point constant.
3685static SDValue
3686getF32Constant(SelectionDAG &DAG, unsigned Flt) {
Owen Anderson825b72b2009-08-11 20:47:22 +00003687 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003688}
3689
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003690/// visitExp - Lower an exp intrinsic. Handles the special sequences for
3691/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003692void
Dan Gohman46510a72010-04-15 01:51:59 +00003693SelectionDAGBuilder::visitExp(const CallInst &I) {
Dale Johannesen59e577f2008-09-05 18:38:42 +00003694 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003695 DebugLoc dl = getCurDebugLoc();
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003696
Gabor Greif0635f352010-06-25 09:38:13 +00003697 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003698 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Gabor Greif0635f352010-06-25 09:38:13 +00003699 SDValue Op = getValue(I.getArgOperand(0));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003700
3701 // Put the exponent in the right bit position for later addition to the
3702 // final result:
3703 //
3704 // #define LOG2OFe 1.4426950f
3705 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
Owen Anderson825b72b2009-08-11 20:47:22 +00003706 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003707 getF32Constant(DAG, 0x3fb8aa3b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003708 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003709
3710 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00003711 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3712 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003713
3714 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00003715 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003716 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendling856ff412009-12-22 00:12:37 +00003717
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003718 if (LimitFloatPrecision <= 6) {
3719 // For floating-point precision of 6:
3720 //
3721 // TwoToFractionalPartOfX =
3722 // 0.997535578f +
3723 // (0.735607626f + 0.252464424f * x) * x;
3724 //
3725 // error 0.0144103317, which is 6 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, 0x3e814304));
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, 0x3f3c50c8));
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, 0x3f7f5e7e));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003733 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,MVT::i32, t5);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003734
3735 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00003736 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003737 TwoToFracPartOfX, IntegerPartOfX);
3738
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003739 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t6);
Craig Topper08ac4692012-11-16 20:01:39 +00003740 } else if (LimitFloatPrecision <= 12) {
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003741 // For floating-point precision of 12:
3742 //
3743 // TwoToFractionalPartOfX =
3744 // 0.999892986f +
3745 // (0.696457318f +
3746 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3747 //
3748 // 0.000107046256 error, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003749 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003750 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003751 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003752 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003753 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3754 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003755 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00003756 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3757 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003758 getF32Constant(DAG, 0x3f7ff8fd));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003759 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,MVT::i32, t7);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003760
3761 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00003762 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003763 TwoToFracPartOfX, IntegerPartOfX);
3764
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003765 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t8);
Craig Topper08ac4692012-11-16 20:01:39 +00003766 } else { // LimitFloatPrecision <= 18
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003767 // For floating-point precision of 18:
3768 //
3769 // TwoToFractionalPartOfX =
3770 // 0.999999982f +
3771 // (0.693148872f +
3772 // (0.240227044f +
3773 // (0.554906021e-1f +
3774 // (0.961591928e-2f +
3775 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3776 //
3777 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003778 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003779 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003780 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003781 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003782 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3783 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003784 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003785 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3786 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003787 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003788 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3789 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003790 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003791 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3792 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003793 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003794 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3795 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003796 getF32Constant(DAG, 0x3f800000));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003797 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003798 MVT::i32, t13);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003799
3800 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00003801 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003802 TwoToFracPartOfX, IntegerPartOfX);
3803
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003804 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t14);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003805 }
3806 } else {
3807 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003808 result = DAG.getNode(ISD::FEXP, dl,
Gabor Greif0635f352010-06-25 09:38:13 +00003809 getValue(I.getArgOperand(0)).getValueType(),
3810 getValue(I.getArgOperand(0)));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003811 }
3812
Dale Johannesen59e577f2008-09-05 18:38:42 +00003813 setValue(&I, result);
3814}
3815
Bill Wendling39150252008-09-09 20:39:27 +00003816/// visitLog - Lower a log intrinsic. Handles the special sequences for
3817/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003818void
Dan Gohman46510a72010-04-15 01:51:59 +00003819SelectionDAGBuilder::visitLog(const CallInst &I) {
Dale Johannesen59e577f2008-09-05 18:38:42 +00003820 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003821 DebugLoc dl = getCurDebugLoc();
Bill Wendling39150252008-09-09 20:39:27 +00003822
Gabor Greif0635f352010-06-25 09:38:13 +00003823 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
Bill Wendling39150252008-09-09 20:39:27 +00003824 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Gabor Greif0635f352010-06-25 09:38:13 +00003825 SDValue Op = getValue(I.getArgOperand(0));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003826 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
Bill Wendling39150252008-09-09 20:39:27 +00003827
3828 // Scale the exponent by log(2) [0.69314718f].
Bill Wendling46ada192010-03-02 01:55:18 +00003829 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Owen Anderson825b72b2009-08-11 20:47:22 +00003830 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003831 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003832
3833 // Get the significand and build it into a floating-point number with
3834 // exponent of 1.
Bill Wendling46ada192010-03-02 01:55:18 +00003835 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling39150252008-09-09 20:39:27 +00003836
Craig Topperdf0ea8d2012-11-16 19:08:44 +00003837 SDValue LogOfMantissa;
Bill Wendling39150252008-09-09 20:39:27 +00003838 if (LimitFloatPrecision <= 6) {
3839 // For floating-point precision of 6:
3840 //
3841 // LogofMantissa =
3842 // -1.1609546f +
3843 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003844 //
Bill Wendling39150252008-09-09 20:39:27 +00003845 // error 0.0034276066, which is better than 8 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003846 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003847 getF32Constant(DAG, 0xbe74c456));
Owen Anderson825b72b2009-08-11 20:47:22 +00003848 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003849 getF32Constant(DAG, 0x3fb3a2b1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003850 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00003851 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3852 getF32Constant(DAG, 0x3f949a29));
Craig Topper08ac4692012-11-16 20:01:39 +00003853 } else if (LimitFloatPrecision <= 12) {
Bill Wendling39150252008-09-09 20:39:27 +00003854 // For floating-point precision of 12:
3855 //
3856 // LogOfMantissa =
3857 // -1.7417939f +
3858 // (2.8212026f +
3859 // (-1.4699568f +
3860 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3861 //
3862 // error 0.000061011436, which is 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003863 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003864 getF32Constant(DAG, 0xbd67b6d6));
Owen Anderson825b72b2009-08-11 20:47:22 +00003865 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003866 getF32Constant(DAG, 0x3ee4f4b8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003867 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3868 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003869 getF32Constant(DAG, 0x3fbc278b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003870 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3871 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003872 getF32Constant(DAG, 0x40348e95));
Owen Anderson825b72b2009-08-11 20:47:22 +00003873 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00003874 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3875 getF32Constant(DAG, 0x3fdef31a));
Craig Topper08ac4692012-11-16 20:01:39 +00003876 } else { // LimitFloatPrecision <= 18
Bill Wendling39150252008-09-09 20:39:27 +00003877 // For floating-point precision of 18:
3878 //
3879 // LogOfMantissa =
3880 // -2.1072184f +
3881 // (4.2372794f +
3882 // (-3.7029485f +
3883 // (2.2781945f +
3884 // (-0.87823314f +
3885 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3886 //
3887 // error 0.0000023660568, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003888 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003889 getF32Constant(DAG, 0xbc91e5ac));
Owen Anderson825b72b2009-08-11 20:47:22 +00003890 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003891 getF32Constant(DAG, 0x3e4350aa));
Owen Anderson825b72b2009-08-11 20:47:22 +00003892 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3893 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003894 getF32Constant(DAG, 0x3f60d3e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003895 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3896 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003897 getF32Constant(DAG, 0x4011cdf0));
Owen Anderson825b72b2009-08-11 20:47:22 +00003898 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3899 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003900 getF32Constant(DAG, 0x406cfd1c));
Owen Anderson825b72b2009-08-11 20:47:22 +00003901 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3902 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003903 getF32Constant(DAG, 0x408797cb));
Owen Anderson825b72b2009-08-11 20:47:22 +00003904 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00003905 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3906 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003907 }
Craig Topperdf0ea8d2012-11-16 19:08:44 +00003908
3909 result = DAG.getNode(ISD::FADD, dl,
3910 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003911 } else {
3912 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003913 result = DAG.getNode(ISD::FLOG, dl,
Gabor Greif0635f352010-06-25 09:38:13 +00003914 getValue(I.getArgOperand(0)).getValueType(),
3915 getValue(I.getArgOperand(0)));
Bill Wendling39150252008-09-09 20:39:27 +00003916 }
3917
Dale Johannesen59e577f2008-09-05 18:38:42 +00003918 setValue(&I, result);
3919}
3920
Bill Wendling3eb59402008-09-09 00:28:24 +00003921/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3922/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003923void
Dan Gohman46510a72010-04-15 01:51:59 +00003924SelectionDAGBuilder::visitLog2(const CallInst &I) {
Dale Johannesen59e577f2008-09-05 18:38:42 +00003925 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003926 DebugLoc dl = getCurDebugLoc();
Bill Wendling3eb59402008-09-09 00:28:24 +00003927
Gabor Greif0635f352010-06-25 09:38:13 +00003928 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003929 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Gabor Greif0635f352010-06-25 09:38:13 +00003930 SDValue Op = getValue(I.getArgOperand(0));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003931 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003932
Bill Wendling39150252008-09-09 20:39:27 +00003933 // Get the exponent.
Bill Wendling46ada192010-03-02 01:55:18 +00003934 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
Bill Wendling856ff412009-12-22 00:12:37 +00003935
Bill Wendling3eb59402008-09-09 00:28:24 +00003936 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003937 // exponent of 1.
Bill Wendling46ada192010-03-02 01:55:18 +00003938 SDValue X = GetSignificand(DAG, Op1, dl);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003939
Bill Wendling3eb59402008-09-09 00:28:24 +00003940 // Different possible minimax approximations of significand in
3941 // floating-point for various degrees of accuracy over [1,2].
Craig Topperdf0ea8d2012-11-16 19:08:44 +00003942 SDValue Log2ofMantissa;
Bill Wendling3eb59402008-09-09 00:28:24 +00003943 if (LimitFloatPrecision <= 6) {
3944 // For floating-point precision of 6:
3945 //
3946 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3947 //
3948 // error 0.0049451742, which is more than 7 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003949 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003950 getF32Constant(DAG, 0xbeb08fe0));
Owen Anderson825b72b2009-08-11 20:47:22 +00003951 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003952 getF32Constant(DAG, 0x40019463));
Owen Anderson825b72b2009-08-11 20:47:22 +00003953 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00003954 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3955 getF32Constant(DAG, 0x3fd6633d));
Craig Topper08ac4692012-11-16 20:01:39 +00003956 } else if (LimitFloatPrecision <= 12) {
Bill Wendling3eb59402008-09-09 00:28:24 +00003957 // For floating-point precision of 12:
3958 //
3959 // Log2ofMantissa =
3960 // -2.51285454f +
3961 // (4.07009056f +
3962 // (-2.12067489f +
3963 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003964 //
Bill Wendling3eb59402008-09-09 00:28:24 +00003965 // error 0.0000876136000, which is better than 13 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003966 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003967 getF32Constant(DAG, 0xbda7262e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003968 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003969 getF32Constant(DAG, 0x3f25280b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003970 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3971 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003972 getF32Constant(DAG, 0x4007b923));
Owen Anderson825b72b2009-08-11 20:47:22 +00003973 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3974 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003975 getF32Constant(DAG, 0x40823e2f));
Owen Anderson825b72b2009-08-11 20:47:22 +00003976 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00003977 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3978 getF32Constant(DAG, 0x4020d29c));
Craig Topper08ac4692012-11-16 20:01:39 +00003979 } else { // LimitFloatPrecision <= 18
Bill Wendling3eb59402008-09-09 00:28:24 +00003980 // For floating-point precision of 18:
3981 //
3982 // Log2ofMantissa =
3983 // -3.0400495f +
3984 // (6.1129976f +
3985 // (-5.3420409f +
3986 // (3.2865683f +
3987 // (-1.2669343f +
3988 // (0.27515199f -
3989 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3990 //
3991 // error 0.0000018516, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003992 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003993 getF32Constant(DAG, 0xbcd2769e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003994 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003995 getF32Constant(DAG, 0x3e8ce0b9));
Owen Anderson825b72b2009-08-11 20:47:22 +00003996 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3997 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003998 getF32Constant(DAG, 0x3fa22ae7));
Owen Anderson825b72b2009-08-11 20:47:22 +00003999 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4000 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004001 getF32Constant(DAG, 0x40525723));
Owen Anderson825b72b2009-08-11 20:47:22 +00004002 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4003 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004004 getF32Constant(DAG, 0x40aaf200));
Owen Anderson825b72b2009-08-11 20:47:22 +00004005 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4006 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004007 getF32Constant(DAG, 0x40c39dad));
Owen Anderson825b72b2009-08-11 20:47:22 +00004008 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00004009 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
4010 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00004011 }
Craig Topperdf0ea8d2012-11-16 19:08:44 +00004012
4013 result = DAG.getNode(ISD::FADD, dl,
4014 MVT::f32, LogOfExponent, Log2ofMantissa);
Dale Johannesen853244f2008-09-05 23:49:37 +00004015 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00004016 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004017 result = DAG.getNode(ISD::FLOG2, dl,
Gabor Greif0635f352010-06-25 09:38:13 +00004018 getValue(I.getArgOperand(0)).getValueType(),
4019 getValue(I.getArgOperand(0)));
Dale Johannesen853244f2008-09-05 23:49:37 +00004020 }
Bill Wendling3eb59402008-09-09 00:28:24 +00004021
Dale Johannesen59e577f2008-09-05 18:38:42 +00004022 setValue(&I, result);
4023}
4024
Bill Wendling3eb59402008-09-09 00:28:24 +00004025/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
4026/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00004027void
Dan Gohman46510a72010-04-15 01:51:59 +00004028SelectionDAGBuilder::visitLog10(const CallInst &I) {
Dale Johannesen59e577f2008-09-05 18:38:42 +00004029 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00004030 DebugLoc dl = getCurDebugLoc();
Bill Wendling181b6272008-10-19 20:34:04 +00004031
Gabor Greif0635f352010-06-25 09:38:13 +00004032 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00004033 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Gabor Greif0635f352010-06-25 09:38:13 +00004034 SDValue Op = getValue(I.getArgOperand(0));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004035 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00004036
Bill Wendling39150252008-09-09 20:39:27 +00004037 // Scale the exponent by log10(2) [0.30102999f].
Bill Wendling46ada192010-03-02 01:55:18 +00004038 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Owen Anderson825b72b2009-08-11 20:47:22 +00004039 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004040 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00004041
4042 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00004043 // exponent of 1.
Bill Wendling46ada192010-03-02 01:55:18 +00004044 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00004045
Craig Topperdf0ea8d2012-11-16 19:08:44 +00004046 SDValue Log10ofMantissa;
Bill Wendling3eb59402008-09-09 00:28:24 +00004047 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00004048 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004049 //
Bill Wendlingbd297bc2008-09-09 18:42:23 +00004050 // Log10ofMantissa =
4051 // -0.50419619f +
4052 // (0.60948995f - 0.10380950f * x) * x;
4053 //
4054 // error 0.0014886165, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004055 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004056 getF32Constant(DAG, 0xbdd49a13));
Owen Anderson825b72b2009-08-11 20:47:22 +00004057 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004058 getF32Constant(DAG, 0x3f1c0789));
Owen Anderson825b72b2009-08-11 20:47:22 +00004059 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00004060 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4061 getF32Constant(DAG, 0x3f011300));
Craig Topper08ac4692012-11-16 20:01:39 +00004062 } else if (LimitFloatPrecision <= 12) {
Bill Wendling3eb59402008-09-09 00:28:24 +00004063 // For floating-point precision of 12:
4064 //
4065 // Log10ofMantissa =
4066 // -0.64831180f +
4067 // (0.91751397f +
4068 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4069 //
4070 // error 0.00019228036, which is better than 12 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004071 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004072 getF32Constant(DAG, 0x3d431f31));
Owen Anderson825b72b2009-08-11 20:47:22 +00004073 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004074 getF32Constant(DAG, 0x3ea21fb2));
Owen Anderson825b72b2009-08-11 20:47:22 +00004075 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4076 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004077 getF32Constant(DAG, 0x3f6ae232));
Owen Anderson825b72b2009-08-11 20:47:22 +00004078 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00004079 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4080 getF32Constant(DAG, 0x3f25f7c3));
Craig Topper08ac4692012-11-16 20:01:39 +00004081 } else { // LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00004082 // For floating-point precision of 18:
4083 //
4084 // Log10ofMantissa =
4085 // -0.84299375f +
4086 // (1.5327582f +
4087 // (-1.0688956f +
4088 // (0.49102474f +
4089 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4090 //
4091 // error 0.0000037995730, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004092 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004093 getF32Constant(DAG, 0x3c5d51ce));
Owen Anderson825b72b2009-08-11 20:47:22 +00004094 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004095 getF32Constant(DAG, 0x3e00685a));
Owen Anderson825b72b2009-08-11 20:47:22 +00004096 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4097 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004098 getF32Constant(DAG, 0x3efb6798));
Owen Anderson825b72b2009-08-11 20:47:22 +00004099 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4100 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004101 getF32Constant(DAG, 0x3f88d192));
Owen Anderson825b72b2009-08-11 20:47:22 +00004102 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4103 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004104 getF32Constant(DAG, 0x3fc4316c));
Owen Anderson825b72b2009-08-11 20:47:22 +00004105 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00004106 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4107 getF32Constant(DAG, 0x3f57ce70));
Bill Wendling3eb59402008-09-09 00:28:24 +00004108 }
Craig Topperdf0ea8d2012-11-16 19:08:44 +00004109
4110 result = DAG.getNode(ISD::FADD, dl,
4111 MVT::f32, LogOfExponent, Log10ofMantissa);
Dale Johannesen852680a2008-09-05 21:27:19 +00004112 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00004113 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004114 result = DAG.getNode(ISD::FLOG10, dl,
Gabor Greif0635f352010-06-25 09:38:13 +00004115 getValue(I.getArgOperand(0)).getValueType(),
4116 getValue(I.getArgOperand(0)));
Dale Johannesen852680a2008-09-05 21:27:19 +00004117 }
Bill Wendling3eb59402008-09-09 00:28:24 +00004118
Dale Johannesen59e577f2008-09-05 18:38:42 +00004119 setValue(&I, result);
4120}
4121
Bill Wendlinge10c8142008-09-09 22:39:21 +00004122/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
4123/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00004124void
Dan Gohman46510a72010-04-15 01:51:59 +00004125SelectionDAGBuilder::visitExp2(const CallInst &I) {
Dale Johannesen601d3c02008-09-05 01:48:15 +00004126 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00004127 DebugLoc dl = getCurDebugLoc();
Bill Wendlinge10c8142008-09-09 22:39:21 +00004128
Gabor Greif0635f352010-06-25 09:38:13 +00004129 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00004130 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Gabor Greif0635f352010-06-25 09:38:13 +00004131 SDValue Op = getValue(I.getArgOperand(0));
Bill Wendlinge10c8142008-09-09 22:39:21 +00004132
Owen Anderson825b72b2009-08-11 20:47:22 +00004133 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
Bill Wendlinge10c8142008-09-09 22:39:21 +00004134
4135 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00004136 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4137 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
Bill Wendlinge10c8142008-09-09 22:39:21 +00004138
4139 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00004140 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00004141 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlinge10c8142008-09-09 22:39:21 +00004142
4143 if (LimitFloatPrecision <= 6) {
4144 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004145 //
Bill Wendlinge10c8142008-09-09 22:39:21 +00004146 // TwoToFractionalPartOfX =
4147 // 0.997535578f +
4148 // (0.735607626f + 0.252464424f * x) * x;
4149 //
4150 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004151 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004152 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00004153 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004154 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00004155 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4156 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004157 getF32Constant(DAG, 0x3f7f5e7e));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004158 SDValue t6 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t5);
Bill Wendlinge10c8142008-09-09 22:39:21 +00004159 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00004160 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00004161
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004162 result = DAG.getNode(ISD::BITCAST, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004163 MVT::f32, TwoToFractionalPartOfX);
Craig Topper08ac4692012-11-16 20:01:39 +00004164 } else if (LimitFloatPrecision <= 12) {
Bill Wendlinge10c8142008-09-09 22:39:21 +00004165 // For floating-point precision of 12:
4166 //
4167 // TwoToFractionalPartOfX =
4168 // 0.999892986f +
4169 // (0.696457318f +
4170 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4171 //
4172 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004173 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004174 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00004175 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004176 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00004177 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4178 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004179 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00004180 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4181 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004182 getF32Constant(DAG, 0x3f7ff8fd));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004183 SDValue t8 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t7);
Bill Wendlinge10c8142008-09-09 22:39:21 +00004184 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00004185 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00004186
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004187 result = DAG.getNode(ISD::BITCAST, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004188 MVT::f32, TwoToFractionalPartOfX);
Craig Topper08ac4692012-11-16 20:01:39 +00004189 } else { // LimitFloatPrecision <= 18
Bill Wendlinge10c8142008-09-09 22:39:21 +00004190 // For floating-point precision of 18:
4191 //
4192 // TwoToFractionalPartOfX =
4193 // 0.999999982f +
4194 // (0.693148872f +
4195 // (0.240227044f +
4196 // (0.554906021e-1f +
4197 // (0.961591928e-2f +
4198 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4199 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004200 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004201 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00004202 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004203 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00004204 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4205 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004206 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00004207 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4208 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004209 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00004210 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4211 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004212 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00004213 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4214 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004215 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00004216 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4217 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004218 getF32Constant(DAG, 0x3f800000));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004219 SDValue t14 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t13);
Bill Wendlinge10c8142008-09-09 22:39:21 +00004220 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00004221 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00004222
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004223 result = DAG.getNode(ISD::BITCAST, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004224 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00004225 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00004226 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00004227 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004228 result = DAG.getNode(ISD::FEXP2, dl,
Gabor Greif0635f352010-06-25 09:38:13 +00004229 getValue(I.getArgOperand(0)).getValueType(),
4230 getValue(I.getArgOperand(0)));
Dale Johannesen601d3c02008-09-05 01:48:15 +00004231 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00004232
Dale Johannesen601d3c02008-09-05 01:48:15 +00004233 setValue(&I, result);
4234}
4235
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004236/// visitPow - Lower a pow intrinsic. Handles the special sequences for
4237/// limited-precision mode with x == 10.0f.
4238void
Dan Gohman46510a72010-04-15 01:51:59 +00004239SelectionDAGBuilder::visitPow(const CallInst &I) {
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004240 SDValue result;
Gabor Greif0635f352010-06-25 09:38:13 +00004241 const Value *Val = I.getArgOperand(0);
Dale Johannesen66978ee2009-01-31 02:22:37 +00004242 DebugLoc dl = getCurDebugLoc();
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004243 bool IsExp10 = false;
4244
Owen Anderson825b72b2009-08-11 20:47:22 +00004245 if (getValue(Val).getValueType() == MVT::f32 &&
Gabor Greif0635f352010-06-25 09:38:13 +00004246 getValue(I.getArgOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004247 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
4248 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
4249 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
4250 APFloat Ten(10.0f);
4251 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
4252 }
4253 }
4254 }
4255
4256 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Gabor Greif0635f352010-06-25 09:38:13 +00004257 SDValue Op = getValue(I.getArgOperand(1));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004258
4259 // Put the exponent in the right bit position for later addition to the
4260 // final result:
4261 //
4262 // #define LOG2OF10 3.3219281f
4263 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
Owen Anderson825b72b2009-08-11 20:47:22 +00004264 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004265 getF32Constant(DAG, 0x40549a78));
Owen Anderson825b72b2009-08-11 20:47:22 +00004266 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004267
4268 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00004269 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4270 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004271
4272 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00004273 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00004274 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004275
4276 if (LimitFloatPrecision <= 6) {
4277 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004278 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004279 // twoToFractionalPartOfX =
4280 // 0.997535578f +
4281 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004282 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004283 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004284 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004285 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00004286 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004287 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00004288 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4289 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004290 getF32Constant(DAG, 0x3f7f5e7e));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004291 SDValue t6 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t5);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004292 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00004293 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004294
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004295 result = DAG.getNode(ISD::BITCAST, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004296 MVT::f32, TwoToFractionalPartOfX);
Craig Topper08ac4692012-11-16 20:01:39 +00004297 } else if (LimitFloatPrecision <= 12) {
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004298 // For floating-point precision of 12:
4299 //
4300 // TwoToFractionalPartOfX =
4301 // 0.999892986f +
4302 // (0.696457318f +
4303 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4304 //
4305 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004306 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004307 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00004308 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004309 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00004310 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4311 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004312 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00004313 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4314 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004315 getF32Constant(DAG, 0x3f7ff8fd));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004316 SDValue t8 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t7);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004317 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00004318 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004319
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004320 result = DAG.getNode(ISD::BITCAST, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004321 MVT::f32, TwoToFractionalPartOfX);
Craig Topper08ac4692012-11-16 20:01:39 +00004322 } else { // LimitFloatPrecision <= 18
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004323 // For floating-point precision of 18:
4324 //
4325 // TwoToFractionalPartOfX =
4326 // 0.999999982f +
4327 // (0.693148872f +
4328 // (0.240227044f +
4329 // (0.554906021e-1f +
4330 // (0.961591928e-2f +
4331 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4332 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004333 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004334 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00004335 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004336 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00004337 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4338 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004339 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00004340 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4341 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004342 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00004343 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4344 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004345 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00004346 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4347 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004348 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00004349 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4350 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004351 getF32Constant(DAG, 0x3f800000));
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004352 SDValue t14 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t13);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004353 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00004354 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004355
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004356 result = DAG.getNode(ISD::BITCAST, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00004357 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004358 }
4359 } else {
4360 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004361 result = DAG.getNode(ISD::FPOW, dl,
Gabor Greif0635f352010-06-25 09:38:13 +00004362 getValue(I.getArgOperand(0)).getValueType(),
4363 getValue(I.getArgOperand(0)),
4364 getValue(I.getArgOperand(1)));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004365 }
4366
4367 setValue(&I, result);
4368}
4369
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004370
4371/// ExpandPowI - Expand a llvm.powi intrinsic.
4372static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS,
4373 SelectionDAG &DAG) {
4374 // If RHS is a constant, we can expand this out to a multiplication tree,
4375 // otherwise we end up lowering to a call to __powidf2 (for example). When
4376 // optimizing for size, we only want to do this if the expansion would produce
4377 // a small number of multiplies, otherwise we do the full expansion.
4378 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4379 // Get the exponent as a positive value.
4380 unsigned Val = RHSC->getSExtValue();
4381 if ((int)Val < 0) Val = -Val;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004382
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004383 // powi(x, 0) -> 1.0
4384 if (Val == 0)
4385 return DAG.getConstantFP(1.0, LHS.getValueType());
4386
Dan Gohmanae541aa2010-04-15 04:33:49 +00004387 const Function *F = DAG.getMachineFunction().getFunction();
Bill Wendling67658342012-10-09 07:45:08 +00004388 if (!F->getFnAttributes().hasAttribute(Attributes::OptimizeForSize) ||
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004389 // If optimizing for size, don't insert too many multiplies. This
4390 // inserts up to 5 multiplies.
4391 CountPopulation_32(Val)+Log2_32(Val) < 7) {
4392 // We use the simple binary decomposition method to generate the multiply
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004393 // sequence. There are more optimal ways to do this (for example,
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004394 // powi(x,15) generates one more multiply than it should), but this has
4395 // the benefit of being both really simple and much better than a libcall.
4396 SDValue Res; // Logically starts equal to 1.0
4397 SDValue CurSquare = LHS;
4398 while (Val) {
Mikhail Glushenkovbfdfea82010-01-01 04:41:36 +00004399 if (Val & 1) {
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004400 if (Res.getNode())
4401 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4402 else
4403 Res = CurSquare; // 1.0*CurSquare.
Mikhail Glushenkovbfdfea82010-01-01 04:41:36 +00004404 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004405
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004406 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4407 CurSquare, CurSquare);
4408 Val >>= 1;
4409 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004410
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004411 // If the original was negative, invert the result, producing 1/(x*x*x).
4412 if (RHSC->getSExtValue() < 0)
4413 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4414 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
4415 return Res;
4416 }
4417 }
4418
4419 // Otherwise, expand to a libcall.
4420 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4421}
4422
Devang Patel227dfdb2011-05-16 21:24:05 +00004423// getTruncatedArgReg - Find underlying register used for an truncated
4424// argument.
4425static unsigned getTruncatedArgReg(const SDValue &N) {
4426 if (N.getOpcode() != ISD::TRUNCATE)
4427 return 0;
4428
4429 const SDValue &Ext = N.getOperand(0);
4430 if (Ext.getOpcode() == ISD::AssertZext || Ext.getOpcode() == ISD::AssertSext){
4431 const SDValue &CFR = Ext.getOperand(0);
4432 if (CFR.getOpcode() == ISD::CopyFromReg)
4433 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
Craig Topper7eb46d82012-04-11 04:55:51 +00004434 if (CFR.getOpcode() == ISD::TRUNCATE)
4435 return getTruncatedArgReg(CFR);
Devang Patel227dfdb2011-05-16 21:24:05 +00004436 }
4437 return 0;
4438}
4439
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004440/// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4441/// argument, create the corresponding DBG_VALUE machine instruction for it now.
4442/// At the end of instruction selection, they will be inserted to the entry BB.
Evan Cheng9e8a2b92010-04-29 01:40:30 +00004443bool
Devang Patel78a06e52010-08-25 20:39:26 +00004444SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable,
Michael J. Spencere70c5262010-10-16 08:25:21 +00004445 int64_t Offset,
Dan Gohman5d11ea32010-05-01 00:33:16 +00004446 const SDValue &N) {
Devang Patel0b48ead2010-08-31 22:22:42 +00004447 const Argument *Arg = dyn_cast<Argument>(V);
4448 if (!Arg)
Evan Cheng9e8a2b92010-04-29 01:40:30 +00004449 return false;
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004450
Devang Patel719f6a92010-04-29 20:40:36 +00004451 MachineFunction &MF = DAG.getMachineFunction();
Devang Patela90b3052010-11-02 17:01:30 +00004452 const TargetInstrInfo *TII = DAG.getTarget().getInstrInfo();
4453 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4454
Devang Patela83ce982010-04-29 18:50:36 +00004455 // Ignore inlined function arguments here.
4456 DIVariable DV(Variable);
Devang Patel719f6a92010-04-29 20:40:36 +00004457 if (DV.isInlinedFnArgument(MF.getFunction()))
Devang Patela83ce982010-04-29 18:50:36 +00004458 return false;
4459
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004460 unsigned Reg = 0;
Devang Patel9aee3352011-09-08 22:59:09 +00004461 // Some arguments' frame index is recorded during argument lowering.
4462 Offset = FuncInfo.getArgumentFrameIndex(Arg);
4463 if (Offset)
Craig Topper7eb46d82012-04-11 04:55:51 +00004464 Reg = TRI->getFrameRegister(MF);
Devang Patel0b48ead2010-08-31 22:22:42 +00004465
Devang Patel9aee3352011-09-08 22:59:09 +00004466 if (!Reg && N.getNode()) {
Devang Patel227dfdb2011-05-16 21:24:05 +00004467 if (N.getOpcode() == ISD::CopyFromReg)
4468 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4469 else
4470 Reg = getTruncatedArgReg(N);
4471 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004472 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4473 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4474 if (PR)
4475 Reg = PR;
4476 }
4477 }
4478
Evan Chenga36acad2010-04-29 06:33:38 +00004479 if (!Reg) {
Devang Patela90b3052010-11-02 17:01:30 +00004480 // Check if ValueMap has reg number.
Evan Chenga36acad2010-04-29 06:33:38 +00004481 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
Devang Patel8bc9ef72010-11-02 17:19:03 +00004482 if (VMI != FuncInfo.ValueMap.end())
4483 Reg = VMI->second;
Evan Chenga36acad2010-04-29 06:33:38 +00004484 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004485
Devang Patel8bc9ef72010-11-02 17:19:03 +00004486 if (!Reg && N.getNode()) {
Devang Patela90b3052010-11-02 17:01:30 +00004487 // Check if frame index is available.
4488 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004489 if (FrameIndexSDNode *FINode =
Devang Patela90b3052010-11-02 17:01:30 +00004490 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) {
4491 Reg = TRI->getFrameRegister(MF);
4492 Offset = FINode->getIndex();
4493 }
Devang Patel8bc9ef72010-11-02 17:19:03 +00004494 }
4495
4496 if (!Reg)
4497 return false;
Devang Patela90b3052010-11-02 17:01:30 +00004498
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004499 MachineInstrBuilder MIB = BuildMI(MF, getCurDebugLoc(),
4500 TII->get(TargetOpcode::DBG_VALUE))
Evan Chenga36acad2010-04-29 06:33:38 +00004501 .addReg(Reg, RegState::Debug).addImm(Offset).addMetadata(Variable);
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004502 FuncInfo.ArgDbgValues.push_back(&*MIB);
Evan Cheng9e8a2b92010-04-29 01:40:30 +00004503 return true;
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004504}
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004505
Douglas Gregor7d9663c2010-05-11 06:17:44 +00004506// VisualStudio defines setjmp as _setjmp
Michael J. Spencer1f409602010-09-24 19:48:47 +00004507#if defined(_MSC_VER) && defined(setjmp) && \
4508 !defined(setjmp_undefined_for_msvc)
4509# pragma push_macro("setjmp")
4510# undef setjmp
4511# define setjmp_undefined_for_msvc
Douglas Gregor7d9663c2010-05-11 06:17:44 +00004512#endif
4513
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004514/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4515/// we want to emit this as a call to a named external function, return the name
4516/// otherwise lower it and return null.
4517const char *
Dan Gohman46510a72010-04-15 01:51:59 +00004518SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00004519 DebugLoc dl = getCurDebugLoc();
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004520 SDValue Res;
4521
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004522 switch (Intrinsic) {
4523 default:
4524 // By default, turn this into a target intrinsic node.
4525 visitTargetIntrinsic(I, Intrinsic);
4526 return 0;
4527 case Intrinsic::vastart: visitVAStart(I); return 0;
4528 case Intrinsic::vaend: visitVAEnd(I); return 0;
4529 case Intrinsic::vacopy: visitVACopy(I); return 0;
4530 case Intrinsic::returnaddress:
Bill Wendling4533cac2010-01-28 21:51:40 +00004531 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
Gabor Greif0635f352010-06-25 09:38:13 +00004532 getValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004533 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00004534 case Intrinsic::frameaddress:
Bill Wendling4533cac2010-01-28 21:51:40 +00004535 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
Gabor Greif0635f352010-06-25 09:38:13 +00004536 getValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004537 return 0;
4538 case Intrinsic::setjmp:
Bill Wendlingc27facc2012-03-05 19:29:36 +00004539 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004540 case Intrinsic::longjmp:
Bill Wendlingc27facc2012-03-05 19:29:36 +00004541 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
Chris Lattner824b9582008-11-21 16:42:48 +00004542 case Intrinsic::memcpy: {
Mon P Wang20adc9d2010-04-04 03:10:48 +00004543 // Assert for address < 256 since we support only user defined address
4544 // spaces.
Gabor Greif0635f352010-06-25 09:38:13 +00004545 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
Mon P Wang20adc9d2010-04-04 03:10:48 +00004546 < 256 &&
Gabor Greif0635f352010-06-25 09:38:13 +00004547 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
Mon P Wang20adc9d2010-04-04 03:10:48 +00004548 < 256 &&
4549 "Unknown address space");
Gabor Greif0635f352010-06-25 09:38:13 +00004550 SDValue Op1 = getValue(I.getArgOperand(0));
4551 SDValue Op2 = getValue(I.getArgOperand(1));
4552 SDValue Op3 = getValue(I.getArgOperand(2));
4553 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4554 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
Mon P Wang20adc9d2010-04-04 03:10:48 +00004555 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol, false,
Chris Lattnere72f2022010-09-21 05:40:29 +00004556 MachinePointerInfo(I.getArgOperand(0)),
4557 MachinePointerInfo(I.getArgOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004558 return 0;
4559 }
Chris Lattner824b9582008-11-21 16:42:48 +00004560 case Intrinsic::memset: {
Mon P Wang20adc9d2010-04-04 03:10:48 +00004561 // Assert for address < 256 since we support only user defined address
4562 // spaces.
Gabor Greif0635f352010-06-25 09:38:13 +00004563 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
Mon P Wang20adc9d2010-04-04 03:10:48 +00004564 < 256 &&
4565 "Unknown address space");
Gabor Greif0635f352010-06-25 09:38:13 +00004566 SDValue Op1 = getValue(I.getArgOperand(0));
4567 SDValue Op2 = getValue(I.getArgOperand(1));
4568 SDValue Op3 = getValue(I.getArgOperand(2));
4569 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4570 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
Mon P Wang20adc9d2010-04-04 03:10:48 +00004571 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
Chris Lattnere72f2022010-09-21 05:40:29 +00004572 MachinePointerInfo(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004573 return 0;
4574 }
Chris Lattner824b9582008-11-21 16:42:48 +00004575 case Intrinsic::memmove: {
Mon P Wang20adc9d2010-04-04 03:10:48 +00004576 // Assert for address < 256 since we support only user defined address
4577 // spaces.
Gabor Greif0635f352010-06-25 09:38:13 +00004578 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
Mon P Wang20adc9d2010-04-04 03:10:48 +00004579 < 256 &&
Gabor Greif0635f352010-06-25 09:38:13 +00004580 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
Mon P Wang20adc9d2010-04-04 03:10:48 +00004581 < 256 &&
4582 "Unknown address space");
Gabor Greif0635f352010-06-25 09:38:13 +00004583 SDValue Op1 = getValue(I.getArgOperand(0));
4584 SDValue Op2 = getValue(I.getArgOperand(1));
4585 SDValue Op3 = getValue(I.getArgOperand(2));
4586 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4587 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
Mon P Wang20adc9d2010-04-04 03:10:48 +00004588 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
Chris Lattnere72f2022010-09-21 05:40:29 +00004589 MachinePointerInfo(I.getArgOperand(0)),
4590 MachinePointerInfo(I.getArgOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004591 return 0;
4592 }
Bill Wendling92c1e122009-02-13 02:16:35 +00004593 case Intrinsic::dbg_declare: {
Dan Gohman46510a72010-04-15 01:51:59 +00004594 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Devang Patelac1ceb32009-10-09 22:42:28 +00004595 MDNode *Variable = DI.getVariable();
Dan Gohman46510a72010-04-15 01:51:59 +00004596 const Value *Address = DI.getAddress();
Eric Christopher8f2a88d2012-03-15 21:33:41 +00004597 if (!Address || !DIVariable(Variable).Verify()) {
4598 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Dale Johannesen8ac38f22010-02-08 21:53:27 +00004599 return 0;
Eric Christopher8f2a88d2012-03-15 21:33:41 +00004600 }
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004601
4602 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
4603 // but do not always have a corresponding SDNode built. The SDNodeOrder
4604 // absolute, but not relative, values are different depending on whether
4605 // debug info exists.
4606 ++SDNodeOrder;
Devang Patel3f74a112010-09-02 21:29:42 +00004607
4608 // Check if address has undef value.
4609 if (isa<UndefValue>(Address) ||
4610 (Address->use_empty() && !isa<Argument>(Address))) {
Eric Christopher24413672012-02-23 03:39:39 +00004611 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Devang Patel3f74a112010-09-02 21:29:42 +00004612 return 0;
4613 }
4614
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004615 SDValue &N = NodeMap[Address];
Devang Patel0b48ead2010-08-31 22:22:42 +00004616 if (!N.getNode() && isa<Argument>(Address))
4617 // Check unused arguments map.
4618 N = UnusedArgNodeMap[Address];
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004619 SDDbgValue *SDV;
4620 if (N.getNode()) {
Devang Patel8e741ed2010-09-02 21:02:27 +00004621 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4622 Address = BCI->getOperand(0);
Eric Christopher178606d2012-02-24 01:59:08 +00004623 // Parameters are handled specially.
4624 bool isParameter =
4625 (DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable ||
4626 isa<Argument>(Address));
4627
Devang Patel8e741ed2010-09-02 21:02:27 +00004628 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4629
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004630 if (isParameter && !AI) {
4631 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4632 if (FINode)
4633 // Byval parameter. We have a frame index at this point.
4634 SDV = DAG.getDbgValue(Variable, FINode->getIndex(),
4635 0, dl, SDNodeOrder);
Devang Patelafeaae72010-12-06 22:39:26 +00004636 else {
Devang Patel227dfdb2011-05-16 21:24:05 +00004637 // Address is an argument, so try to emit its dbg value using
4638 // virtual register info from the FuncInfo.ValueMap.
4639 EmitFuncArgumentDbgValue(Address, Variable, 0, N);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004640 return 0;
Devang Patelafeaae72010-12-06 22:39:26 +00004641 }
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004642 } else if (AI)
4643 SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(),
4644 0, dl, SDNodeOrder);
Devang Patelafeaae72010-12-06 22:39:26 +00004645 else {
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004646 // Can't do anything with other non-AI cases yet.
Eric Christopher24413672012-02-23 03:39:39 +00004647 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Eric Christopher178606d2012-02-24 01:59:08 +00004648 DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
4649 DEBUG(Address->dump());
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004650 return 0;
Devang Patelafeaae72010-12-06 22:39:26 +00004651 }
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004652 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4653 } else {
Gabor Greiffb4032f2010-10-01 10:32:19 +00004654 // If Address is an argument then try to emit its dbg value using
Michael J. Spencere70c5262010-10-16 08:25:21 +00004655 // virtual register info from the FuncInfo.ValueMap.
Devang Patel6cd467b2010-08-26 22:53:27 +00004656 if (!EmitFuncArgumentDbgValue(Address, Variable, 0, N)) {
Devang Patel1397fdc2010-09-15 14:48:53 +00004657 // If variable is pinned by a alloca in dominating bb then
4658 // use StaticAllocaMap.
4659 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
Devang Patel27ede1b2010-09-15 18:13:55 +00004660 if (AI->getParent() != DI.getParent()) {
4661 DenseMap<const AllocaInst*, int>::iterator SI =
4662 FuncInfo.StaticAllocaMap.find(AI);
4663 if (SI != FuncInfo.StaticAllocaMap.end()) {
4664 SDV = DAG.getDbgValue(Variable, SI->second,
4665 0, dl, SDNodeOrder);
4666 DAG.AddDbgValue(SDV, 0, false);
4667 return 0;
4668 }
Devang Patel1397fdc2010-09-15 14:48:53 +00004669 }
4670 }
Eric Christopher0822e012012-02-23 03:39:43 +00004671 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Devang Patel6cd467b2010-08-26 22:53:27 +00004672 }
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004673 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004674 return 0;
Bill Wendling92c1e122009-02-13 02:16:35 +00004675 }
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004676 case Intrinsic::dbg_value: {
Dan Gohman46510a72010-04-15 01:51:59 +00004677 const DbgValueInst &DI = cast<DbgValueInst>(I);
Devang Patel02f0dbd2010-05-07 22:04:20 +00004678 if (!DIVariable(DI.getVariable()).Verify())
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004679 return 0;
4680
4681 MDNode *Variable = DI.getVariable();
Devang Patel00190342010-03-15 19:15:44 +00004682 uint64_t Offset = DI.getOffset();
Dan Gohman46510a72010-04-15 01:51:59 +00004683 const Value *V = DI.getValue();
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004684 if (!V)
4685 return 0;
Devang Patel00190342010-03-15 19:15:44 +00004686
4687 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
4688 // but do not always have a corresponding SDNode built. The SDNodeOrder
4689 // absolute, but not relative, values are different depending on whether
4690 // debug info exists.
4691 ++SDNodeOrder;
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004692 SDDbgValue *SDV;
Devang Patel57871242011-08-03 23:13:55 +00004693 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004694 SDV = DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder);
4695 DAG.AddDbgValue(SDV, 0, false);
Devang Patel00190342010-03-15 19:15:44 +00004696 } else {
Dale Johannesenbdc09d92010-07-16 00:02:08 +00004697 // Do not use getValue() in here; we don't want to generate code at
4698 // this point if it hasn't been done yet.
Devang Patel9126c0d2010-06-01 19:59:01 +00004699 SDValue N = NodeMap[V];
4700 if (!N.getNode() && isa<Argument>(V))
4701 // Check unused arguments map.
4702 N = UnusedArgNodeMap[V];
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004703 if (N.getNode()) {
Devang Patel78a06e52010-08-25 20:39:26 +00004704 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, N)) {
Evan Cheng9e8a2b92010-04-29 01:40:30 +00004705 SDV = DAG.getDbgValue(Variable, N.getNode(),
4706 N.getResNo(), Offset, dl, SDNodeOrder);
4707 DAG.AddDbgValue(SDV, N.getNode(), false);
4708 }
Devang Patela778f5c2011-02-18 22:43:42 +00004709 } else if (!V->use_empty() ) {
Dale Johannesenbdc09d92010-07-16 00:02:08 +00004710 // Do not call getValue(V) yet, as we don't want to generate code.
4711 // Remember it for later.
4712 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4713 DanglingDebugInfoMap[V] = DDI;
Devang Patel0991dfb2010-08-27 22:25:51 +00004714 } else {
Devang Patel00190342010-03-15 19:15:44 +00004715 // We may expand this to cover more cases. One case where we have no
Devang Patelafeaae72010-12-06 22:39:26 +00004716 // data available is an unreferenced parameter.
Eric Christopher0822e012012-02-23 03:39:43 +00004717 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004718 }
Devang Patel00190342010-03-15 19:15:44 +00004719 }
4720
4721 // Build a debug info table entry.
Dan Gohman46510a72010-04-15 01:51:59 +00004722 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004723 V = BCI->getOperand(0);
Dan Gohman46510a72010-04-15 01:51:59 +00004724 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004725 // Don't handle byval struct arguments or VLAs, for example.
Eric Christopher7e1e18f2012-03-26 06:10:32 +00004726 if (!AI) {
Eric Christopher9fc5c832012-03-28 07:34:36 +00004727 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
4728 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004729 return 0;
Eric Christopher7e1e18f2012-03-26 06:10:32 +00004730 }
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004731 DenseMap<const AllocaInst*, int>::iterator SI =
4732 FuncInfo.StaticAllocaMap.find(AI);
4733 if (SI == FuncInfo.StaticAllocaMap.end())
4734 return 0; // VLAs.
4735 int FI = SI->second;
Michael J. Spencere70c5262010-10-16 08:25:21 +00004736
Chris Lattner512063d2010-04-05 06:19:28 +00004737 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4738 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
4739 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004740 return 0;
4741 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004742
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00004743 case Intrinsic::eh_typeid_for: {
Chris Lattner512063d2010-04-05 06:19:28 +00004744 // Find the type id for the given typeinfo.
Gabor Greif0635f352010-06-25 09:38:13 +00004745 GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0));
Chris Lattner512063d2010-04-05 06:19:28 +00004746 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4747 Res = DAG.getConstant(TypeID, MVT::i32);
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004748 setValue(&I, Res);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004749 return 0;
4750 }
4751
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004752 case Intrinsic::eh_return_i32:
4753 case Intrinsic::eh_return_i64:
Chris Lattner512063d2010-04-05 06:19:28 +00004754 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
4755 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
4756 MVT::Other,
4757 getControlRoot(),
Gabor Greif0635f352010-06-25 09:38:13 +00004758 getValue(I.getArgOperand(0)),
4759 getValue(I.getArgOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004760 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004761 case Intrinsic::eh_unwind_init:
Chris Lattner512063d2010-04-05 06:19:28 +00004762 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004763 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004764 case Intrinsic::eh_dwarf_cfa: {
Gabor Greif0635f352010-06-25 09:38:13 +00004765 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), dl,
Duncan Sands3a66a682009-10-13 21:04:12 +00004766 TLI.getPointerTy());
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004767 SDValue Offset = DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004768 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004769 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004770 TLI.getPointerTy()),
4771 CfaArg);
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004772 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004773 TLI.getPointerTy(),
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004774 DAG.getConstant(0, TLI.getPointerTy()));
Bill Wendling4533cac2010-01-28 21:51:40 +00004775 setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
4776 FA, Offset));
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004777 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004778 }
Jim Grosbachca752c92010-01-28 01:45:32 +00004779 case Intrinsic::eh_sjlj_callsite: {
Chris Lattner512063d2010-04-05 06:19:28 +00004780 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Gabor Greif0635f352010-06-25 09:38:13 +00004781 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
Jim Grosbachca752c92010-01-28 01:45:32 +00004782 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
Chris Lattner512063d2010-04-05 06:19:28 +00004783 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
Jim Grosbachca752c92010-01-28 01:45:32 +00004784
Chris Lattner512063d2010-04-05 06:19:28 +00004785 MMI.setCurrentCallSite(CI->getZExtValue());
Jim Grosbachca752c92010-01-28 01:45:32 +00004786 return 0;
4787 }
Bill Wendling6ef94172011-09-28 03:36:43 +00004788 case Intrinsic::eh_sjlj_functioncontext: {
4789 // Get and store the index of the function context.
4790 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
Bill Wendlingadbf7b22011-09-28 03:52:41 +00004791 AllocaInst *FnCtx =
4792 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
Bill Wendling6ef94172011-09-28 03:36:43 +00004793 int FI = FuncInfo.StaticAllocaMap[FnCtx];
4794 MFI->setFunctionContextIndex(FI);
4795 return 0;
4796 }
Jim Grosbach23ff7cf2010-05-26 20:22:18 +00004797 case Intrinsic::eh_sjlj_setjmp: {
Bill Wendlingce370cf2011-10-07 21:25:38 +00004798 SDValue Ops[2];
4799 Ops[0] = getRoot();
4800 Ops[1] = getValue(I.getArgOperand(0));
4801 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, dl,
4802 DAG.getVTList(MVT::i32, MVT::Other),
4803 Ops, 2);
4804 setValue(&I, Op.getValue(0));
4805 DAG.setRoot(Op.getValue(1));
Jim Grosbach23ff7cf2010-05-26 20:22:18 +00004806 return 0;
4807 }
Jim Grosbach5eb19512010-05-22 01:06:18 +00004808 case Intrinsic::eh_sjlj_longjmp: {
Jim Grosbach23ff7cf2010-05-26 20:22:18 +00004809 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, dl, MVT::Other,
Jim Grosbache4ad3872010-10-19 23:27:08 +00004810 getRoot(), getValue(I.getArgOperand(0))));
4811 return 0;
4812 }
Jim Grosbachca752c92010-01-28 01:45:32 +00004813
Dale Johannesen0488fb62010-09-30 23:57:10 +00004814 case Intrinsic::x86_mmx_pslli_w:
4815 case Intrinsic::x86_mmx_pslli_d:
4816 case Intrinsic::x86_mmx_pslli_q:
4817 case Intrinsic::x86_mmx_psrli_w:
4818 case Intrinsic::x86_mmx_psrli_d:
4819 case Intrinsic::x86_mmx_psrli_q:
4820 case Intrinsic::x86_mmx_psrai_w:
4821 case Intrinsic::x86_mmx_psrai_d: {
4822 SDValue ShAmt = getValue(I.getArgOperand(1));
4823 if (isa<ConstantSDNode>(ShAmt)) {
4824 visitTargetIntrinsic(I, Intrinsic);
4825 return 0;
4826 }
4827 unsigned NewIntrinsic = 0;
4828 EVT ShAmtVT = MVT::v2i32;
4829 switch (Intrinsic) {
4830 case Intrinsic::x86_mmx_pslli_w:
4831 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
4832 break;
4833 case Intrinsic::x86_mmx_pslli_d:
4834 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
4835 break;
4836 case Intrinsic::x86_mmx_pslli_q:
4837 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
4838 break;
4839 case Intrinsic::x86_mmx_psrli_w:
4840 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
4841 break;
4842 case Intrinsic::x86_mmx_psrli_d:
4843 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
4844 break;
4845 case Intrinsic::x86_mmx_psrli_q:
4846 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
4847 break;
4848 case Intrinsic::x86_mmx_psrai_w:
4849 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
4850 break;
4851 case Intrinsic::x86_mmx_psrai_d:
4852 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
4853 break;
4854 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4855 }
4856
4857 // The vector shift intrinsics with scalars uses 32b shift amounts but
4858 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
4859 // to be zero.
4860 // We must do this early because v2i32 is not a legal type.
4861 DebugLoc dl = getCurDebugLoc();
4862 SDValue ShOps[2];
4863 ShOps[0] = ShAmt;
4864 ShOps[1] = DAG.getConstant(0, MVT::i32);
4865 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
4866 EVT DestVT = TLI.getValueType(I.getType());
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004867 ShAmt = DAG.getNode(ISD::BITCAST, dl, DestVT, ShAmt);
Dale Johannesen0488fb62010-09-30 23:57:10 +00004868 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
4869 DAG.getConstant(NewIntrinsic, MVT::i32),
4870 getValue(I.getArgOperand(0)), ShAmt);
4871 setValue(&I, Res);
4872 return 0;
4873 }
Pete Cooperd18134f2012-02-24 03:51:49 +00004874 case Intrinsic::x86_avx_vinsertf128_pd_256:
4875 case Intrinsic::x86_avx_vinsertf128_ps_256:
Craig Topperb45c9692012-04-07 22:32:29 +00004876 case Intrinsic::x86_avx_vinsertf128_si_256:
4877 case Intrinsic::x86_avx2_vinserti128: {
Pete Cooperd18134f2012-02-24 03:51:49 +00004878 DebugLoc dl = getCurDebugLoc();
4879 EVT DestVT = TLI.getValueType(I.getType());
4880 EVT ElVT = TLI.getValueType(I.getArgOperand(1)->getType());
4881 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(2))->getZExtValue() & 1) *
4882 ElVT.getVectorNumElements();
4883 Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, DestVT,
4884 getValue(I.getArgOperand(0)),
4885 getValue(I.getArgOperand(1)),
Craig Topperf6dc7922012-09-05 05:48:09 +00004886 DAG.getIntPtrConstant(Idx));
4887 setValue(&I, Res);
4888 return 0;
4889 }
4890 case Intrinsic::x86_avx_vextractf128_pd_256:
4891 case Intrinsic::x86_avx_vextractf128_ps_256:
4892 case Intrinsic::x86_avx_vextractf128_si_256:
4893 case Intrinsic::x86_avx2_vextracti128: {
4894 DebugLoc dl = getCurDebugLoc();
4895 EVT DestVT = TLI.getValueType(I.getType());
4896 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(1))->getZExtValue() & 1) *
4897 DestVT.getVectorNumElements();
4898 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT,
4899 getValue(I.getArgOperand(0)),
4900 DAG.getIntPtrConstant(Idx));
Pete Cooperd18134f2012-02-24 03:51:49 +00004901 setValue(&I, Res);
4902 return 0;
4903 }
Mon P Wang77cdf302008-11-10 20:54:11 +00004904 case Intrinsic::convertff:
4905 case Intrinsic::convertfsi:
4906 case Intrinsic::convertfui:
4907 case Intrinsic::convertsif:
4908 case Intrinsic::convertuif:
4909 case Intrinsic::convertss:
4910 case Intrinsic::convertsu:
4911 case Intrinsic::convertus:
4912 case Intrinsic::convertuu: {
4913 ISD::CvtCode Code = ISD::CVT_INVALID;
4914 switch (Intrinsic) {
Craig Topperc42e6402012-04-11 04:34:11 +00004915 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
Mon P Wang77cdf302008-11-10 20:54:11 +00004916 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4917 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4918 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4919 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4920 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4921 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4922 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4923 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4924 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4925 }
Owen Andersone50ed302009-08-10 22:56:29 +00004926 EVT DestVT = TLI.getValueType(I.getType());
Gabor Greif0635f352010-06-25 09:38:13 +00004927 const Value *Op1 = I.getArgOperand(0);
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004928 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
4929 DAG.getValueType(DestVT),
4930 DAG.getValueType(getValue(Op1).getValueType()),
Gabor Greif0635f352010-06-25 09:38:13 +00004931 getValue(I.getArgOperand(1)),
4932 getValue(I.getArgOperand(2)),
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004933 Code);
4934 setValue(&I, Res);
Mon P Wang77cdf302008-11-10 20:54:11 +00004935 return 0;
4936 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004937 case Intrinsic::powi:
Gabor Greif0635f352010-06-25 09:38:13 +00004938 setValue(&I, ExpandPowI(dl, getValue(I.getArgOperand(0)),
4939 getValue(I.getArgOperand(1)), DAG));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004940 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004941 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004942 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004943 return 0;
4944 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004945 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004946 return 0;
4947 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004948 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004949 return 0;
4950 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004951 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004952 return 0;
4953 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00004954 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004955 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004956 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004957 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004958 return 0;
Craig Topper9bd4dd72012-11-16 07:48:23 +00004959 case Intrinsic::sqrt:
Peter Collingbourneb34d3aa2012-05-28 21:48:37 +00004960 case Intrinsic::fabs:
Craig Topper9bd4dd72012-11-16 07:48:23 +00004961 case Intrinsic::sin:
4962 case Intrinsic::cos:
Dan Gohman27db99f2012-07-26 17:43:27 +00004963 case Intrinsic::floor:
Craig Topper49010472012-11-15 06:51:10 +00004964 case Intrinsic::ceil:
Craig Topper49010472012-11-15 06:51:10 +00004965 case Intrinsic::trunc:
Craig Topper49010472012-11-15 06:51:10 +00004966 case Intrinsic::rint:
Craig Topper9bd4dd72012-11-16 07:48:23 +00004967 case Intrinsic::nearbyint: {
4968 unsigned Opcode;
4969 switch (Intrinsic) {
4970 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4971 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
4972 case Intrinsic::fabs: Opcode = ISD::FABS; break;
4973 case Intrinsic::sin: Opcode = ISD::FSIN; break;
4974 case Intrinsic::cos: Opcode = ISD::FCOS; break;
4975 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
4976 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
4977 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
4978 case Intrinsic::rint: Opcode = ISD::FRINT; break;
4979 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
4980 }
4981
4982 setValue(&I, DAG.getNode(Opcode, dl,
Craig Topper49010472012-11-15 06:51:10 +00004983 getValue(I.getArgOperand(0)).getValueType(),
4984 getValue(I.getArgOperand(0))));
4985 return 0;
Craig Topper9bd4dd72012-11-16 07:48:23 +00004986 }
Cameron Zwarich33390842011-07-08 21:39:21 +00004987 case Intrinsic::fma:
4988 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 return 0;
Lang Hames5afba6f2012-06-05 19:07:46 +00004994 case Intrinsic::fmuladd: {
4995 EVT VT = TLI.getValueType(I.getType());
Lang Hamese0231412012-06-22 01:09:09 +00004996 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
Lang Hamesb47ec402012-11-22 03:31:45 +00004997 TLI.isOperationLegalOrCustom(ISD::FMA, VT) &&
Lang Hamese0231412012-06-22 01:09:09 +00004998 TLI.isFMAFasterThanMulAndAdd(VT)){
Lang Hames5afba6f2012-06-05 19:07:46 +00004999 setValue(&I, DAG.getNode(ISD::FMA, dl,
5000 getValue(I.getArgOperand(0)).getValueType(),
5001 getValue(I.getArgOperand(0)),
5002 getValue(I.getArgOperand(1)),
5003 getValue(I.getArgOperand(2))));
5004 } else {
5005 SDValue Mul = DAG.getNode(ISD::FMUL, dl,
5006 getValue(I.getArgOperand(0)).getValueType(),
5007 getValue(I.getArgOperand(0)),
5008 getValue(I.getArgOperand(1)));
5009 SDValue Add = DAG.getNode(ISD::FADD, dl,
5010 getValue(I.getArgOperand(0)).getValueType(),
5011 Mul,
5012 getValue(I.getArgOperand(2)));
5013 setValue(&I, Add);
5014 }
5015 return 0;
5016 }
Anton Korobeynikovbe5b0322010-03-14 18:42:15 +00005017 case Intrinsic::convert_to_fp16:
5018 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, dl,
Gabor Greif0635f352010-06-25 09:38:13 +00005019 MVT::i16, getValue(I.getArgOperand(0))));
Anton Korobeynikovbe5b0322010-03-14 18:42:15 +00005020 return 0;
5021 case Intrinsic::convert_from_fp16:
5022 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, dl,
Gabor Greif0635f352010-06-25 09:38:13 +00005023 MVT::f32, getValue(I.getArgOperand(0))));
Anton Korobeynikovbe5b0322010-03-14 18:42:15 +00005024 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005025 case Intrinsic::pcmarker: {
Gabor Greif0635f352010-06-25 09:38:13 +00005026 SDValue Tmp = getValue(I.getArgOperand(0));
Bill Wendling4533cac2010-01-28 21:51:40 +00005027 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005028 return 0;
5029 }
5030 case Intrinsic::readcyclecounter: {
5031 SDValue Op = getRoot();
Bill Wendlingd0283fa2009-12-22 00:40:51 +00005032 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
5033 DAG.getVTList(MVT::i64, MVT::Other),
5034 &Op, 1);
5035 setValue(&I, Res);
5036 DAG.setRoot(Res.getValue(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005037 return 0;
5038 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005039 case Intrinsic::bswap:
Bill Wendling4533cac2010-01-28 21:51:40 +00005040 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
Gabor Greif0635f352010-06-25 09:38:13 +00005041 getValue(I.getArgOperand(0)).getValueType(),
5042 getValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005043 return 0;
5044 case Intrinsic::cttz: {
Gabor Greif0635f352010-06-25 09:38:13 +00005045 SDValue Arg = getValue(I.getArgOperand(0));
Chandler Carruth63974b22011-12-13 01:56:10 +00005046 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00005047 EVT Ty = Arg.getValueType();
Chandler Carruth63974b22011-12-13 01:56:10 +00005048 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
5049 dl, Ty, Arg));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005050 return 0;
5051 }
5052 case Intrinsic::ctlz: {
Gabor Greif0635f352010-06-25 09:38:13 +00005053 SDValue Arg = getValue(I.getArgOperand(0));
Chandler Carruth63974b22011-12-13 01:56:10 +00005054 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00005055 EVT Ty = Arg.getValueType();
Chandler Carruth63974b22011-12-13 01:56:10 +00005056 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
5057 dl, Ty, Arg));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005058 return 0;
5059 }
5060 case Intrinsic::ctpop: {
Gabor Greif0635f352010-06-25 09:38:13 +00005061 SDValue Arg = getValue(I.getArgOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00005062 EVT Ty = Arg.getValueType();
Bill Wendling4533cac2010-01-28 21:51:40 +00005063 setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005064 return 0;
5065 }
5066 case Intrinsic::stacksave: {
5067 SDValue Op = getRoot();
Bill Wendlingd0283fa2009-12-22 00:40:51 +00005068 Res = DAG.getNode(ISD::STACKSAVE, dl,
5069 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
5070 setValue(&I, Res);
5071 DAG.setRoot(Res.getValue(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005072 return 0;
5073 }
5074 case Intrinsic::stackrestore: {
Gabor Greif0635f352010-06-25 09:38:13 +00005075 Res = getValue(I.getArgOperand(0));
Bill Wendling4533cac2010-01-28 21:51:40 +00005076 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005077 return 0;
5078 }
Bill Wendling57344502008-11-18 11:01:33 +00005079 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00005080 // Emit code into the DAG to store the stack guard onto the stack.
5081 MachineFunction &MF = DAG.getMachineFunction();
5082 MachineFrameInfo *MFI = MF.getFrameInfo();
Owen Andersone50ed302009-08-10 22:56:29 +00005083 EVT PtrTy = TLI.getPointerTy();
Bill Wendlingb2a42982008-11-06 02:29:10 +00005084
Gabor Greif0635f352010-06-25 09:38:13 +00005085 SDValue Src = getValue(I.getArgOperand(0)); // The guard's value.
5086 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
Bill Wendlingb2a42982008-11-06 02:29:10 +00005087
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00005088 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00005089 MFI->setStackProtectorIndex(FI);
5090
5091 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
5092
5093 // Store the stack protector onto the stack.
Bill Wendlingd0283fa2009-12-22 00:40:51 +00005094 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
Chris Lattner84bd98a2010-09-21 18:58:22 +00005095 MachinePointerInfo::getFixedStack(FI),
5096 true, false, 0);
Bill Wendlingd0283fa2009-12-22 00:40:51 +00005097 setValue(&I, Res);
5098 DAG.setRoot(Res);
Bill Wendlingb2a42982008-11-06 02:29:10 +00005099 return 0;
5100 }
Eric Christopher7b5e6172009-10-27 00:52:25 +00005101 case Intrinsic::objectsize: {
5102 // If we don't know by now, we're never going to know.
Gabor Greif0635f352010-06-25 09:38:13 +00005103 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
Eric Christopher7b5e6172009-10-27 00:52:25 +00005104
5105 assert(CI && "Non-constant type in __builtin_object_size?");
5106
Gabor Greif0635f352010-06-25 09:38:13 +00005107 SDValue Arg = getValue(I.getCalledValue());
Eric Christopher7e5d2ff2009-10-28 21:32:16 +00005108 EVT Ty = Arg.getValueType();
5109
Dan Gohmane368b462010-06-18 14:22:04 +00005110 if (CI->isZero())
Bill Wendlingd0283fa2009-12-22 00:40:51 +00005111 Res = DAG.getConstant(-1ULL, Ty);
Eric Christopher7b5e6172009-10-27 00:52:25 +00005112 else
Bill Wendlingd0283fa2009-12-22 00:40:51 +00005113 Res = DAG.getConstant(0, Ty);
5114
5115 setValue(&I, Res);
Eric Christopher7b5e6172009-10-27 00:52:25 +00005116 return 0;
5117 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005118 case Intrinsic::var_annotation:
5119 // Discard annotate attributes
5120 return 0;
5121
5122 case Intrinsic::init_trampoline: {
Gabor Greif0635f352010-06-25 09:38:13 +00005123 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005124
5125 SDValue Ops[6];
5126 Ops[0] = getRoot();
Gabor Greif0635f352010-06-25 09:38:13 +00005127 Ops[1] = getValue(I.getArgOperand(0));
5128 Ops[2] = getValue(I.getArgOperand(1));
5129 Ops[3] = getValue(I.getArgOperand(2));
5130 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005131 Ops[5] = DAG.getSrcValue(F);
5132
Duncan Sands4a544a72011-09-06 13:37:06 +00005133 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, dl, MVT::Other, Ops, 6);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005134
Duncan Sands4a544a72011-09-06 13:37:06 +00005135 DAG.setRoot(Res);
5136 return 0;
5137 }
5138 case Intrinsic::adjust_trampoline: {
5139 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, dl,
5140 TLI.getPointerTy(),
5141 getValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005142 return 0;
5143 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005144 case Intrinsic::gcroot:
5145 if (GFI) {
Bill Wendling95dd4422012-05-01 22:50:45 +00005146 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
Gabor Greif0635f352010-06-25 09:38:13 +00005147 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005148
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005149 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5150 GFI->addStackRoot(FI->getIndex(), TypeMap);
5151 }
5152 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005153 case Intrinsic::gcread:
5154 case Intrinsic::gcwrite:
Torok Edwinc23197a2009-07-14 16:55:14 +00005155 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
Bill Wendlingd0283fa2009-12-22 00:40:51 +00005156 case Intrinsic::flt_rounds:
Bill Wendling4533cac2010-01-28 21:51:40 +00005157 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005158 return 0;
Jakub Staszak9da99342011-07-06 18:22:43 +00005159
5160 case Intrinsic::expect: {
5161 // Just replace __builtin_expect(exp, c) with EXP.
5162 setValue(&I, getValue(I.getArgOperand(0)));
5163 return 0;
5164 }
5165
Shuxin Yang970755e2012-10-19 20:11:16 +00005166 case Intrinsic::debugtrap:
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005167 case Intrinsic::trap: {
Nick Lewycky8a8d4792011-12-02 22:16:29 +00005168 StringRef TrapFuncName = TM.Options.getTrapFunctionName();
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005169 if (TrapFuncName.empty()) {
Shuxin Yang970755e2012-10-19 20:11:16 +00005170 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
5171 ISD::TRAP : ISD::DEBUGTRAP;
5172 DAG.setRoot(DAG.getNode(Op, dl,MVT::Other, getRoot()));
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005173 return 0;
5174 }
5175 TargetLowering::ArgListTy Args;
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00005176 TargetLowering::
5177 CallLoweringInfo CLI(getRoot(), I.getType(),
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005178 false, false, false, false, 0, CallingConv::C,
Evan Cheng4bfcd4a2012-02-28 18:51:51 +00005179 /*isTailCall=*/false,
5180 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005181 DAG.getExternalSymbol(TrapFuncName.data(), TLI.getPointerTy()),
5182 Args, DAG, getCurDebugLoc());
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00005183 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005184 DAG.setRoot(Result.second);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005185 return 0;
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005186 }
Shuxin Yang970755e2012-10-19 20:11:16 +00005187
Bill Wendlingef375462008-11-21 02:38:44 +00005188 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00005189 case Intrinsic::sadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00005190 case Intrinsic::usub_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00005191 case Intrinsic::ssub_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00005192 case Intrinsic::umul_with_overflow:
Craig Topperc42e6402012-04-11 04:34:11 +00005193 case Intrinsic::smul_with_overflow: {
5194 ISD::NodeType Op;
5195 switch (Intrinsic) {
5196 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5197 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5198 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5199 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5200 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5201 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5202 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5203 }
5204 SDValue Op1 = getValue(I.getArgOperand(0));
5205 SDValue Op2 = getValue(I.getArgOperand(1));
Bill Wendling7cdc3c82008-11-21 02:03:52 +00005206
Craig Topperc42e6402012-04-11 04:34:11 +00005207 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
5208 setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2));
5209 return 0;
5210 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005211 case Intrinsic::prefetch: {
Bruno Cardoso Lopes9a767332011-06-14 04:58:37 +00005212 SDValue Ops[5];
Dale Johannesen1de4aa92010-10-26 23:11:10 +00005213 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005214 Ops[0] = getRoot();
Gabor Greif0635f352010-06-25 09:38:13 +00005215 Ops[1] = getValue(I.getArgOperand(0));
5216 Ops[2] = getValue(I.getArgOperand(1));
5217 Ops[3] = getValue(I.getArgOperand(2));
Bruno Cardoso Lopes9a767332011-06-14 04:58:37 +00005218 Ops[4] = getValue(I.getArgOperand(3));
Dale Johannesen1de4aa92010-10-26 23:11:10 +00005219 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, dl,
5220 DAG.getVTList(MVT::Other),
Bruno Cardoso Lopes9a767332011-06-14 04:58:37 +00005221 &Ops[0], 5,
Dale Johannesen1de4aa92010-10-26 23:11:10 +00005222 EVT::getIntegerVT(*Context, 8),
5223 MachinePointerInfo(I.getArgOperand(0)),
5224 0, /* align */
5225 false, /* volatile */
5226 rw==0, /* read */
5227 rw==1)); /* write */
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005228 return 0;
5229 }
Duncan Sandsf07c9492009-11-10 09:08:09 +00005230 case Intrinsic::lifetime_start:
Nadav Rotemc05d3062012-09-06 09:17:37 +00005231 case Intrinsic::lifetime_end: {
Nadav Rotemc05d3062012-09-06 09:17:37 +00005232 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
Nadav Rotem9a2ae002012-09-10 08:43:23 +00005233 // Stack coloring is not enabled in O0, discard region information.
5234 if (TM.getOptLevel() == CodeGenOpt::None)
5235 return 0;
Nadav Rotemc05d3062012-09-06 09:17:37 +00005236
Nadav Rotem9a2ae002012-09-10 08:43:23 +00005237 SmallVector<Value *, 4> Allocas;
5238 GetUnderlyingObjects(I.getArgOperand(1), Allocas, TD);
5239
5240 for (SmallVector<Value*, 4>::iterator Object = Allocas.begin(),
5241 E = Allocas.end(); Object != E; ++Object) {
5242 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5243
5244 // Could not find an Alloca.
5245 if (!LifetimeObject)
5246 continue;
5247
5248 int FI = FuncInfo.StaticAllocaMap[LifetimeObject];
5249
5250 SDValue Ops[2];
5251 Ops[0] = getRoot();
5252 Ops[1] = DAG.getFrameIndex(FI, TLI.getPointerTy(), true);
5253 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5254
5255 Res = DAG.getNode(Opcode, dl, MVT::Other, Ops, 2);
5256 DAG.setRoot(Res);
5257 }
Nadav Rotemc05d3062012-09-06 09:17:37 +00005258 }
5259 case Intrinsic::invariant_start:
Duncan Sandsf07c9492009-11-10 09:08:09 +00005260 // Discard region information.
Bill Wendling4533cac2010-01-28 21:51:40 +00005261 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
Duncan Sandsf07c9492009-11-10 09:08:09 +00005262 return 0;
5263 case Intrinsic::invariant_end:
Duncan Sandsf07c9492009-11-10 09:08:09 +00005264 // Discard region information.
5265 return 0;
Nuno Lopes85b40892012-06-28 22:30:12 +00005266 case Intrinsic::donothing:
5267 // ignore
5268 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005269 }
5270}
5271
Dan Gohman46510a72010-04-15 01:51:59 +00005272void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
Dan Gohman2048b852009-11-23 18:04:58 +00005273 bool isTailCall,
5274 MachineBasicBlock *LandingPad) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005275 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
5276 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
5277 Type *RetTy = FTy->getReturnType();
Chris Lattner512063d2010-04-05 06:19:28 +00005278 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Chris Lattner16112732010-03-14 01:41:15 +00005279 MCSymbol *BeginLabel = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005280
5281 TargetLowering::ArgListTy Args;
5282 TargetLowering::ArgListEntry Entry;
5283 Args.reserve(CS.arg_size());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005284
5285 // Check whether the function can return without sret-demotion.
Dan Gohman84023e02010-07-10 09:00:22 +00005286 SmallVector<ISD::OutputArg, 4> Outs;
Dan Gohman84023e02010-07-10 09:00:22 +00005287 GetReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
Eli Friedman2db0e9e2012-05-25 00:09:29 +00005288 Outs, TLI);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005289
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005290 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
Bill Wendling96cb1122012-07-19 00:04:14 +00005291 DAG.getMachineFunction(),
5292 FTy->isVarArg(), Outs,
5293 FTy->getContext());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005294
5295 SDValue DemoteStackSlot;
Chris Lattnerecf42c42010-09-21 16:36:31 +00005296 int DemoteStackIdx = -100;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005297
5298 if (!CanLowerReturn) {
Micah Villmow3574eca2012-10-08 16:38:25 +00005299 uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005300 FTy->getReturnType());
Micah Villmow3574eca2012-10-08 16:38:25 +00005301 unsigned Align = TLI.getDataLayout()->getPrefTypeAlignment(
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005302 FTy->getReturnType());
5303 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerecf42c42010-09-21 16:36:31 +00005304 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005305 Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005306
Chris Lattnerecf42c42010-09-21 16:36:31 +00005307 DemoteStackSlot = DAG.getFrameIndex(DemoteStackIdx, TLI.getPointerTy());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005308 Entry.Node = DemoteStackSlot;
5309 Entry.Ty = StackSlotPtrType;
5310 Entry.isSExt = false;
5311 Entry.isZExt = false;
5312 Entry.isInReg = false;
5313 Entry.isSRet = true;
5314 Entry.isNest = false;
5315 Entry.isByVal = false;
5316 Entry.Alignment = Align;
5317 Args.push_back(Entry);
5318 RetTy = Type::getVoidTy(FTy->getContext());
5319 }
5320
Dan Gohman46510a72010-04-15 01:51:59 +00005321 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005322 i != e; ++i) {
Rafael Espindola3fa82832011-05-13 15:18:06 +00005323 const Value *V = *i;
5324
5325 // Skip empty types
5326 if (V->getType()->isEmptyTy())
5327 continue;
5328
5329 SDValue ArgNode = getValue(V);
5330 Entry.Node = ArgNode; Entry.Ty = V->getType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005331
5332 unsigned attrInd = i - CS.arg_begin() + 1;
Bill Wendling3e2d76c2012-10-09 21:38:14 +00005333 Entry.isSExt = CS.paramHasAttr(attrInd, Attributes::SExt);
5334 Entry.isZExt = CS.paramHasAttr(attrInd, Attributes::ZExt);
5335 Entry.isInReg = CS.paramHasAttr(attrInd, Attributes::InReg);
5336 Entry.isSRet = CS.paramHasAttr(attrInd, Attributes::StructRet);
5337 Entry.isNest = CS.paramHasAttr(attrInd, Attributes::Nest);
5338 Entry.isByVal = CS.paramHasAttr(attrInd, Attributes::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005339 Entry.Alignment = CS.getParamAlignment(attrInd);
5340 Args.push_back(Entry);
5341 }
5342
Chris Lattner512063d2010-04-05 06:19:28 +00005343 if (LandingPad) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005344 // Insert a label before the invoke call to mark the try range. This can be
5345 // used to detect deletion of the invoke via the MachineModuleInfo.
Chris Lattner512063d2010-04-05 06:19:28 +00005346 BeginLabel = MMI.getContext().CreateTempSymbol();
Jim Grosbach1b747ad2009-08-11 00:09:57 +00005347
Jim Grosbachca752c92010-01-28 01:45:32 +00005348 // For SjLj, keep track of which landing pads go with which invokes
5349 // so as to maintain the ordering of pads in the LSDA.
Chris Lattner512063d2010-04-05 06:19:28 +00005350 unsigned CallSiteIndex = MMI.getCurrentCallSite();
Jim Grosbachca752c92010-01-28 01:45:32 +00005351 if (CallSiteIndex) {
Chris Lattner512063d2010-04-05 06:19:28 +00005352 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
Bill Wendling30e67402011-10-05 22:24:35 +00005353 LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
Bill Wendlinga8512ed2011-10-04 22:00:35 +00005354
Jim Grosbachca752c92010-01-28 01:45:32 +00005355 // Now that the call site is handled, stop tracking it.
Chris Lattner512063d2010-04-05 06:19:28 +00005356 MMI.setCurrentCallSite(0);
Jim Grosbachca752c92010-01-28 01:45:32 +00005357 }
5358
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005359 // Both PendingLoads and PendingExports must be flushed here;
5360 // this call might not return.
5361 (void)getRoot();
Chris Lattner7561d482010-03-14 02:33:54 +00005362 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getControlRoot(), BeginLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005363 }
5364
Dan Gohman98ca4f22009-08-05 01:29:28 +00005365 // Check if target-independent constraints permit a tail call here.
5366 // Target-dependent constraints are checked within TLI.LowerCallTo.
5367 if (isTailCall &&
Evan Cheng86809cc2010-02-03 03:28:02 +00005368 !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI))
Dan Gohman98ca4f22009-08-05 01:29:28 +00005369 isTailCall = false;
5370
Dan Gohmanbadcda42010-08-28 00:51:03 +00005371 // If there's a possibility that fast-isel has already selected some amount
5372 // of the current basic block, don't emit a tail call.
Nick Lewycky8a8d4792011-12-02 22:16:29 +00005373 if (isTailCall && TM.Options.EnableFastISel)
Dan Gohmanbadcda42010-08-28 00:51:03 +00005374 isTailCall = false;
5375
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00005376 TargetLowering::
5377 CallLoweringInfo CLI(getRoot(), RetTy, FTy, isTailCall, Callee, Args, DAG,
5378 getCurDebugLoc(), CS);
5379 std::pair<SDValue,SDValue> Result = TLI.LowerCallTo(CLI);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005380 assert((isTailCall || Result.second.getNode()) &&
5381 "Non-null chain expected with non-tail call!");
5382 assert((Result.second.getNode() || !Result.first.getNode()) &&
5383 "Null value expected with tail call!");
Bill Wendlinge80ae832009-12-22 00:50:32 +00005384 if (Result.first.getNode()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005385 setValue(CS.getInstruction(), Result.first);
Bill Wendlinge80ae832009-12-22 00:50:32 +00005386 } else if (!CanLowerReturn && Result.second.getNode()) {
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005387 // The instruction result is the result of loading from the
5388 // hidden sret parameter.
5389 SmallVector<EVT, 1> PVTs;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005390 Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005391
5392 ComputeValueVTs(TLI, PtrRetTy, PVTs);
5393 assert(PVTs.size() == 1 && "Pointers should fit in one register");
5394 EVT PtrVT = PVTs[0];
Eli Friedman2db0e9e2012-05-25 00:09:29 +00005395
5396 SmallVector<EVT, 4> RetTys;
5397 SmallVector<uint64_t, 4> Offsets;
5398 RetTy = FTy->getReturnType();
5399 ComputeValueVTs(TLI, RetTy, RetTys, &Offsets);
5400
5401 unsigned NumValues = RetTys.size();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005402 SmallVector<SDValue, 4> Values(NumValues);
5403 SmallVector<SDValue, 4> Chains(NumValues);
5404
5405 for (unsigned i = 0; i < NumValues; ++i) {
Bill Wendlinge80ae832009-12-22 00:50:32 +00005406 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
5407 DemoteStackSlot,
5408 DAG.getConstant(Offsets[i], PtrVT));
Eli Friedman2db0e9e2012-05-25 00:09:29 +00005409 SDValue L = DAG.getLoad(RetTys[i], getCurDebugLoc(), Result.second, Add,
Chris Lattnerecf42c42010-09-21 16:36:31 +00005410 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]),
Pete Cooperd752e0f2011-11-08 18:42:53 +00005411 false, false, false, 1);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005412 Values[i] = L;
5413 Chains[i] = L.getValue(1);
5414 }
Bill Wendlinge80ae832009-12-22 00:50:32 +00005415
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005416 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
5417 MVT::Other, &Chains[0], NumValues);
5418 PendingLoads.push_back(Chain);
Michael J. Spencere70c5262010-10-16 08:25:21 +00005419
Bill Wendling4533cac2010-01-28 21:51:40 +00005420 setValue(CS.getInstruction(),
5421 DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
5422 DAG.getVTList(&RetTys[0], RetTys.size()),
Eli Friedman2db0e9e2012-05-25 00:09:29 +00005423 &Values[0], Values.size()));
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005424 }
Bill Wendlinge80ae832009-12-22 00:50:32 +00005425
Evan Chengc249e482011-04-01 19:57:01 +00005426 // Assign order to nodes here. If the call does not produce a result, it won't
5427 // be mapped to a SDNode and visit() will not assign it an order number.
Evan Cheng8380c032011-04-01 19:42:22 +00005428 if (!Result.second.getNode()) {
Evan Chengc249e482011-04-01 19:57:01 +00005429 // As a special case, a null chain means that a tail call has been emitted and
5430 // the DAG root is already updated.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005431 HasTailCall = true;
Evan Cheng8380c032011-04-01 19:42:22 +00005432 ++SDNodeOrder;
5433 AssignOrderingToNode(DAG.getRoot().getNode());
5434 } else {
5435 DAG.setRoot(Result.second);
5436 ++SDNodeOrder;
5437 AssignOrderingToNode(Result.second.getNode());
5438 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005439
Chris Lattner512063d2010-04-05 06:19:28 +00005440 if (LandingPad) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005441 // Insert a label at the end of the invoke call to mark the try range. This
5442 // can be used to detect deletion of the invoke via the MachineModuleInfo.
Chris Lattner512063d2010-04-05 06:19:28 +00005443 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
Chris Lattner7561d482010-03-14 02:33:54 +00005444 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getRoot(), EndLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005445
5446 // Inform MachineModuleInfo of range.
Chris Lattner512063d2010-04-05 06:19:28 +00005447 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005448 }
5449}
5450
Chris Lattner8047d9a2009-12-24 00:37:38 +00005451/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5452/// value is equal or not-equal to zero.
Dan Gohman46510a72010-04-15 01:51:59 +00005453static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
5454 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Chris Lattner8047d9a2009-12-24 00:37:38 +00005455 UI != E; ++UI) {
Dan Gohman46510a72010-04-15 01:51:59 +00005456 if (const ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
Chris Lattner8047d9a2009-12-24 00:37:38 +00005457 if (IC->isEquality())
Dan Gohman46510a72010-04-15 01:51:59 +00005458 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
Chris Lattner8047d9a2009-12-24 00:37:38 +00005459 if (C->isNullValue())
5460 continue;
5461 // Unknown instruction.
5462 return false;
5463 }
5464 return true;
5465}
5466
Dan Gohman46510a72010-04-15 01:51:59 +00005467static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005468 Type *LoadTy,
Chris Lattner8047d9a2009-12-24 00:37:38 +00005469 SelectionDAGBuilder &Builder) {
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005470
Chris Lattner8047d9a2009-12-24 00:37:38 +00005471 // Check to see if this load can be trivially constant folded, e.g. if the
5472 // input is from a string literal.
Dan Gohman46510a72010-04-15 01:51:59 +00005473 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
Chris Lattner8047d9a2009-12-24 00:37:38 +00005474 // Cast pointer to the type we really want to load.
Dan Gohman46510a72010-04-15 01:51:59 +00005475 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
Chris Lattner8047d9a2009-12-24 00:37:38 +00005476 PointerType::getUnqual(LoadTy));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005477
Dan Gohman46510a72010-04-15 01:51:59 +00005478 if (const Constant *LoadCst =
5479 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
5480 Builder.TD))
Chris Lattner8047d9a2009-12-24 00:37:38 +00005481 return Builder.getValue(LoadCst);
5482 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005483
Chris Lattner8047d9a2009-12-24 00:37:38 +00005484 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
5485 // still constant memory, the input chain can be the entry node.
5486 SDValue Root;
5487 bool ConstantMemory = false;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005488
Chris Lattner8047d9a2009-12-24 00:37:38 +00005489 // Do not serialize (non-volatile) loads of constant memory with anything.
5490 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5491 Root = Builder.DAG.getEntryNode();
5492 ConstantMemory = true;
5493 } else {
5494 // Do not serialize non-volatile loads against each other.
5495 Root = Builder.DAG.getRoot();
5496 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005497
Chris Lattner8047d9a2009-12-24 00:37:38 +00005498 SDValue Ptr = Builder.getValue(PtrVal);
5499 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root,
Chris Lattnerecf42c42010-09-21 16:36:31 +00005500 Ptr, MachinePointerInfo(PtrVal),
David Greene1e559442010-02-15 17:00:31 +00005501 false /*volatile*/,
Pete Cooperd752e0f2011-11-08 18:42:53 +00005502 false /*nontemporal*/,
5503 false /*isinvariant*/, 1 /* align=1 */);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005504
Chris Lattner8047d9a2009-12-24 00:37:38 +00005505 if (!ConstantMemory)
5506 Builder.PendingLoads.push_back(LoadVal.getValue(1));
5507 return LoadVal;
5508}
5509
5510
5511/// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5512/// If so, return true and lower it, otherwise return false and it will be
5513/// lowered like a normal call.
Dan Gohman46510a72010-04-15 01:51:59 +00005514bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
Chris Lattner8047d9a2009-12-24 00:37:38 +00005515 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
Gabor Greif37387d52010-06-30 12:55:46 +00005516 if (I.getNumArgOperands() != 3)
Chris Lattner8047d9a2009-12-24 00:37:38 +00005517 return false;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005518
Gabor Greif0635f352010-06-25 09:38:13 +00005519 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
Duncan Sands1df98592010-02-16 11:11:14 +00005520 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
Gabor Greif0635f352010-06-25 09:38:13 +00005521 !I.getArgOperand(2)->getType()->isIntegerTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00005522 !I.getType()->isIntegerTy())
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005523 return false;
5524
Gabor Greif0635f352010-06-25 09:38:13 +00005525 const ConstantInt *Size = dyn_cast<ConstantInt>(I.getArgOperand(2));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005526
Chris Lattner8047d9a2009-12-24 00:37:38 +00005527 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
5528 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
Chris Lattner04b091a2009-12-24 01:07:17 +00005529 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) {
5530 bool ActuallyDoIt = true;
5531 MVT LoadVT;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005532 Type *LoadTy;
Chris Lattner04b091a2009-12-24 01:07:17 +00005533 switch (Size->getZExtValue()) {
5534 default:
5535 LoadVT = MVT::Other;
5536 LoadTy = 0;
5537 ActuallyDoIt = false;
5538 break;
5539 case 2:
5540 LoadVT = MVT::i16;
5541 LoadTy = Type::getInt16Ty(Size->getContext());
5542 break;
5543 case 4:
5544 LoadVT = MVT::i32;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005545 LoadTy = Type::getInt32Ty(Size->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00005546 break;
5547 case 8:
5548 LoadVT = MVT::i64;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005549 LoadTy = Type::getInt64Ty(Size->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00005550 break;
5551 /*
5552 case 16:
5553 LoadVT = MVT::v4i32;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005554 LoadTy = Type::getInt32Ty(Size->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00005555 LoadTy = VectorType::get(LoadTy, 4);
5556 break;
5557 */
5558 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005559
Chris Lattner04b091a2009-12-24 01:07:17 +00005560 // This turns into unaligned loads. We only do this if the target natively
5561 // supports the MVT we'll be loading or if it is small enough (<= 4) that
5562 // we'll only produce a small number of byte loads.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005563
Chris Lattner04b091a2009-12-24 01:07:17 +00005564 // Require that we can find a legal MVT, and only do this if the target
5565 // supports unaligned loads of that type. Expanding into byte loads would
5566 // bloat the code.
5567 if (ActuallyDoIt && Size->getZExtValue() > 4) {
5568 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5569 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
5570 if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT))
5571 ActuallyDoIt = false;
5572 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005573
Chris Lattner04b091a2009-12-24 01:07:17 +00005574 if (ActuallyDoIt) {
5575 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5576 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005577
Chris Lattner04b091a2009-12-24 01:07:17 +00005578 SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal,
5579 ISD::SETNE);
5580 EVT CallVT = TLI.getValueType(I.getType(), true);
5581 setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT));
5582 return true;
5583 }
Chris Lattner8047d9a2009-12-24 00:37:38 +00005584 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005585
5586
Chris Lattner8047d9a2009-12-24 00:37:38 +00005587 return false;
5588}
5589
Bob Wilson53624a22012-08-03 23:29:17 +00005590/// visitUnaryFloatCall - If a call instruction is a unary floating-point
5591/// operation (as expected), translate it to an SDNode with the specified opcode
5592/// and return true.
5593bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
5594 unsigned Opcode) {
5595 // Sanity check that it really is a unary floating-point call.
5596 if (I.getNumArgOperands() != 1 ||
5597 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5598 I.getType() != I.getArgOperand(0)->getType() ||
5599 !I.onlyReadsMemory())
5600 return false;
5601
5602 SDValue Tmp = getValue(I.getArgOperand(0));
5603 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(), Tmp.getValueType(), Tmp));
5604 return true;
5605}
Chris Lattner8047d9a2009-12-24 00:37:38 +00005606
Dan Gohman46510a72010-04-15 01:51:59 +00005607void SelectionDAGBuilder::visitCall(const CallInst &I) {
Chris Lattner598751e2010-07-05 05:36:21 +00005608 // Handle inline assembly differently.
5609 if (isa<InlineAsm>(I.getCalledValue())) {
5610 visitInlineAsm(&I);
5611 return;
5612 }
Michael J. Spencere70c5262010-10-16 08:25:21 +00005613
Michael J. Spencer391b43b2010-10-21 20:49:23 +00005614 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Michael J. Spencerc9c137b2012-02-22 19:06:13 +00005615 ComputeUsesVAFloatArgument(I, &MMI);
Michael J. Spencer391b43b2010-10-21 20:49:23 +00005616
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005617 const char *RenameFn = 0;
5618 if (Function *F = I.getCalledFunction()) {
5619 if (F->isDeclaration()) {
Chris Lattner598751e2010-07-05 05:36:21 +00005620 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
Dale Johannesen49de9822009-02-05 01:49:45 +00005621 if (unsigned IID = II->getIntrinsicID(F)) {
5622 RenameFn = visitIntrinsicCall(I, IID);
5623 if (!RenameFn)
5624 return;
5625 }
5626 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005627 if (unsigned IID = F->getIntrinsicID()) {
5628 RenameFn = visitIntrinsicCall(I, IID);
5629 if (!RenameFn)
5630 return;
5631 }
5632 }
5633
5634 // Check for well-known libc/libm calls. If the function is internal, it
5635 // can't be a library call.
Bob Wilson982dc842012-08-03 21:26:24 +00005636 LibFunc::Func Func;
5637 if (!F->hasLocalLinkage() && F->hasName() &&
5638 LibInfo->getLibFunc(F->getName(), Func) &&
5639 LibInfo->hasOptimizedCodeGen(Func)) {
5640 switch (Func) {
5641 default: break;
5642 case LibFunc::copysign:
5643 case LibFunc::copysignf:
5644 case LibFunc::copysignl:
Gabor Greif37387d52010-06-30 12:55:46 +00005645 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
Gabor Greif0635f352010-06-25 09:38:13 +00005646 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5647 I.getType() == I.getArgOperand(0)->getType() &&
Bob Wilson53624a22012-08-03 23:29:17 +00005648 I.getType() == I.getArgOperand(1)->getType() &&
5649 I.onlyReadsMemory()) {
Gabor Greif0635f352010-06-25 09:38:13 +00005650 SDValue LHS = getValue(I.getArgOperand(0));
5651 SDValue RHS = getValue(I.getArgOperand(1));
Bill Wendling0d580132009-12-23 01:28:19 +00005652 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
5653 LHS.getValueType(), LHS, RHS));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005654 return;
5655 }
Bob Wilson982dc842012-08-03 21:26:24 +00005656 break;
5657 case LibFunc::fabs:
5658 case LibFunc::fabsf:
5659 case LibFunc::fabsl:
Bob Wilson53624a22012-08-03 23:29:17 +00005660 if (visitUnaryFloatCall(I, ISD::FABS))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005661 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005662 break;
5663 case LibFunc::sin:
5664 case LibFunc::sinf:
5665 case LibFunc::sinl:
Bob Wilson53624a22012-08-03 23:29:17 +00005666 if (visitUnaryFloatCall(I, ISD::FSIN))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005667 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005668 break;
5669 case LibFunc::cos:
5670 case LibFunc::cosf:
5671 case LibFunc::cosl:
Bob Wilson53624a22012-08-03 23:29:17 +00005672 if (visitUnaryFloatCall(I, ISD::FCOS))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005673 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005674 break;
5675 case LibFunc::sqrt:
5676 case LibFunc::sqrtf:
5677 case LibFunc::sqrtl:
Bob Wilson53624a22012-08-03 23:29:17 +00005678 if (visitUnaryFloatCall(I, ISD::FSQRT))
Dale Johannesen52fb79b2009-09-25 17:23:22 +00005679 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005680 break;
5681 case LibFunc::floor:
5682 case LibFunc::floorf:
5683 case LibFunc::floorl:
Bob Wilson53624a22012-08-03 23:29:17 +00005684 if (visitUnaryFloatCall(I, ISD::FFLOOR))
Owen Anderson4a4fdf32011-12-08 19:32:14 +00005685 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005686 break;
5687 case LibFunc::nearbyint:
5688 case LibFunc::nearbyintf:
5689 case LibFunc::nearbyintl:
Bob Wilson53624a22012-08-03 23:29:17 +00005690 if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
Owen Anderson4a4fdf32011-12-08 19:32:14 +00005691 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005692 break;
5693 case LibFunc::ceil:
5694 case LibFunc::ceilf:
5695 case LibFunc::ceill:
Bob Wilson53624a22012-08-03 23:29:17 +00005696 if (visitUnaryFloatCall(I, ISD::FCEIL))
Owen Anderson4a4fdf32011-12-08 19:32:14 +00005697 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005698 break;
5699 case LibFunc::rint:
5700 case LibFunc::rintf:
5701 case LibFunc::rintl:
Bob Wilson53624a22012-08-03 23:29:17 +00005702 if (visitUnaryFloatCall(I, ISD::FRINT))
Owen Anderson4a4fdf32011-12-08 19:32:14 +00005703 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005704 break;
5705 case LibFunc::trunc:
5706 case LibFunc::truncf:
5707 case LibFunc::truncl:
Bob Wilson53624a22012-08-03 23:29:17 +00005708 if (visitUnaryFloatCall(I, ISD::FTRUNC))
Owen Anderson4a4fdf32011-12-08 19:32:14 +00005709 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005710 break;
5711 case LibFunc::log2:
5712 case LibFunc::log2f:
5713 case LibFunc::log2l:
Bob Wilson53624a22012-08-03 23:29:17 +00005714 if (visitUnaryFloatCall(I, ISD::FLOG2))
Owen Anderson4e0adfa2011-12-15 00:54:12 +00005715 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005716 break;
5717 case LibFunc::exp2:
5718 case LibFunc::exp2f:
5719 case LibFunc::exp2l:
Bob Wilson53624a22012-08-03 23:29:17 +00005720 if (visitUnaryFloatCall(I, ISD::FEXP2))
Owen Anderson4e0adfa2011-12-15 00:54:12 +00005721 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005722 break;
5723 case LibFunc::memcmp:
Chris Lattner8047d9a2009-12-24 00:37:38 +00005724 if (visitMemCmpCall(I))
5725 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005726 break;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005727 }
5728 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005729 }
Michael J. Spencere70c5262010-10-16 08:25:21 +00005730
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005731 SDValue Callee;
5732 if (!RenameFn)
Gabor Greif0635f352010-06-25 09:38:13 +00005733 Callee = getValue(I.getCalledValue());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005734 else
Bill Wendling056292f2008-09-16 21:48:12 +00005735 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005736
Bill Wendling0d580132009-12-23 01:28:19 +00005737 // Check if we can potentially perform a tail call. More detailed checking is
5738 // be done within LowerCallTo, after more information about the call is known.
Evan Cheng11e67932010-01-26 23:13:04 +00005739 LowerCallTo(&I, Callee, I.isTailCall());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005740}
5741
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00005742namespace {
Dan Gohman462f6b52010-05-29 17:53:24 +00005743
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005744/// AsmOperandInfo - This contains information for each constraint that we are
5745/// lowering.
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00005746class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
Cedric Venetaff9c272009-02-14 16:06:42 +00005747public:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005748 /// CallOperand - If this is the result output operand or a clobber
5749 /// this is null, otherwise it is the incoming operand to the CallInst.
5750 /// This gets modified as the asm is processed.
5751 SDValue CallOperand;
5752
5753 /// AssignedRegs - If this is a register or register class operand, this
5754 /// contains the set of register corresponding to the operand.
5755 RegsForValue AssignedRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005756
John Thompsoneac6e1d2010-09-13 18:15:37 +00005757 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005758 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
5759 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005760
Owen Andersone50ed302009-08-10 22:56:29 +00005761 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
Chris Lattner81249c92008-10-17 17:05:25 +00005762 /// corresponds to. If there is no Value* for this operand, it returns
Owen Anderson825b72b2009-08-11 20:47:22 +00005763 /// MVT::Other.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005764 EVT getCallOperandValEVT(LLVMContext &Context,
Owen Anderson1d0be152009-08-13 21:58:54 +00005765 const TargetLowering &TLI,
Micah Villmow3574eca2012-10-08 16:38:25 +00005766 const DataLayout *TD) const {
Owen Anderson825b72b2009-08-11 20:47:22 +00005767 if (CallOperandVal == 0) return MVT::Other;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005768
Chris Lattner81249c92008-10-17 17:05:25 +00005769 if (isa<BasicBlock>(CallOperandVal))
5770 return TLI.getPointerTy();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005771
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005772 llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005773
Eric Christophercef81b72011-05-09 20:04:43 +00005774 // FIXME: code duplicated from TargetLowering::ParseConstraints().
Chris Lattner81249c92008-10-17 17:05:25 +00005775 // If this is an indirect operand, the operand is a pointer to the
5776 // accessed type.
Bob Wilsone261b0c2009-12-22 18:34:19 +00005777 if (isIndirect) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005778 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
Bob Wilsone261b0c2009-12-22 18:34:19 +00005779 if (!PtrTy)
Chris Lattner75361b62010-04-07 22:58:41 +00005780 report_fatal_error("Indirect operand for inline asm not a pointer!");
Bob Wilsone261b0c2009-12-22 18:34:19 +00005781 OpTy = PtrTy->getElementType();
5782 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005783
Eric Christophercef81b72011-05-09 20:04:43 +00005784 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005785 if (StructType *STy = dyn_cast<StructType>(OpTy))
Eric Christophercef81b72011-05-09 20:04:43 +00005786 if (STy->getNumElements() == 1)
5787 OpTy = STy->getElementType(0);
5788
Chris Lattner81249c92008-10-17 17:05:25 +00005789 // If OpTy is not a single value, it may be a struct/union that we
5790 // can tile with integers.
5791 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5792 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
5793 switch (BitSize) {
5794 default: break;
5795 case 1:
5796 case 8:
5797 case 16:
5798 case 32:
5799 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00005800 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00005801 OpTy = IntegerType::get(Context, BitSize);
Chris Lattner81249c92008-10-17 17:05:25 +00005802 break;
5803 }
5804 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005805
Chris Lattner81249c92008-10-17 17:05:25 +00005806 return TLI.getValueType(OpTy, true);
5807 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005808};
Dan Gohman462f6b52010-05-29 17:53:24 +00005809
John Thompson44ab89e2010-10-29 17:29:13 +00005810typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
5811
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00005812} // end anonymous namespace
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005813
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005814/// GetRegistersForValue - Assign registers (virtual or physical) for the
5815/// specified operand. We prefer to assign virtual registers, to allow the
Bob Wilson266d9452009-12-17 05:07:36 +00005816/// register allocator to handle the assignment process. However, if the asm
5817/// uses features that we can't model on machineinstrs, we have SDISel do the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005818/// allocation. This produces generally horrible, but correct, code.
5819///
5820/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005821///
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00005822static void GetRegistersForValue(SelectionDAG &DAG,
5823 const TargetLowering &TLI,
5824 DebugLoc DL,
Benjamin Kramer8b93ff22012-02-24 14:01:17 +00005825 SDISelAsmOperandInfo &OpInfo) {
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00005826 LLVMContext &Context = *DAG.getContext();
Owen Anderson23b9b192009-08-12 00:36:31 +00005827
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005828 MachineFunction &MF = DAG.getMachineFunction();
5829 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005830
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005831 // If this is a constraint for a single physreg, or a constraint for a
5832 // register class, find it.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005833 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005834 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5835 OpInfo.ConstraintVT);
5836
5837 unsigned NumRegs = 1;
Owen Anderson825b72b2009-08-11 20:47:22 +00005838 if (OpInfo.ConstraintVT != MVT::Other) {
Chris Lattner01426e12008-10-21 00:45:36 +00005839 // If this is a FP input in an integer register (or visa versa) insert a bit
5840 // cast of the input value. More generally, handle any case where the input
5841 // value disagrees with the register class we plan to stick this in.
5842 if (OpInfo.Type == InlineAsm::isInput &&
5843 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
Owen Andersone50ed302009-08-10 22:56:29 +00005844 // Try to convert to the first EVT that the reg class contains. If the
Chris Lattner01426e12008-10-21 00:45:36 +00005845 // types are identical size, use a bitcast to convert (e.g. two differing
5846 // vector types).
Owen Andersone50ed302009-08-10 22:56:29 +00005847 EVT RegVT = *PhysReg.second->vt_begin();
Chris Lattner01426e12008-10-21 00:45:36 +00005848 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00005849 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005850 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00005851 OpInfo.ConstraintVT = RegVT;
5852 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5853 // If the input is a FP value and we want it in FP registers, do a
5854 // bitcast to the corresponding integer type. This turns an f64 value
5855 // into i64, which can be passed with two i32 values on a 32-bit
5856 // machine.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005857 RegVT = EVT::getIntegerVT(Context,
Owen Anderson23b9b192009-08-12 00:36:31 +00005858 OpInfo.ConstraintVT.getSizeInBits());
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00005859 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005860 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00005861 OpInfo.ConstraintVT = RegVT;
5862 }
5863 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005864
Owen Anderson23b9b192009-08-12 00:36:31 +00005865 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00005866 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005867
Owen Andersone50ed302009-08-10 22:56:29 +00005868 EVT RegVT;
5869 EVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005870
5871 // If this is a constraint for a specific physical register, like {r17},
5872 // assign it now.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005873 if (unsigned AssignedReg = PhysReg.first) {
5874 const TargetRegisterClass *RC = PhysReg.second;
Owen Anderson825b72b2009-08-11 20:47:22 +00005875 if (OpInfo.ConstraintVT == MVT::Other)
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005876 ValueVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005877
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005878 // Get the actual register value type. This is important, because the user
5879 // may have asked for (e.g.) the AX register in i32 type. We need to
5880 // remember that AX is actually i16 to get the right extension.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005881 RegVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005882
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005883 // This is a explicit reference to a physical register.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005884 Regs.push_back(AssignedReg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005885
5886 // If this is an expanded reference, add the rest of the regs to Regs.
5887 if (NumRegs != 1) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005888 TargetRegisterClass::iterator I = RC->begin();
5889 for (; *I != AssignedReg; ++I)
5890 assert(I != RC->end() && "Didn't find reg!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005891
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005892 // Already added the first reg.
5893 --NumRegs; ++I;
5894 for (; NumRegs; --NumRegs, ++I) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005895 assert(I != RC->end() && "Ran out of registers to allocate!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005896 Regs.push_back(*I);
5897 }
5898 }
Bill Wendling651ad132009-12-22 01:25:10 +00005899
Dan Gohman7451d3e2010-05-29 17:03:36 +00005900 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005901 return;
5902 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005903
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005904 // Otherwise, if this was a reference to an LLVM register class, create vregs
5905 // for this reference.
Chris Lattnerb3b44842009-03-24 15:25:07 +00005906 if (const TargetRegisterClass *RC = PhysReg.second) {
5907 RegVT = *RC->vt_begin();
Owen Anderson825b72b2009-08-11 20:47:22 +00005908 if (OpInfo.ConstraintVT == MVT::Other)
Evan Chengfb112882009-03-23 08:01:15 +00005909 ValueVT = RegVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005910
Evan Chengfb112882009-03-23 08:01:15 +00005911 // Create the appropriate number of virtual registers.
5912 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5913 for (; NumRegs; --NumRegs)
Chris Lattnerb3b44842009-03-24 15:25:07 +00005914 Regs.push_back(RegInfo.createVirtualRegister(RC));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005915
Dan Gohman7451d3e2010-05-29 17:03:36 +00005916 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
Evan Chengfb112882009-03-23 08:01:15 +00005917 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005918 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005919
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005920 // Otherwise, we couldn't allocate enough registers for this.
5921}
5922
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005923/// visitInlineAsm - Handle a call to an InlineAsm object.
5924///
Dan Gohman46510a72010-04-15 01:51:59 +00005925void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
5926 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005927
5928 /// ConstraintOperands - Information about all of the constraints.
John Thompson44ab89e2010-10-29 17:29:13 +00005929 SDISelAsmOperandInfoVector ConstraintOperands;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005930
Evan Chengce1cdac2011-05-06 20:52:23 +00005931 TargetLowering::AsmOperandInfoVector
5932 TargetConstraints = TLI.ParseConstraints(CS);
5933
John Thompsoneac6e1d2010-09-13 18:15:37 +00005934 bool hasMemory = false;
Michael J. Spencere70c5262010-10-16 08:25:21 +00005935
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005936 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5937 unsigned ResNo = 0; // ResNo - The result number of the next output.
John Thompsoneac6e1d2010-09-13 18:15:37 +00005938 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
5939 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005940 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Michael J. Spencere70c5262010-10-16 08:25:21 +00005941
Owen Anderson825b72b2009-08-11 20:47:22 +00005942 EVT OpVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005943
5944 // Compute the value type for each operand.
5945 switch (OpInfo.Type) {
5946 case InlineAsm::isOutput:
5947 // Indirect outputs just consume an argument.
5948 if (OpInfo.isIndirect) {
Dan Gohman46510a72010-04-15 01:51:59 +00005949 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005950 break;
5951 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005952
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005953 // The return value of the call is this value. As such, there is no
5954 // corresponding argument.
Nick Lewycky8de34002011-09-30 22:19:53 +00005955 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005956 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005957 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5958 } else {
5959 assert(ResNo == 0 && "Asm only has one result!");
5960 OpVT = TLI.getValueType(CS.getType());
5961 }
5962 ++ResNo;
5963 break;
5964 case InlineAsm::isInput:
Dan Gohman46510a72010-04-15 01:51:59 +00005965 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005966 break;
5967 case InlineAsm::isClobber:
5968 // Nothing to do.
5969 break;
5970 }
5971
5972 // If this is an input or an indirect output, process the call argument.
5973 // BasicBlocks are labels, currently appearing only in asm's.
5974 if (OpInfo.CallOperandVal) {
Dan Gohman46510a72010-04-15 01:51:59 +00005975 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005976 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00005977 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005978 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005979 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005980
Owen Anderson1d0be152009-08-13 21:58:54 +00005981 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005982 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005983
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005984 OpInfo.ConstraintVT = OpVT;
Michael J. Spencere70c5262010-10-16 08:25:21 +00005985
John Thompsoneac6e1d2010-09-13 18:15:37 +00005986 // Indirect operand accesses access memory.
5987 if (OpInfo.isIndirect)
5988 hasMemory = true;
5989 else {
5990 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
Evan Chengce1cdac2011-05-06 20:52:23 +00005991 TargetLowering::ConstraintType
5992 CType = TLI.getConstraintType(OpInfo.Codes[j]);
John Thompsoneac6e1d2010-09-13 18:15:37 +00005993 if (CType == TargetLowering::C_Memory) {
5994 hasMemory = true;
5995 break;
5996 }
5997 }
5998 }
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005999 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006000
John Thompsoneac6e1d2010-09-13 18:15:37 +00006001 SDValue Chain, Flag;
6002
6003 // We won't need to flush pending loads if this asm doesn't touch
6004 // memory and is nonvolatile.
6005 if (hasMemory || IA->hasSideEffects())
6006 Chain = getRoot();
6007 else
6008 Chain = DAG.getRoot();
6009
Chris Lattner2a0b96c2008-10-18 18:49:30 +00006010 // Second pass over the constraints: compute which constraint option to use
6011 // and assign registers to constraints that want a specific physreg.
John Thompsoneac6e1d2010-09-13 18:15:37 +00006012 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Chris Lattner2a0b96c2008-10-18 18:49:30 +00006013 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006014
John Thompson54584742010-09-24 22:24:05 +00006015 // If this is an output operand with a matching input operand, look up the
6016 // matching input. If their types mismatch, e.g. one is an integer, the
6017 // other is floating point, or their sizes are different, flag it as an
6018 // error.
6019 if (OpInfo.hasMatchingInput()) {
6020 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
Michael J. Spencere70c5262010-10-16 08:25:21 +00006021
John Thompson54584742010-09-24 22:24:05 +00006022 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Bill Wendling96cb1122012-07-19 00:04:14 +00006023 std::pair<unsigned, const TargetRegisterClass*> MatchRC =
6024 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
Evan Cheng1dafa702011-08-23 19:17:21 +00006025 OpInfo.ConstraintVT);
Bill Wendling96cb1122012-07-19 00:04:14 +00006026 std::pair<unsigned, const TargetRegisterClass*> InputRC =
6027 TLI.getRegForInlineAsmConstraint(Input.ConstraintCode,
Evan Cheng1dafa702011-08-23 19:17:21 +00006028 Input.ConstraintVT);
John Thompson54584742010-09-24 22:24:05 +00006029 if ((OpInfo.ConstraintVT.isInteger() !=
6030 Input.ConstraintVT.isInteger()) ||
Eric Christopher5427ede2011-07-14 20:13:52 +00006031 (MatchRC.second != InputRC.second)) {
John Thompson54584742010-09-24 22:24:05 +00006032 report_fatal_error("Unsupported asm: input constraint"
6033 " with a matching output constraint of"
6034 " incompatible type!");
6035 }
6036 Input.ConstraintVT = OpInfo.ConstraintVT;
6037 }
6038 }
6039
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006040 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +00006041 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006042
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006043 // If this is a memory input, and if the operand is not indirect, do what we
6044 // need to to provide an address for the memory input.
6045 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
6046 !OpInfo.isIndirect) {
Evan Chengce1cdac2011-05-06 20:52:23 +00006047 assert((OpInfo.isMultipleAlternative ||
6048 (OpInfo.Type == InlineAsm::isInput)) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006049 "Can only indirectify direct input operands!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006050
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006051 // Memory operands really want the address of the value. If we don't have
6052 // an indirect input, put it in the constpool if we can, otherwise spill
6053 // it to a stack slot.
Eric Christophere0b42c02011-06-03 17:21:23 +00006054 // TODO: This isn't quite right. We need to handle these according to
6055 // the addressing mode that the constraint wants. Also, this may take
6056 // an additional register for the computation and we don't want that
6057 // either.
Eric Christopher471e4222011-06-08 23:55:35 +00006058
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006059 // If the operand is a float, integer, or vector constant, spill to a
6060 // constant pool entry to get its address.
Dan Gohman46510a72010-04-15 01:51:59 +00006061 const Value *OpVal = OpInfo.CallOperandVal;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006062 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
Chris Lattnera78fa8c2012-01-27 03:08:05 +00006063 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006064 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
6065 TLI.getPointerTy());
6066 } else {
6067 // Otherwise, create a stack slot and emit a store to it before the
6068 // asm.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00006069 Type *Ty = OpVal->getType();
Micah Villmow3574eca2012-10-08 16:38:25 +00006070 uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(Ty);
6071 unsigned Align = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006072 MachineFunction &MF = DAG.getMachineFunction();
David Greene3f2bf852009-11-12 20:49:22 +00006073 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006074 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Dale Johannesen66978ee2009-01-31 02:22:37 +00006075 Chain = DAG.getStore(Chain, getCurDebugLoc(),
Chris Lattnerecf42c42010-09-21 16:36:31 +00006076 OpInfo.CallOperand, StackSlot,
6077 MachinePointerInfo::getFixedStack(SSFI),
David Greene1e559442010-02-15 17:00:31 +00006078 false, false, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006079 OpInfo.CallOperand = StackSlot;
6080 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006081
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006082 // There is no longer a Value* corresponding to this operand.
6083 OpInfo.CallOperandVal = 0;
Bill Wendling651ad132009-12-22 01:25:10 +00006084
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006085 // It is now an indirect operand.
6086 OpInfo.isIndirect = true;
6087 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006088
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006089 // If this constraint is for a specific register, allocate it before
6090 // anything else.
6091 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Benjamin Kramer8b93ff22012-02-24 14:01:17 +00006092 GetRegistersForValue(DAG, TLI, getCurDebugLoc(), OpInfo);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006093 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006094
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006095 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00006096 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006097 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6098 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006099
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006100 // C_Register operands have already been allocated, Other/Memory don't need
6101 // to be.
6102 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Benjamin Kramer8b93ff22012-02-24 14:01:17 +00006103 GetRegistersForValue(DAG, TLI, getCurDebugLoc(), OpInfo);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006104 }
6105
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006106 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6107 std::vector<SDValue> AsmNodeOperands;
6108 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
6109 AsmNodeOperands.push_back(
Dan Gohmanf2d7fb32010-01-04 21:00:54 +00006110 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
6111 TLI.getPointerTy()));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006112
Chris Lattnerdecc2672010-04-07 05:20:54 +00006113 // If we have a !srcloc metadata node associated with it, we want to attach
6114 // this to the ultimately generated inline asm machineinstr. To do this, we
6115 // pass in the third operand as this (potentially null) inline asm MDNode.
6116 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
6117 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006118
Chad Rosier3d716882012-10-30 19:11:54 +00006119 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
6120 // bits as operand 3.
Evan Chengc36b7062011-01-07 23:50:32 +00006121 unsigned ExtraInfo = 0;
6122 if (IA->hasSideEffects())
6123 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
6124 if (IA->isAlignStack())
6125 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
Chad Rosier77fffa62012-09-05 22:17:43 +00006126 // Set the asm dialect.
Chad Rosier2f1d8152012-09-05 22:40:13 +00006127 ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
Chad Rosier3d716882012-10-30 19:11:54 +00006128
6129 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
6130 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6131 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
6132
6133 // Compute the constraint code and ConstraintType to use.
6134 TLI.ComputeConstraintToUse(OpInfo, SDValue());
6135
Chad Rosierdfa4cec2012-10-30 20:01:12 +00006136 // Ideally, we would only check against memory constraints. However, the
6137 // meaning of an other constraint can be target-specific and we can't easily
6138 // reason about it. Therefore, be conservative and set MayLoad/MayStore
6139 // for other constriants as well.
Chad Rosier3d716882012-10-30 19:11:54 +00006140 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
6141 OpInfo.ConstraintType == TargetLowering::C_Other) {
6142 if (OpInfo.Type == InlineAsm::isInput)
6143 ExtraInfo |= InlineAsm::Extra_MayLoad;
6144 else if (OpInfo.Type == InlineAsm::isOutput)
6145 ExtraInfo |= InlineAsm::Extra_MayStore;
6146 }
6147 }
6148
Evan Chengc36b7062011-01-07 23:50:32 +00006149 AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
6150 TLI.getPointerTy()));
Dale Johannesenf1e309e2010-07-02 20:16:09 +00006151
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006152 // Loop over all of the inputs, copying the operand values into the
6153 // appropriate registers and processing the output regs.
6154 RegsForValue RetValRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006155
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006156 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6157 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006158
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006159 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6160 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6161
6162 switch (OpInfo.Type) {
6163 case InlineAsm::isOutput: {
6164 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6165 OpInfo.ConstraintType != TargetLowering::C_Register) {
6166 // Memory output, or 'other' output (e.g. 'X' constraint).
6167 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6168
6169 // Add information to the INLINEASM node to know about this output.
Chris Lattnerdecc2672010-04-07 05:20:54 +00006170 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6171 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006172 TLI.getPointerTy()));
6173 AsmNodeOperands.push_back(OpInfo.CallOperand);
6174 break;
6175 }
6176
6177 // Otherwise, this is a register or register class output.
6178
6179 // Copy the output from the appropriate register. Find a register that
6180 // we can use.
Chris Lattnerfcd70902012-01-03 23:51:01 +00006181 if (OpInfo.AssignedRegs.Regs.empty()) {
6182 LLVMContext &Ctx = *DAG.getContext();
6183 Ctx.emitError(CS.getInstruction(),
6184 "couldn't allocate output register for constraint '" +
6185 Twine(OpInfo.ConstraintCode) + "'");
6186 break;
6187 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006188
6189 // If this is an indirect operand, store through the pointer after the
6190 // asm.
6191 if (OpInfo.isIndirect) {
6192 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6193 OpInfo.CallOperandVal));
6194 } else {
6195 // This is the result value of the call.
Benjamin Kramerf0127052010-01-05 13:12:22 +00006196 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006197 // Concatenate this output onto the outputs list.
6198 RetValRegs.append(OpInfo.AssignedRegs);
6199 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006200
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006201 // Add information to the INLINEASM node to know that this register is
6202 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00006203 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
Chris Lattnerdecc2672010-04-07 05:20:54 +00006204 InlineAsm::Kind_RegDefEarlyClobber :
6205 InlineAsm::Kind_RegDef,
Evan Chengfb112882009-03-23 08:01:15 +00006206 false,
6207 0,
Bill Wendling46ada192010-03-02 01:55:18 +00006208 DAG,
Bill Wendling651ad132009-12-22 01:25:10 +00006209 AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006210 break;
6211 }
6212 case InlineAsm::isInput: {
6213 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006214
Chris Lattner6bdcda32008-10-17 16:47:46 +00006215 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006216 // If this is required to match an output register we have already set,
6217 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00006218 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006219
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006220 // Scan until we find the definition we already emitted of this operand.
6221 // When we find it, create a RegsForValue operand.
Chris Lattnerdecc2672010-04-07 05:20:54 +00006222 unsigned CurOp = InlineAsm::Op_FirstOperand;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006223 for (; OperandNo; --OperandNo) {
6224 // Advance to the next operand.
Evan Cheng697cbbf2009-03-20 18:03:34 +00006225 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00006226 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Chris Lattnerdecc2672010-04-07 05:20:54 +00006227 assert((InlineAsm::isRegDefKind(OpFlag) ||
6228 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6229 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
Evan Cheng697cbbf2009-03-20 18:03:34 +00006230 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006231 }
6232
Evan Cheng697cbbf2009-03-20 18:03:34 +00006233 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00006234 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Chris Lattnerdecc2672010-04-07 05:20:54 +00006235 if (InlineAsm::isRegDefKind(OpFlag) ||
6236 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
Evan Cheng697cbbf2009-03-20 18:03:34 +00006237 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
Chris Lattner6129c372010-04-08 00:09:16 +00006238 if (OpInfo.isIndirect) {
6239 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
Dan Gohman99be8ae2010-04-19 22:41:47 +00006240 LLVMContext &Ctx = *DAG.getContext();
Chris Lattner6129c372010-04-08 00:09:16 +00006241 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
6242 " don't know how to handle tied "
6243 "indirect register inputs");
6244 }
Michael J. Spencere70c5262010-10-16 08:25:21 +00006245
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006246 RegsForValue MatchedRegs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006247 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
Owen Andersone50ed302009-08-10 22:56:29 +00006248 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
Evan Chengfb112882009-03-23 08:01:15 +00006249 MatchedRegs.RegVTs.push_back(RegVT);
6250 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
Evan Cheng697cbbf2009-03-20 18:03:34 +00006251 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
Evan Chengfb112882009-03-23 08:01:15 +00006252 i != e; ++i)
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00006253 MatchedRegs.Regs.push_back
6254 (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006255
6256 // Use the produced MatchedRegs object to
Dale Johannesen66978ee2009-01-31 02:22:37 +00006257 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
Bill Wendlingf18eb582012-09-26 06:16:18 +00006258 Chain, &Flag, CS.getInstruction());
Chris Lattnerdecc2672010-04-07 05:20:54 +00006259 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
Evan Chengfb112882009-03-23 08:01:15 +00006260 true, OpInfo.getMatchedOperand(),
Bill Wendling46ada192010-03-02 01:55:18 +00006261 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006262 break;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006263 }
Michael J. Spencere70c5262010-10-16 08:25:21 +00006264
Chris Lattnerdecc2672010-04-07 05:20:54 +00006265 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
6266 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
6267 "Unexpected number of operands");
6268 // Add information to the INLINEASM node to know about this input.
6269 // See InlineAsm.h isUseOperandTiedToDef.
6270 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
6271 OpInfo.getMatchedOperand());
6272 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
6273 TLI.getPointerTy()));
6274 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6275 break;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006276 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006277
Dale Johannesenb5611a62010-07-13 20:17:05 +00006278 // Treat indirect 'X' constraint as memory.
Michael J. Spencere70c5262010-10-16 08:25:21 +00006279 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
6280 OpInfo.isIndirect)
Dale Johannesenb5611a62010-07-13 20:17:05 +00006281 OpInfo.ConstraintType = TargetLowering::C_Memory;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006282
Dale Johannesenb5611a62010-07-13 20:17:05 +00006283 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006284 std::vector<SDValue> Ops;
Eric Christopher100c8332011-06-02 23:16:42 +00006285 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
Dale Johannesen1784d162010-06-25 21:55:36 +00006286 Ops, DAG);
Chris Lattnerfcd70902012-01-03 23:51:01 +00006287 if (Ops.empty()) {
6288 LLVMContext &Ctx = *DAG.getContext();
6289 Ctx.emitError(CS.getInstruction(),
6290 "invalid operand for inline asm constraint '" +
6291 Twine(OpInfo.ConstraintCode) + "'");
6292 break;
6293 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006294
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006295 // Add information to the INLINEASM node to know about this input.
Chris Lattnerdecc2672010-04-07 05:20:54 +00006296 unsigned ResOpType =
6297 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006298 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006299 TLI.getPointerTy()));
6300 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6301 break;
Chris Lattnerdecc2672010-04-07 05:20:54 +00006302 }
Michael J. Spencere70c5262010-10-16 08:25:21 +00006303
Chris Lattnerdecc2672010-04-07 05:20:54 +00006304 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006305 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
6306 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
6307 "Memory operands expect pointer values");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006308
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006309 // Add information to the INLINEASM node to know about this input.
Chris Lattnerdecc2672010-04-07 05:20:54 +00006310 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
Dale Johannesen86b49f82008-09-24 01:07:17 +00006311 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006312 TLI.getPointerTy()));
6313 AsmNodeOperands.push_back(InOperandVal);
6314 break;
6315 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006316
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006317 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6318 OpInfo.ConstraintType == TargetLowering::C_Register) &&
6319 "Unknown constraint type!");
Eric Christopher9eb4f8a2012-07-02 21:16:43 +00006320
6321 // TODO: Support this.
6322 if (OpInfo.isIndirect) {
6323 LLVMContext &Ctx = *DAG.getContext();
6324 Ctx.emitError(CS.getInstruction(),
6325 "Don't know how to handle indirect register inputs yet "
6326 "for constraint '" + Twine(OpInfo.ConstraintCode) + "'");
6327 break;
6328 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006329
6330 // Copy the input into the appropriate registers.
Chris Lattnerfcd70902012-01-03 23:51:01 +00006331 if (OpInfo.AssignedRegs.Regs.empty()) {
6332 LLVMContext &Ctx = *DAG.getContext();
6333 Ctx.emitError(CS.getInstruction(),
6334 "couldn't allocate input reg for constraint '" +
6335 Twine(OpInfo.ConstraintCode) + "'");
6336 break;
6337 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006338
Dale Johannesen66978ee2009-01-31 02:22:37 +00006339 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
Bill Wendlingf18eb582012-09-26 06:16:18 +00006340 Chain, &Flag, CS.getInstruction());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006341
Chris Lattnerdecc2672010-04-07 05:20:54 +00006342 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
Bill Wendling46ada192010-03-02 01:55:18 +00006343 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006344 break;
6345 }
6346 case InlineAsm::isClobber: {
6347 // Add the clobbered value to the operand list, so that the register
6348 // allocator is aware that the physreg got clobbered.
6349 if (!OpInfo.AssignedRegs.Regs.empty())
Jakob Stoklund Olesenf792fa92011-06-27 04:08:33 +00006350 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
Bill Wendling46ada192010-03-02 01:55:18 +00006351 false, 0, DAG,
Bill Wendling651ad132009-12-22 01:25:10 +00006352 AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006353 break;
6354 }
6355 }
6356 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006357
Chris Lattnerdecc2672010-04-07 05:20:54 +00006358 // Finish up input operands. Set the input chain and add the flag last.
Dale Johannesenf1e309e2010-07-02 20:16:09 +00006359 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006360 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006361
Dale Johannesen66978ee2009-01-31 02:22:37 +00006362 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +00006363 DAG.getVTList(MVT::Other, MVT::Glue),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006364 &AsmNodeOperands[0], AsmNodeOperands.size());
6365 Flag = Chain.getValue(1);
6366
6367 // If this asm returns a register value, copy the result from that register
6368 // and set it as the value of the call.
6369 if (!RetValRegs.Regs.empty()) {
Dan Gohman7451d3e2010-05-29 17:03:36 +00006370 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(),
Bill Wendling12931302012-09-26 04:04:19 +00006371 Chain, &Flag, CS.getInstruction());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006372
Chris Lattner2a0b96c2008-10-18 18:49:30 +00006373 // FIXME: Why don't we do this for inline asms with MRVs?
6374 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
Owen Andersone50ed302009-08-10 22:56:29 +00006375 EVT ResultType = TLI.getValueType(CS.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006376
Chris Lattner2a0b96c2008-10-18 18:49:30 +00006377 // If any of the results of the inline asm is a vector, it may have the
6378 // wrong width/num elts. This can happen for register classes that can
6379 // contain multiple different value types. The preg or vreg allocated may
6380 // not have the same VT as was expected. Convert it to the right type
6381 // with bit_convert.
6382 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
Wesley Peckbf17cfa2010-11-23 03:31:01 +00006383 Val = DAG.getNode(ISD::BITCAST, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00006384 ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00006385
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006386 } else if (ResultType != Val.getValueType() &&
Chris Lattner2a0b96c2008-10-18 18:49:30 +00006387 ResultType.isInteger() && Val.getValueType().isInteger()) {
6388 // If a result value was tied to an input value, the computed result may
6389 // have a wider width than the expected result. Extract the relevant
6390 // portion.
Dale Johannesen66978ee2009-01-31 02:22:37 +00006391 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00006392 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006393
Chris Lattner2a0b96c2008-10-18 18:49:30 +00006394 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00006395 }
Dan Gohman95915732008-10-18 01:03:45 +00006396
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006397 setValue(CS.getInstruction(), Val);
Dale Johannesenec65a7d2009-04-14 00:56:56 +00006398 // Don't need to use this as a chain in this case.
6399 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6400 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006401 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006402
Dan Gohman46510a72010-04-15 01:51:59 +00006403 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006404
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006405 // Process indirect outputs, first output all of the flagged copies out of
6406 // physregs.
6407 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6408 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Dan Gohman46510a72010-04-15 01:51:59 +00006409 const Value *Ptr = IndirectStoresToEmit[i].second;
Dan Gohman7451d3e2010-05-29 17:03:36 +00006410 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(),
Bill Wendling12931302012-09-26 04:04:19 +00006411 Chain, &Flag, IA);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006412 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6413 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006414
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006415 // Emit the non-flagged stores from the physregs.
6416 SmallVector<SDValue, 8> OutChains;
Bill Wendling651ad132009-12-22 01:25:10 +00006417 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6418 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
6419 StoresToEmit[i].first,
6420 getValue(StoresToEmit[i].second),
Chris Lattner84bd98a2010-09-21 18:58:22 +00006421 MachinePointerInfo(StoresToEmit[i].second),
David Greene1e559442010-02-15 17:00:31 +00006422 false, false, 0);
Bill Wendling651ad132009-12-22 01:25:10 +00006423 OutChains.push_back(Val);
Bill Wendling651ad132009-12-22 01:25:10 +00006424 }
6425
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006426 if (!OutChains.empty())
Owen Anderson825b72b2009-08-11 20:47:22 +00006427 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006428 &OutChains[0], OutChains.size());
Bill Wendling651ad132009-12-22 01:25:10 +00006429
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006430 DAG.setRoot(Chain);
6431}
6432
Dan Gohman46510a72010-04-15 01:51:59 +00006433void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
Bill Wendlingc1d3c942009-12-23 00:44:51 +00006434 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
6435 MVT::Other, getRoot(),
Gabor Greif0635f352010-06-25 09:38:13 +00006436 getValue(I.getArgOperand(0)),
6437 DAG.getSrcValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006438}
6439
Dan Gohman46510a72010-04-15 01:51:59 +00006440void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
Micah Villmow3574eca2012-10-08 16:38:25 +00006441 const DataLayout &TD = *TLI.getDataLayout();
Dale Johannesena04b7572009-02-03 23:04:43 +00006442 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
6443 getRoot(), getValue(I.getOperand(0)),
Rafael Espindolacbeeae22010-07-11 04:01:49 +00006444 DAG.getSrcValue(I.getOperand(0)),
Rafael Espindola9d544d02010-07-12 18:11:17 +00006445 TD.getABITypeAlignment(I.getType()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006446 setValue(&I, V);
6447 DAG.setRoot(V.getValue(1));
6448}
6449
Dan Gohman46510a72010-04-15 01:51:59 +00006450void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
Bill Wendlingc1d3c942009-12-23 00:44:51 +00006451 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
6452 MVT::Other, getRoot(),
Gabor Greif0635f352010-06-25 09:38:13 +00006453 getValue(I.getArgOperand(0)),
6454 DAG.getSrcValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006455}
6456
Dan Gohman46510a72010-04-15 01:51:59 +00006457void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
Bill Wendlingc1d3c942009-12-23 00:44:51 +00006458 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
6459 MVT::Other, getRoot(),
Gabor Greif0635f352010-06-25 09:38:13 +00006460 getValue(I.getArgOperand(0)),
6461 getValue(I.getArgOperand(1)),
6462 DAG.getSrcValue(I.getArgOperand(0)),
6463 DAG.getSrcValue(I.getArgOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006464}
6465
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006466/// TargetLowering::LowerCallTo - This is the default LowerCallTo
Dan Gohman98ca4f22009-08-05 01:29:28 +00006467/// implementation, which just calls LowerCall.
6468/// FIXME: When all targets are
6469/// migrated to using LowerCall, this hook should be integrated into SDISel.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006470std::pair<SDValue, SDValue>
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006471TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006472 // Handle all of the outgoing arguments.
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006473 CLI.Outs.clear();
6474 CLI.OutVals.clear();
6475 ArgListTy &Args = CLI.Args;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006476 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Owen Andersone50ed302009-08-10 22:56:29 +00006477 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006478 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
6479 for (unsigned Value = 0, NumValues = ValueVTs.size();
6480 Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00006481 EVT VT = ValueVTs[Value];
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006482 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
Chris Lattner2a0b96c2008-10-18 18:49:30 +00006483 SDValue Op = SDValue(Args[i].Node.getNode(),
6484 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006485 ISD::ArgFlagsTy Flags;
6486 unsigned OriginalAlignment =
Micah Villmow3574eca2012-10-08 16:38:25 +00006487 getDataLayout()->getABITypeAlignment(ArgTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006488
6489 if (Args[i].isZExt)
6490 Flags.setZExt();
6491 if (Args[i].isSExt)
6492 Flags.setSExt();
6493 if (Args[i].isInReg)
6494 Flags.setInReg();
6495 if (Args[i].isSRet)
6496 Flags.setSRet();
6497 if (Args[i].isByVal) {
6498 Flags.setByVal();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00006499 PointerType *Ty = cast<PointerType>(Args[i].Ty);
6500 Type *ElementTy = Ty->getElementType();
Micah Villmow3574eca2012-10-08 16:38:25 +00006501 Flags.setByValSize(getDataLayout()->getTypeAllocSize(ElementTy));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006502 // For ByVal, alignment should come from FE. BE will guess if this
6503 // info is not there but there are cases it cannot get right.
Chris Lattner9db20f32011-05-22 23:23:02 +00006504 unsigned FrameAlign;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006505 if (Args[i].Alignment)
6506 FrameAlign = Args[i].Alignment;
Chris Lattner9db20f32011-05-22 23:23:02 +00006507 else
6508 FrameAlign = getByValTypeAlignment(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006509 Flags.setByValAlign(FrameAlign);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006510 }
6511 if (Args[i].isNest)
6512 Flags.setNest();
6513 Flags.setOrigAlign(OriginalAlignment);
6514
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006515 EVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
6516 unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006517 SmallVector<SDValue, 4> Parts(NumParts);
6518 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
6519
6520 if (Args[i].isSExt)
6521 ExtendKind = ISD::SIGN_EXTEND;
6522 else if (Args[i].isZExt)
6523 ExtendKind = ISD::ZERO_EXTEND;
6524
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006525 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts,
Bill Wendlingf18eb582012-09-26 06:16:18 +00006526 PartVT, CLI.CS ? CLI.CS->getInstruction() : 0, ExtendKind);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006527
Dan Gohman98ca4f22009-08-05 01:29:28 +00006528 for (unsigned j = 0; j != NumParts; ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006529 // if it isn't first piece, alignment must be 1
Dan Gohmanc9403652010-07-07 15:54:55 +00006530 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(),
Manman Ren0a1544d2012-11-01 23:49:58 +00006531 i < CLI.NumFixedArgs,
6532 i, j*Parts[j].getValueType().getStoreSize());
Dan Gohman98ca4f22009-08-05 01:29:28 +00006533 if (NumParts > 1 && j == 0)
6534 MyFlags.Flags.setSplit();
6535 else if (j != 0)
6536 MyFlags.Flags.setOrigAlign(1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006537
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006538 CLI.Outs.push_back(MyFlags);
6539 CLI.OutVals.push_back(Parts[j]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006540 }
6541 }
6542 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006543
Dan Gohman98ca4f22009-08-05 01:29:28 +00006544 // Handle the incoming return values from the call.
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006545 CLI.Ins.clear();
Owen Andersone50ed302009-08-10 22:56:29 +00006546 SmallVector<EVT, 4> RetTys;
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006547 ComputeValueVTs(*this, CLI.RetTy, RetTys);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006548 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Owen Andersone50ed302009-08-10 22:56:29 +00006549 EVT VT = RetTys[I];
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006550 EVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
6551 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006552 for (unsigned i = 0; i != NumRegs; ++i) {
6553 ISD::InputArg MyFlags;
Duncan Sands1440e8b2010-11-03 11:35:31 +00006554 MyFlags.VT = RegisterVT.getSimpleVT();
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006555 MyFlags.Used = CLI.IsReturnValueUsed;
6556 if (CLI.RetSExt)
Dan Gohman98ca4f22009-08-05 01:29:28 +00006557 MyFlags.Flags.setSExt();
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006558 if (CLI.RetZExt)
Dan Gohman98ca4f22009-08-05 01:29:28 +00006559 MyFlags.Flags.setZExt();
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006560 if (CLI.IsInReg)
Dan Gohman98ca4f22009-08-05 01:29:28 +00006561 MyFlags.Flags.setInReg();
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006562 CLI.Ins.push_back(MyFlags);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006563 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006564 }
6565
Dan Gohman98ca4f22009-08-05 01:29:28 +00006566 SmallVector<SDValue, 4> InVals;
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006567 CLI.Chain = LowerCall(CLI, InVals);
Dan Gohman5e866062009-08-06 15:37:27 +00006568
6569 // Verify that the target's LowerCall behaved as expected.
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006570 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00006571 "LowerCall didn't return a valid chain!");
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006572 assert((!CLI.IsTailCall || InVals.empty()) &&
Dan Gohman5e866062009-08-06 15:37:27 +00006573 "LowerCall emitted a return value for a tail call!");
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006574 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
Dan Gohman5e866062009-08-06 15:37:27 +00006575 "LowerCall didn't emit the correct number of values!");
Dan Gohman98ca4f22009-08-05 01:29:28 +00006576
6577 // For a tail call, the return value is merely live-out and there aren't
6578 // any nodes in the DAG representing it. Return a special value to
6579 // indicate that a tail call has been emitted and no more Instructions
6580 // should be processed in the current block.
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006581 if (CLI.IsTailCall) {
6582 CLI.DAG.setRoot(CLI.Chain);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006583 return std::make_pair(SDValue(), SDValue());
6584 }
6585
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006586 DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
Evan Chengaf1871f2010-03-11 19:38:18 +00006587 assert(InVals[i].getNode() &&
6588 "LowerCall emitted a null value!");
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006589 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
Evan Chengaf1871f2010-03-11 19:38:18 +00006590 "LowerCall emitted a value with the wrong type!");
6591 });
6592
Dan Gohman98ca4f22009-08-05 01:29:28 +00006593 // Collect the legal value parts into potentially illegal values
6594 // that correspond to the original function's return values.
6595 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006596 if (CLI.RetSExt)
Dan Gohman98ca4f22009-08-05 01:29:28 +00006597 AssertOp = ISD::AssertSext;
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006598 else if (CLI.RetZExt)
Dan Gohman98ca4f22009-08-05 01:29:28 +00006599 AssertOp = ISD::AssertZext;
6600 SmallVector<SDValue, 4> ReturnValues;
6601 unsigned CurReg = 0;
6602 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Owen Andersone50ed302009-08-10 22:56:29 +00006603 EVT VT = RetTys[I];
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006604 EVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
6605 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006606
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006607 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
Bill Wendling12931302012-09-26 04:04:19 +00006608 NumRegs, RegisterVT, VT, NULL,
Bill Wendling4533cac2010-01-28 21:51:40 +00006609 AssertOp));
Dan Gohman98ca4f22009-08-05 01:29:28 +00006610 CurReg += NumRegs;
6611 }
6612
6613 // For a function returning void, there is no return value. We can't create
6614 // such a node, so we just return a null return value in that case. In
Chris Lattner7a2bdde2011-04-15 05:18:47 +00006615 // that case, nothing will actually look at the value.
Dan Gohman98ca4f22009-08-05 01:29:28 +00006616 if (ReturnValues.empty())
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006617 return std::make_pair(SDValue(), CLI.Chain);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006618
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006619 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
6620 CLI.DAG.getVTList(&RetTys[0], RetTys.size()),
Dan Gohman98ca4f22009-08-05 01:29:28 +00006621 &ReturnValues[0], ReturnValues.size());
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006622 return std::make_pair(Res, CLI.Chain);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006623}
6624
Duncan Sands9fbc7e22009-01-21 09:00:29 +00006625void TargetLowering::LowerOperationWrapper(SDNode *N,
6626 SmallVectorImpl<SDValue> &Results,
Dan Gohmand858e902010-04-17 15:26:15 +00006627 SelectionDAG &DAG) const {
Duncan Sands9fbc7e22009-01-21 09:00:29 +00006628 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptabb326bb2009-01-21 04:48:39 +00006629 if (Res.getNode())
6630 Results.push_back(Res);
6631}
6632
Dan Gohmand858e902010-04-17 15:26:15 +00006633SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
Torok Edwinc23197a2009-07-14 16:55:14 +00006634 llvm_unreachable("LowerOperation not implemented for this target!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006635}
6636
Dan Gohman46510a72010-04-15 01:51:59 +00006637void
6638SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
Dan Gohman28a17352010-07-01 01:59:43 +00006639 SDValue Op = getNonRegisterValue(V);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006640 assert((Op.getOpcode() != ISD::CopyFromReg ||
6641 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
6642 "Copy from a reg to the same reg!");
6643 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
6644
Owen Anderson23b9b192009-08-12 00:36:31 +00006645 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006646 SDValue Chain = DAG.getEntryNode();
Bill Wendlingf18eb582012-09-26 06:16:18 +00006647 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0, V);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006648 PendingExports.push_back(Chain);
6649}
6650
6651#include "llvm/CodeGen/SelectionDAGISel.h"
6652
Eli Friedman23d32432011-05-05 16:53:34 +00006653/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
6654/// entry block, return true. This includes arguments used by switches, since
6655/// the switch may expand into multiple basic blocks.
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006656static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
Eli Friedman23d32432011-05-05 16:53:34 +00006657 // With FastISel active, we may be splitting blocks, so force creation
6658 // of virtual registers for all non-dead arguments.
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006659 if (FastISel)
Eli Friedman23d32432011-05-05 16:53:34 +00006660 return A->use_empty();
6661
6662 const BasicBlock *Entry = A->getParent()->begin();
6663 for (Value::const_use_iterator UI = A->use_begin(), E = A->use_end();
6664 UI != E; ++UI) {
6665 const User *U = *UI;
6666 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
6667 return false; // Use not in entry block.
6668 }
6669 return true;
6670}
6671
Dan Gohman46510a72010-04-15 01:51:59 +00006672void SelectionDAGISel::LowerArguments(const BasicBlock *LLVMBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006673 // If this is the entry block, emit arguments.
Dan Gohman46510a72010-04-15 01:51:59 +00006674 const Function &F = *LLVMBB->getParent();
Dan Gohman2048b852009-11-23 18:04:58 +00006675 SelectionDAG &DAG = SDB->DAG;
Dan Gohman2048b852009-11-23 18:04:58 +00006676 DebugLoc dl = SDB->getCurDebugLoc();
Micah Villmow3574eca2012-10-08 16:38:25 +00006677 const DataLayout *TD = TLI.getDataLayout();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006678 SmallVector<ISD::InputArg, 16> Ins;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006679
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +00006680 // Check whether the function can return without sret-demotion.
Dan Gohman84023e02010-07-10 09:00:22 +00006681 SmallVector<ISD::OutputArg, 4> Outs;
6682 GetReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
6683 Outs, TLI);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006684
Dan Gohman7451d3e2010-05-29 17:03:36 +00006685 if (!FuncInfo->CanLowerReturn) {
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006686 // Put in an sret pointer parameter before all the other parameters.
6687 SmallVector<EVT, 1> ValueVTs;
6688 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6689
6690 // NOTE: Assuming that a pointer will never break down to more than one VT
6691 // or one register.
6692 ISD::ArgFlagsTy Flags;
6693 Flags.setSRet();
Dan Gohmanf81eca02010-04-22 20:46:50 +00006694 EVT RegisterVT = TLI.getRegisterType(*DAG.getContext(), ValueVTs[0]);
Stepan Dyatkovskiy661afe72012-10-10 11:37:36 +00006695 ISD::InputArg RetArg(Flags, RegisterVT, true, 0, 0);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006696 Ins.push_back(RetArg);
6697 }
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +00006698
Dan Gohman98ca4f22009-08-05 01:29:28 +00006699 // Set up the incoming argument description vector.
Dan Gohman98ca4f22009-08-05 01:29:28 +00006700 unsigned Idx = 1;
Dan Gohman46510a72010-04-15 01:51:59 +00006701 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
Dan Gohman98ca4f22009-08-05 01:29:28 +00006702 I != E; ++I, ++Idx) {
Owen Andersone50ed302009-08-10 22:56:29 +00006703 SmallVector<EVT, 4> ValueVTs;
Dan Gohman98ca4f22009-08-05 01:29:28 +00006704 ComputeValueVTs(TLI, I->getType(), ValueVTs);
6705 bool isArgValueUsed = !I->use_empty();
6706 for (unsigned Value = 0, NumValues = ValueVTs.size();
6707 Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00006708 EVT VT = ValueVTs[Value];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00006709 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Dan Gohman98ca4f22009-08-05 01:29:28 +00006710 ISD::ArgFlagsTy Flags;
6711 unsigned OriginalAlignment =
6712 TD->getABITypeAlignment(ArgTy);
6713
Bill Wendling67658342012-10-09 07:45:08 +00006714 if (F.getParamAttributes(Idx).hasAttribute(Attributes::ZExt))
Dan Gohman98ca4f22009-08-05 01:29:28 +00006715 Flags.setZExt();
Bill Wendling67658342012-10-09 07:45:08 +00006716 if (F.getParamAttributes(Idx).hasAttribute(Attributes::SExt))
Dan Gohman98ca4f22009-08-05 01:29:28 +00006717 Flags.setSExt();
Bill Wendling67658342012-10-09 07:45:08 +00006718 if (F.getParamAttributes(Idx).hasAttribute(Attributes::InReg))
Dan Gohman98ca4f22009-08-05 01:29:28 +00006719 Flags.setInReg();
Bill Wendling67658342012-10-09 07:45:08 +00006720 if (F.getParamAttributes(Idx).hasAttribute(Attributes::StructRet))
Dan Gohman98ca4f22009-08-05 01:29:28 +00006721 Flags.setSRet();
Bill Wendling67658342012-10-09 07:45:08 +00006722 if (F.getParamAttributes(Idx).hasAttribute(Attributes::ByVal)) {
Dan Gohman98ca4f22009-08-05 01:29:28 +00006723 Flags.setByVal();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00006724 PointerType *Ty = cast<PointerType>(I->getType());
6725 Type *ElementTy = Ty->getElementType();
Chris Lattner9db20f32011-05-22 23:23:02 +00006726 Flags.setByValSize(TD->getTypeAllocSize(ElementTy));
Dan Gohman98ca4f22009-08-05 01:29:28 +00006727 // For ByVal, alignment should be passed from FE. BE will guess if
6728 // this info is not there but there are cases it cannot get right.
Chris Lattner9db20f32011-05-22 23:23:02 +00006729 unsigned FrameAlign;
Dan Gohman98ca4f22009-08-05 01:29:28 +00006730 if (F.getParamAlignment(Idx))
6731 FrameAlign = F.getParamAlignment(Idx);
Chris Lattner9db20f32011-05-22 23:23:02 +00006732 else
6733 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006734 Flags.setByValAlign(FrameAlign);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006735 }
Bill Wendling67658342012-10-09 07:45:08 +00006736 if (F.getParamAttributes(Idx).hasAttribute(Attributes::Nest))
Dan Gohman98ca4f22009-08-05 01:29:28 +00006737 Flags.setNest();
6738 Flags.setOrigAlign(OriginalAlignment);
6739
Owen Anderson23b9b192009-08-12 00:36:31 +00006740 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6741 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006742 for (unsigned i = 0; i != NumRegs; ++i) {
Stepan Dyatkovskiy661afe72012-10-10 11:37:36 +00006743 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed,
6744 Idx-1, i*RegisterVT.getStoreSize());
Dan Gohman98ca4f22009-08-05 01:29:28 +00006745 if (NumRegs > 1 && i == 0)
6746 MyFlags.Flags.setSplit();
6747 // if it isn't first piece, alignment must be 1
6748 else if (i > 0)
6749 MyFlags.Flags.setOrigAlign(1);
6750 Ins.push_back(MyFlags);
6751 }
6752 }
6753 }
6754
6755 // Call the target to set up the argument values.
6756 SmallVector<SDValue, 8> InVals;
6757 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
6758 F.isVarArg(), Ins,
6759 dl, DAG, InVals);
Dan Gohman5e866062009-08-06 15:37:27 +00006760
6761 // Verify that the target's LowerFormalArguments behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +00006762 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00006763 "LowerFormalArguments didn't return a valid chain!");
6764 assert(InVals.size() == Ins.size() &&
6765 "LowerFormalArguments didn't emit the correct number of values!");
Bill Wendling3ea58b62009-12-22 21:35:02 +00006766 DEBUG({
6767 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6768 assert(InVals[i].getNode() &&
6769 "LowerFormalArguments emitted a null value!");
Duncan Sands1440e8b2010-11-03 11:35:31 +00006770 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
Bill Wendling3ea58b62009-12-22 21:35:02 +00006771 "LowerFormalArguments emitted a value with the wrong type!");
6772 }
6773 });
Bill Wendling3ea3c242009-12-22 02:10:19 +00006774
Dan Gohman5e866062009-08-06 15:37:27 +00006775 // Update the DAG with the new chain value resulting from argument lowering.
Dan Gohman98ca4f22009-08-05 01:29:28 +00006776 DAG.setRoot(NewRoot);
6777
6778 // Set up the argument values.
6779 unsigned i = 0;
6780 Idx = 1;
Dan Gohman7451d3e2010-05-29 17:03:36 +00006781 if (!FuncInfo->CanLowerReturn) {
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006782 // Create a virtual register for the sret pointer, and put in a copy
6783 // from the sret argument into it.
6784 SmallVector<EVT, 1> ValueVTs;
6785 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6786 EVT VT = ValueVTs[0];
6787 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6788 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Bill Wendling46ada192010-03-02 01:55:18 +00006789 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
Bill Wendling12931302012-09-26 04:04:19 +00006790 RegVT, VT, NULL, AssertOp);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006791
Dan Gohman2048b852009-11-23 18:04:58 +00006792 MachineFunction& MF = SDB->DAG.getMachineFunction();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006793 MachineRegisterInfo& RegInfo = MF.getRegInfo();
6794 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
Dan Gohman7451d3e2010-05-29 17:03:36 +00006795 FuncInfo->DemoteRegister = SRetReg;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00006796 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(),
6797 SRetReg, ArgValue);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006798 DAG.setRoot(NewRoot);
Bill Wendling3ea3c242009-12-22 02:10:19 +00006799
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006800 // i indexes lowered arguments. Bump it past the hidden sret argument.
6801 // Idx indexes LLVM arguments. Don't touch it.
6802 ++i;
6803 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006804
Dan Gohman46510a72010-04-15 01:51:59 +00006805 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
Dan Gohman98ca4f22009-08-05 01:29:28 +00006806 ++I, ++Idx) {
6807 SmallVector<SDValue, 4> ArgValues;
Owen Andersone50ed302009-08-10 22:56:29 +00006808 SmallVector<EVT, 4> ValueVTs;
Dan Gohman98ca4f22009-08-05 01:29:28 +00006809 ComputeValueVTs(TLI, I->getType(), ValueVTs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006810 unsigned NumValues = ValueVTs.size();
Devang Patel9126c0d2010-06-01 19:59:01 +00006811
6812 // If this argument is unused then remember its value. It is used to generate
6813 // debugging information.
6814 if (I->use_empty() && NumValues)
6815 SDB->setUnusedArgValue(I, InVals[i]);
6816
Eli Friedman23d32432011-05-05 16:53:34 +00006817 for (unsigned Val = 0; Val != NumValues; ++Val) {
6818 EVT VT = ValueVTs[Val];
Owen Anderson23b9b192009-08-12 00:36:31 +00006819 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6820 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006821
6822 if (!I->use_empty()) {
6823 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Bill Wendling67658342012-10-09 07:45:08 +00006824 if (F.getParamAttributes(Idx).hasAttribute(Attributes::SExt))
Dan Gohman98ca4f22009-08-05 01:29:28 +00006825 AssertOp = ISD::AssertSext;
Bill Wendling67658342012-10-09 07:45:08 +00006826 else if (F.getParamAttributes(Idx).hasAttribute(Attributes::ZExt))
Dan Gohman98ca4f22009-08-05 01:29:28 +00006827 AssertOp = ISD::AssertZext;
6828
Bill Wendling46ada192010-03-02 01:55:18 +00006829 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
Bill Wendling3ea3c242009-12-22 02:10:19 +00006830 NumParts, PartVT, VT,
Bill Wendling12931302012-09-26 04:04:19 +00006831 NULL, AssertOp));
Dan Gohman98ca4f22009-08-05 01:29:28 +00006832 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006833
Dan Gohman98ca4f22009-08-05 01:29:28 +00006834 i += NumParts;
6835 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006836
Eli Friedman23d32432011-05-05 16:53:34 +00006837 // We don't need to do anything else for unused arguments.
6838 if (ArgValues.empty())
6839 continue;
6840
Devang Patel9aee3352011-09-08 22:59:09 +00006841 // Note down frame index.
6842 if (FrameIndexSDNode *FI =
Bill Wendling96cb1122012-07-19 00:04:14 +00006843 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
Devang Patel9aee3352011-09-08 22:59:09 +00006844 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
Devang Patel0b48ead2010-08-31 22:22:42 +00006845
Eli Friedman23d32432011-05-05 16:53:34 +00006846 SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues,
6847 SDB->getCurDebugLoc());
Devang Patel9aee3352011-09-08 22:59:09 +00006848
Eli Friedman23d32432011-05-05 16:53:34 +00006849 SDB->setValue(I, Res);
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006850 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
Devang Patel9aee3352011-09-08 22:59:09 +00006851 if (LoadSDNode *LNode =
6852 dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
6853 if (FrameIndexSDNode *FI =
6854 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6855 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
6856 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006857
Eli Friedman23d32432011-05-05 16:53:34 +00006858 // If this argument is live outside of the entry block, insert a copy from
6859 // wherever we got it to the vreg that other BB's will reference it as.
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006860 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
Eli Friedman23d32432011-05-05 16:53:34 +00006861 // If we can, though, try to skip creating an unnecessary vreg.
6862 // FIXME: This isn't very clean... it would be nice to make this more
Eli Friedman7f33d672011-05-10 21:50:58 +00006863 // general. It's also subtly incompatible with the hacks FastISel
6864 // uses with vregs.
Eli Friedman23d32432011-05-05 16:53:34 +00006865 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
6866 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
6867 FuncInfo->ValueMap[I] = Reg;
6868 continue;
6869 }
6870 }
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006871 if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
Eli Friedman23d32432011-05-05 16:53:34 +00006872 FuncInfo->InitializeRegForValue(I);
Dan Gohman2048b852009-11-23 18:04:58 +00006873 SDB->CopyToExportRegsIfNeeded(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006874 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006875 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006876
Dan Gohman98ca4f22009-08-05 01:29:28 +00006877 assert(i == InVals.size() && "Argument register count mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006878
6879 // Finally, if the target has anything special to do, allow it to do so.
6880 // FIXME: this should insert code into the DAG!
Dan Gohman64652652010-04-14 20:17:22 +00006881 EmitFunctionEntryCode();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006882}
6883
6884/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
6885/// ensure constants are generated when needed. Remember the virtual registers
6886/// that need to be added to the Machine PHI nodes as input. We cannot just
6887/// directly add them, because expansion might result in multiple MBB's for one
6888/// BB. As such, the start of the BB might correspond to a different MBB than
6889/// the end.
6890///
6891void
Dan Gohmanf81eca02010-04-22 20:46:50 +00006892SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
Dan Gohman46510a72010-04-15 01:51:59 +00006893 const TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006894
6895 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6896
6897 // Check successor nodes' PHI nodes that expect a constant to be available
6898 // from this block.
6899 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
Dan Gohman46510a72010-04-15 01:51:59 +00006900 const BasicBlock *SuccBB = TI->getSuccessor(succ);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006901 if (!isa<PHINode>(SuccBB->begin())) continue;
Dan Gohmanf81eca02010-04-22 20:46:50 +00006902 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006903
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006904 // If this terminator has multiple identical successors (common for
6905 // switches), only handle each succ once.
6906 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006907
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006908 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006909
6910 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6911 // nodes and Machine PHI nodes, but the incoming operands have not been
6912 // emitted yet.
Dan Gohman46510a72010-04-15 01:51:59 +00006913 for (BasicBlock::const_iterator I = SuccBB->begin();
6914 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006915 // Ignore dead phi's.
6916 if (PN->use_empty()) continue;
6917
Rafael Espindola3fa82832011-05-13 15:18:06 +00006918 // Skip empty types
6919 if (PN->getType()->isEmptyTy())
6920 continue;
6921
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006922 unsigned Reg;
Dan Gohman46510a72010-04-15 01:51:59 +00006923 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006924
Dan Gohman46510a72010-04-15 01:51:59 +00006925 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
Dan Gohmanf81eca02010-04-22 20:46:50 +00006926 unsigned &RegOut = ConstantsOut[C];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006927 if (RegOut == 0) {
Dan Gohman89496d02010-07-02 00:10:16 +00006928 RegOut = FuncInfo.CreateRegs(C->getType());
Dan Gohmanf81eca02010-04-22 20:46:50 +00006929 CopyValueToVirtualRegister(C, RegOut);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006930 }
6931 Reg = RegOut;
6932 } else {
Dan Gohmanc25ad632010-07-01 01:33:21 +00006933 DenseMap<const Value *, unsigned>::iterator I =
6934 FuncInfo.ValueMap.find(PHIOp);
6935 if (I != FuncInfo.ValueMap.end())
6936 Reg = I->second;
6937 else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006938 assert(isa<AllocaInst>(PHIOp) &&
Dan Gohmanf81eca02010-04-22 20:46:50 +00006939 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006940 "Didn't codegen value into a register!??");
Dan Gohman89496d02010-07-02 00:10:16 +00006941 Reg = FuncInfo.CreateRegs(PHIOp->getType());
Dan Gohmanf81eca02010-04-22 20:46:50 +00006942 CopyValueToVirtualRegister(PHIOp, Reg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006943 }
6944 }
6945
6946 // Remember that this register needs to added to the machine PHI node as
6947 // the input for this MBB.
Owen Andersone50ed302009-08-10 22:56:29 +00006948 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006949 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6950 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
Owen Andersone50ed302009-08-10 22:56:29 +00006951 EVT VT = ValueVTs[vti];
Dan Gohmanf81eca02010-04-22 20:46:50 +00006952 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006953 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Dan Gohmanf81eca02010-04-22 20:46:50 +00006954 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006955 Reg += NumRegisters;
6956 }
6957 }
6958 }
Dan Gohmanf81eca02010-04-22 20:46:50 +00006959 ConstantsOut.clear();
Dan Gohman3df24e62008-09-03 23:12:08 +00006960}