blob: 56e774c2c7b337d251a2496d6588cbd05db23205 [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
Craig Topper538cd482012-11-24 18:52:06 +00003690/// expandExp - Lower an exp intrinsic. Handles the special sequences for
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003691/// limited-precision mode.
Craig Topper538cd482012-11-24 18:52:06 +00003692static SDValue expandExp(DebugLoc dl, SDValue Op, SelectionDAG &DAG,
3693 const TargetLowering &TLI) {
3694 if (Op.getValueType() == MVT::f32 &&
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003695 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003696
3697 // Put the exponent in the right bit position for later addition to the
3698 // final result:
3699 //
3700 // #define LOG2OFe 1.4426950f
3701 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
Owen Anderson825b72b2009-08-11 20:47:22 +00003702 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003703 getF32Constant(DAG, 0x3fb8aa3b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003704 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003705
3706 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00003707 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3708 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003709
3710 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00003711 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003712 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendling856ff412009-12-22 00:12:37 +00003713
Craig Topperb3157722012-11-24 08:22:37 +00003714 SDValue TwoToFracPartOfX;
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003715 if (LimitFloatPrecision <= 6) {
3716 // For floating-point precision of 6:
3717 //
3718 // TwoToFractionalPartOfX =
3719 // 0.997535578f +
3720 // (0.735607626f + 0.252464424f * x) * x;
3721 //
3722 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003723 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003724 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00003725 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003726 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003727 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
Craig Topperb3157722012-11-24 08:22:37 +00003728 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3729 getF32Constant(DAG, 0x3f7f5e7e));
Craig Topper08ac4692012-11-16 20:01:39 +00003730 } else if (LimitFloatPrecision <= 12) {
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003731 // For floating-point precision of 12:
3732 //
3733 // TwoToFractionalPartOfX =
3734 // 0.999892986f +
3735 // (0.696457318f +
3736 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3737 //
3738 // 0.000107046256 error, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003739 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003740 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003741 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003742 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003743 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3744 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003745 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00003746 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topperb3157722012-11-24 08:22:37 +00003747 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3748 getF32Constant(DAG, 0x3f7ff8fd));
Craig Topper08ac4692012-11-16 20:01:39 +00003749 } else { // LimitFloatPrecision <= 18
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003750 // For floating-point precision of 18:
3751 //
3752 // TwoToFractionalPartOfX =
3753 // 0.999999982f +
3754 // (0.693148872f +
3755 // (0.240227044f +
3756 // (0.554906021e-1f +
3757 // (0.961591928e-2f +
3758 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3759 //
3760 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003761 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003762 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003763 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003764 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003765 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3766 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003767 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003768 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3769 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003770 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003771 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3772 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003773 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003774 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3775 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003776 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003777 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
Craig Topperb3157722012-11-24 08:22:37 +00003778 TwoToFracPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3779 getF32Constant(DAG, 0x3f800000));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003780 }
Craig Topperb3157722012-11-24 08:22:37 +00003781
3782 // Add the exponent into the result in integer domain.
3783 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, TwoToFracPartOfX);
Craig Topper538cd482012-11-24 18:52:06 +00003784 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
3785 DAG.getNode(ISD::ADD, dl, MVT::i32,
3786 t13, IntegerPartOfX));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003787 }
3788
Craig Topper538cd482012-11-24 18:52:06 +00003789 // No special expansion.
3790 return DAG.getNode(ISD::FEXP, dl, Op.getValueType(), Op);
Dale Johannesen59e577f2008-09-05 18:38:42 +00003791}
3792
Craig Topper5d1e0892012-11-23 18:38:31 +00003793/// expandLog - Lower a log intrinsic. Handles the special sequences for
Bill Wendling39150252008-09-09 20:39:27 +00003794/// limited-precision mode.
Craig Topper5d1e0892012-11-23 18:38:31 +00003795static SDValue expandLog(DebugLoc dl, SDValue Op, SelectionDAG &DAG,
3796 const TargetLowering &TLI) {
3797 if (Op.getValueType() == MVT::f32 &&
Bill Wendling39150252008-09-09 20:39:27 +00003798 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003799 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
Bill Wendling39150252008-09-09 20:39:27 +00003800
3801 // Scale the exponent by log(2) [0.69314718f].
Bill Wendling46ada192010-03-02 01:55:18 +00003802 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Owen Anderson825b72b2009-08-11 20:47:22 +00003803 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003804 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003805
3806 // Get the significand and build it into a floating-point number with
3807 // exponent of 1.
Bill Wendling46ada192010-03-02 01:55:18 +00003808 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling39150252008-09-09 20:39:27 +00003809
Craig Topperdf0ea8d2012-11-16 19:08:44 +00003810 SDValue LogOfMantissa;
Bill Wendling39150252008-09-09 20:39:27 +00003811 if (LimitFloatPrecision <= 6) {
3812 // For floating-point precision of 6:
3813 //
3814 // LogofMantissa =
3815 // -1.1609546f +
3816 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003817 //
Bill Wendling39150252008-09-09 20:39:27 +00003818 // error 0.0034276066, which is better than 8 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003819 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003820 getF32Constant(DAG, 0xbe74c456));
Owen Anderson825b72b2009-08-11 20:47:22 +00003821 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003822 getF32Constant(DAG, 0x3fb3a2b1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003823 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00003824 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3825 getF32Constant(DAG, 0x3f949a29));
Craig Topper08ac4692012-11-16 20:01:39 +00003826 } else if (LimitFloatPrecision <= 12) {
Bill Wendling39150252008-09-09 20:39:27 +00003827 // For floating-point precision of 12:
3828 //
3829 // LogOfMantissa =
3830 // -1.7417939f +
3831 // (2.8212026f +
3832 // (-1.4699568f +
3833 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3834 //
3835 // error 0.000061011436, which is 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003836 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003837 getF32Constant(DAG, 0xbd67b6d6));
Owen Anderson825b72b2009-08-11 20:47:22 +00003838 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003839 getF32Constant(DAG, 0x3ee4f4b8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003840 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3841 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003842 getF32Constant(DAG, 0x3fbc278b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003843 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3844 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003845 getF32Constant(DAG, 0x40348e95));
Owen Anderson825b72b2009-08-11 20:47:22 +00003846 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00003847 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3848 getF32Constant(DAG, 0x3fdef31a));
Craig Topper08ac4692012-11-16 20:01:39 +00003849 } else { // LimitFloatPrecision <= 18
Bill Wendling39150252008-09-09 20:39:27 +00003850 // For floating-point precision of 18:
3851 //
3852 // LogOfMantissa =
3853 // -2.1072184f +
3854 // (4.2372794f +
3855 // (-3.7029485f +
3856 // (2.2781945f +
3857 // (-0.87823314f +
3858 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3859 //
3860 // error 0.0000023660568, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003861 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003862 getF32Constant(DAG, 0xbc91e5ac));
Owen Anderson825b72b2009-08-11 20:47:22 +00003863 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003864 getF32Constant(DAG, 0x3e4350aa));
Owen Anderson825b72b2009-08-11 20:47:22 +00003865 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3866 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003867 getF32Constant(DAG, 0x3f60d3e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003868 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3869 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003870 getF32Constant(DAG, 0x4011cdf0));
Owen Anderson825b72b2009-08-11 20:47:22 +00003871 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3872 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003873 getF32Constant(DAG, 0x406cfd1c));
Owen Anderson825b72b2009-08-11 20:47:22 +00003874 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3875 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003876 getF32Constant(DAG, 0x408797cb));
Owen Anderson825b72b2009-08-11 20:47:22 +00003877 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00003878 LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3879 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003880 }
Craig Topperdf0ea8d2012-11-16 19:08:44 +00003881
Craig Topper5d1e0892012-11-23 18:38:31 +00003882 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003883 }
3884
Craig Topper5d1e0892012-11-23 18:38:31 +00003885 // No special expansion.
3886 return DAG.getNode(ISD::FLOG, dl, Op.getValueType(), Op);
Dale Johannesen59e577f2008-09-05 18:38:42 +00003887}
3888
Craig Topper5d1e0892012-11-23 18:38:31 +00003889/// expandLog2 - Lower a log2 intrinsic. Handles the special sequences for
Bill Wendling3eb59402008-09-09 00:28:24 +00003890/// limited-precision mode.
Craig Topper5d1e0892012-11-23 18:38:31 +00003891static SDValue expandLog2(DebugLoc dl, SDValue Op, SelectionDAG &DAG,
3892 const TargetLowering &TLI) {
3893 if (Op.getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003894 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003895 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003896
Bill Wendling39150252008-09-09 20:39:27 +00003897 // Get the exponent.
Bill Wendling46ada192010-03-02 01:55:18 +00003898 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
Bill Wendling856ff412009-12-22 00:12:37 +00003899
Bill Wendling3eb59402008-09-09 00:28:24 +00003900 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003901 // exponent of 1.
Bill Wendling46ada192010-03-02 01:55:18 +00003902 SDValue X = GetSignificand(DAG, Op1, dl);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003903
Bill Wendling3eb59402008-09-09 00:28:24 +00003904 // Different possible minimax approximations of significand in
3905 // floating-point for various degrees of accuracy over [1,2].
Craig Topperdf0ea8d2012-11-16 19:08:44 +00003906 SDValue Log2ofMantissa;
Bill Wendling3eb59402008-09-09 00:28:24 +00003907 if (LimitFloatPrecision <= 6) {
3908 // For floating-point precision of 6:
3909 //
3910 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3911 //
3912 // error 0.0049451742, which is more than 7 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003913 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003914 getF32Constant(DAG, 0xbeb08fe0));
Owen Anderson825b72b2009-08-11 20:47:22 +00003915 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003916 getF32Constant(DAG, 0x40019463));
Owen Anderson825b72b2009-08-11 20:47:22 +00003917 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00003918 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3919 getF32Constant(DAG, 0x3fd6633d));
Craig Topper08ac4692012-11-16 20:01:39 +00003920 } else if (LimitFloatPrecision <= 12) {
Bill Wendling3eb59402008-09-09 00:28:24 +00003921 // For floating-point precision of 12:
3922 //
3923 // Log2ofMantissa =
3924 // -2.51285454f +
3925 // (4.07009056f +
3926 // (-2.12067489f +
3927 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003928 //
Bill Wendling3eb59402008-09-09 00:28:24 +00003929 // error 0.0000876136000, which is better than 13 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003930 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003931 getF32Constant(DAG, 0xbda7262e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003932 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003933 getF32Constant(DAG, 0x3f25280b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003934 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3935 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003936 getF32Constant(DAG, 0x4007b923));
Owen Anderson825b72b2009-08-11 20:47:22 +00003937 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3938 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003939 getF32Constant(DAG, 0x40823e2f));
Owen Anderson825b72b2009-08-11 20:47:22 +00003940 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00003941 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3942 getF32Constant(DAG, 0x4020d29c));
Craig Topper08ac4692012-11-16 20:01:39 +00003943 } else { // LimitFloatPrecision <= 18
Bill Wendling3eb59402008-09-09 00:28:24 +00003944 // For floating-point precision of 18:
3945 //
3946 // Log2ofMantissa =
3947 // -3.0400495f +
3948 // (6.1129976f +
3949 // (-5.3420409f +
3950 // (3.2865683f +
3951 // (-1.2669343f +
3952 // (0.27515199f -
3953 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3954 //
3955 // error 0.0000018516, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003956 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003957 getF32Constant(DAG, 0xbcd2769e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003958 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003959 getF32Constant(DAG, 0x3e8ce0b9));
Owen Anderson825b72b2009-08-11 20:47:22 +00003960 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3961 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003962 getF32Constant(DAG, 0x3fa22ae7));
Owen Anderson825b72b2009-08-11 20:47:22 +00003963 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3964 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003965 getF32Constant(DAG, 0x40525723));
Owen Anderson825b72b2009-08-11 20:47:22 +00003966 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3967 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003968 getF32Constant(DAG, 0x40aaf200));
Owen Anderson825b72b2009-08-11 20:47:22 +00003969 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3970 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003971 getF32Constant(DAG, 0x40c39dad));
Owen Anderson825b72b2009-08-11 20:47:22 +00003972 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00003973 Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3974 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003975 }
Craig Topperdf0ea8d2012-11-16 19:08:44 +00003976
Craig Topper5d1e0892012-11-23 18:38:31 +00003977 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log2ofMantissa);
Dale Johannesen853244f2008-09-05 23:49:37 +00003978 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003979
Craig Topper5d1e0892012-11-23 18:38:31 +00003980 // No special expansion.
3981 return DAG.getNode(ISD::FLOG2, dl, Op.getValueType(), Op);
Dale Johannesen59e577f2008-09-05 18:38:42 +00003982}
3983
Craig Topper5d1e0892012-11-23 18:38:31 +00003984/// expandLog10 - Lower a log10 intrinsic. Handles the special sequences for
Bill Wendling3eb59402008-09-09 00:28:24 +00003985/// limited-precision mode.
Craig Topper5d1e0892012-11-23 18:38:31 +00003986static SDValue expandLog10(DebugLoc dl, SDValue Op, SelectionDAG &DAG,
3987 const TargetLowering &TLI) {
3988 if (Op.getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003989 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Wesley Peckbf17cfa2010-11-23 03:31:01 +00003990 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003991
Bill Wendling39150252008-09-09 20:39:27 +00003992 // Scale the exponent by log10(2) [0.30102999f].
Bill Wendling46ada192010-03-02 01:55:18 +00003993 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Owen Anderson825b72b2009-08-11 20:47:22 +00003994 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003995 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003996
3997 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003998 // exponent of 1.
Bill Wendling46ada192010-03-02 01:55:18 +00003999 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00004000
Craig Topperdf0ea8d2012-11-16 19:08:44 +00004001 SDValue Log10ofMantissa;
Bill Wendling3eb59402008-09-09 00:28:24 +00004002 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00004003 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004004 //
Bill Wendlingbd297bc2008-09-09 18:42:23 +00004005 // Log10ofMantissa =
4006 // -0.50419619f +
4007 // (0.60948995f - 0.10380950f * x) * x;
4008 //
4009 // error 0.0014886165, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004010 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004011 getF32Constant(DAG, 0xbdd49a13));
Owen Anderson825b72b2009-08-11 20:47:22 +00004012 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004013 getF32Constant(DAG, 0x3f1c0789));
Owen Anderson825b72b2009-08-11 20:47:22 +00004014 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00004015 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
4016 getF32Constant(DAG, 0x3f011300));
Craig Topper08ac4692012-11-16 20:01:39 +00004017 } else if (LimitFloatPrecision <= 12) {
Bill Wendling3eb59402008-09-09 00:28:24 +00004018 // For floating-point precision of 12:
4019 //
4020 // Log10ofMantissa =
4021 // -0.64831180f +
4022 // (0.91751397f +
4023 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
4024 //
4025 // error 0.00019228036, which is better than 12 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004026 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004027 getF32Constant(DAG, 0x3d431f31));
Owen Anderson825b72b2009-08-11 20:47:22 +00004028 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004029 getF32Constant(DAG, 0x3ea21fb2));
Owen Anderson825b72b2009-08-11 20:47:22 +00004030 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4031 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004032 getF32Constant(DAG, 0x3f6ae232));
Owen Anderson825b72b2009-08-11 20:47:22 +00004033 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00004034 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
4035 getF32Constant(DAG, 0x3f25f7c3));
Craig Topper08ac4692012-11-16 20:01:39 +00004036 } else { // LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00004037 // For floating-point precision of 18:
4038 //
4039 // Log10ofMantissa =
4040 // -0.84299375f +
4041 // (1.5327582f +
4042 // (-1.0688956f +
4043 // (0.49102474f +
4044 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
4045 //
4046 // error 0.0000037995730, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004047 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004048 getF32Constant(DAG, 0x3c5d51ce));
Owen Anderson825b72b2009-08-11 20:47:22 +00004049 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004050 getF32Constant(DAG, 0x3e00685a));
Owen Anderson825b72b2009-08-11 20:47:22 +00004051 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
4052 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004053 getF32Constant(DAG, 0x3efb6798));
Owen Anderson825b72b2009-08-11 20:47:22 +00004054 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4055 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004056 getF32Constant(DAG, 0x3f88d192));
Owen Anderson825b72b2009-08-11 20:47:22 +00004057 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4058 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004059 getF32Constant(DAG, 0x3fc4316c));
Owen Anderson825b72b2009-08-11 20:47:22 +00004060 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
Craig Topperdf0ea8d2012-11-16 19:08:44 +00004061 Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
4062 getF32Constant(DAG, 0x3f57ce70));
Bill Wendling3eb59402008-09-09 00:28:24 +00004063 }
Craig Topperdf0ea8d2012-11-16 19:08:44 +00004064
Craig Topper5d1e0892012-11-23 18:38:31 +00004065 return DAG.getNode(ISD::FADD, dl, MVT::f32, LogOfExponent, Log10ofMantissa);
Dale Johannesen852680a2008-09-05 21:27:19 +00004066 }
Bill Wendling3eb59402008-09-09 00:28:24 +00004067
Craig Topper5d1e0892012-11-23 18:38:31 +00004068 // No special expansion.
4069 return DAG.getNode(ISD::FLOG10, dl, Op.getValueType(), Op);
Dale Johannesen59e577f2008-09-05 18:38:42 +00004070}
4071
Craig Topper538cd482012-11-24 18:52:06 +00004072/// expandExp2 - Lower an exp2 intrinsic. Handles the special sequences for
Bill Wendlinge10c8142008-09-09 22:39:21 +00004073/// limited-precision mode.
Craig Topper538cd482012-11-24 18:52:06 +00004074static SDValue expandExp2(DebugLoc dl, SDValue Op, SelectionDAG &DAG,
4075 const TargetLowering &TLI) {
4076 if (Op.getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00004077 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Owen Anderson825b72b2009-08-11 20:47:22 +00004078 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
Bill Wendlinge10c8142008-09-09 22:39:21 +00004079
4080 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00004081 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4082 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
Bill Wendlinge10c8142008-09-09 22:39:21 +00004083
4084 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00004085 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00004086 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlinge10c8142008-09-09 22:39:21 +00004087
Craig Topperb3157722012-11-24 08:22:37 +00004088 SDValue TwoToFractionalPartOfX;
Bill Wendlinge10c8142008-09-09 22:39:21 +00004089 if (LimitFloatPrecision <= 6) {
4090 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004091 //
Bill Wendlinge10c8142008-09-09 22:39:21 +00004092 // TwoToFractionalPartOfX =
4093 // 0.997535578f +
4094 // (0.735607626f + 0.252464424f * x) * x;
4095 //
4096 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004097 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004098 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00004099 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004100 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00004101 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
Craig Topperb3157722012-11-24 08:22:37 +00004102 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4103 getF32Constant(DAG, 0x3f7f5e7e));
Craig Topper08ac4692012-11-16 20:01:39 +00004104 } else if (LimitFloatPrecision <= 12) {
Bill Wendlinge10c8142008-09-09 22:39:21 +00004105 // For floating-point precision of 12:
4106 //
4107 // TwoToFractionalPartOfX =
4108 // 0.999892986f +
4109 // (0.696457318f +
4110 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4111 //
4112 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004113 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004114 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00004115 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004116 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00004117 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4118 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004119 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00004120 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topperb3157722012-11-24 08:22:37 +00004121 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4122 getF32Constant(DAG, 0x3f7ff8fd));
Craig Topper08ac4692012-11-16 20:01:39 +00004123 } else { // LimitFloatPrecision <= 18
Bill Wendlinge10c8142008-09-09 22:39:21 +00004124 // For floating-point precision of 18:
4125 //
4126 // TwoToFractionalPartOfX =
4127 // 0.999999982f +
4128 // (0.693148872f +
4129 // (0.240227044f +
4130 // (0.554906021e-1f +
4131 // (0.961591928e-2f +
4132 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4133 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004134 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004135 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00004136 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004137 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00004138 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4139 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004140 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00004141 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4142 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004143 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00004144 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4145 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004146 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00004147 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4148 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004149 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00004150 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
Craig Topperb3157722012-11-24 08:22:37 +00004151 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4152 getF32Constant(DAG, 0x3f800000));
Bill Wendlinge10c8142008-09-09 22:39:21 +00004153 }
Craig Topperb3157722012-11-24 08:22:37 +00004154
4155 // Add the exponent into the result in integer domain.
4156 SDValue t13 = DAG.getNode(ISD::BITCAST, dl, MVT::i32,
4157 TwoToFractionalPartOfX);
Craig Topper538cd482012-11-24 18:52:06 +00004158 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4159 DAG.getNode(ISD::ADD, dl, MVT::i32,
4160 t13, IntegerPartOfX));
Dale Johannesen601d3c02008-09-05 01:48:15 +00004161 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00004162
Craig Topper538cd482012-11-24 18:52:06 +00004163 // No special expansion.
4164 return DAG.getNode(ISD::FEXP2, dl, Op.getValueType(), Op);
Dale Johannesen601d3c02008-09-05 01:48:15 +00004165}
4166
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004167/// visitPow - Lower a pow intrinsic. Handles the special sequences for
4168/// limited-precision mode with x == 10.0f.
Craig Topper327e4cb2012-11-25 08:08:58 +00004169static SDValue expandPow(DebugLoc dl, SDValue LHS, SDValue RHS,
4170 SelectionDAG &DAG, const TargetLowering &TLI) {
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004171 bool IsExp10 = false;
Craig Topper327e4cb2012-11-25 08:08:58 +00004172 if (LHS.getValueType() == MVT::f32 && LHS.getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004173 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
Craig Topper327e4cb2012-11-25 08:08:58 +00004174 if (ConstantFPSDNode *LHSC = dyn_cast<ConstantFPSDNode>(LHS)) {
4175 APFloat Ten(10.0f);
4176 IsExp10 = LHSC->isExactlyValue(Ten);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004177 }
4178 }
4179
Craig Topperc1aa6382012-11-25 00:48:58 +00004180 if (IsExp10) {
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004181 // Put the exponent in the right bit position for later addition to the
4182 // final result:
4183 //
4184 // #define LOG2OF10 3.3219281f
4185 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
Craig Topper327e4cb2012-11-25 08:08:58 +00004186 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, RHS,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004187 getF32Constant(DAG, 0x40549a78));
Owen Anderson825b72b2009-08-11 20:47:22 +00004188 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004189
4190 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00004191 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
4192 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004193
4194 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00004195 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00004196 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004197
Craig Topper915562e2012-11-25 00:15:07 +00004198 SDValue TwoToFractionalPartOfX;
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004199 if (LimitFloatPrecision <= 6) {
4200 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004201 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004202 // twoToFractionalPartOfX =
4203 // 0.997535578f +
4204 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004205 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004206 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004207 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004208 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00004209 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004210 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00004211 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
Craig Topper915562e2012-11-25 00:15:07 +00004212 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
4213 getF32Constant(DAG, 0x3f7f5e7e));
Craig Topper08ac4692012-11-16 20:01:39 +00004214 } else if (LimitFloatPrecision <= 12) {
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004215 // For floating-point precision of 12:
4216 //
4217 // TwoToFractionalPartOfX =
4218 // 0.999892986f +
4219 // (0.696457318f +
4220 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
4221 //
4222 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004223 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004224 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00004225 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004226 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00004227 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4228 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004229 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00004230 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
Craig Topper915562e2012-11-25 00:15:07 +00004231 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4232 getF32Constant(DAG, 0x3f7ff8fd));
Craig Topper08ac4692012-11-16 20:01:39 +00004233 } else { // LimitFloatPrecision <= 18
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004234 // For floating-point precision of 18:
4235 //
4236 // TwoToFractionalPartOfX =
4237 // 0.999999982f +
4238 // (0.693148872f +
4239 // (0.240227044f +
4240 // (0.554906021e-1f +
4241 // (0.961591928e-2f +
4242 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
4243 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00004244 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004245 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00004246 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004247 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00004248 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
4249 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004250 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00004251 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
4252 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004253 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00004254 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4255 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004256 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00004257 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4258 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00004259 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00004260 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
Craig Topper915562e2012-11-25 00:15:07 +00004261 TwoToFractionalPartOfX = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4262 getF32Constant(DAG, 0x3f800000));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004263 }
Craig Topper915562e2012-11-25 00:15:07 +00004264
4265 SDValue t13 = DAG.getNode(ISD::BITCAST, dl,MVT::i32,TwoToFractionalPartOfX);
Craig Topper327e4cb2012-11-25 08:08:58 +00004266 return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4267 DAG.getNode(ISD::ADD, dl, MVT::i32,
4268 t13, IntegerPartOfX));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004269 }
4270
Craig Topper327e4cb2012-11-25 08:08:58 +00004271 // No special expansion.
4272 return DAG.getNode(ISD::FPOW, dl, LHS.getValueType(), LHS, RHS);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004273}
4274
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004275
4276/// ExpandPowI - Expand a llvm.powi intrinsic.
4277static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS,
4278 SelectionDAG &DAG) {
4279 // If RHS is a constant, we can expand this out to a multiplication tree,
4280 // otherwise we end up lowering to a call to __powidf2 (for example). When
4281 // optimizing for size, we only want to do this if the expansion would produce
4282 // a small number of multiplies, otherwise we do the full expansion.
4283 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4284 // Get the exponent as a positive value.
4285 unsigned Val = RHSC->getSExtValue();
4286 if ((int)Val < 0) Val = -Val;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004287
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004288 // powi(x, 0) -> 1.0
4289 if (Val == 0)
4290 return DAG.getConstantFP(1.0, LHS.getValueType());
4291
Dan Gohmanae541aa2010-04-15 04:33:49 +00004292 const Function *F = DAG.getMachineFunction().getFunction();
Bill Wendling67658342012-10-09 07:45:08 +00004293 if (!F->getFnAttributes().hasAttribute(Attributes::OptimizeForSize) ||
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004294 // If optimizing for size, don't insert too many multiplies. This
4295 // inserts up to 5 multiplies.
4296 CountPopulation_32(Val)+Log2_32(Val) < 7) {
4297 // We use the simple binary decomposition method to generate the multiply
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004298 // sequence. There are more optimal ways to do this (for example,
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004299 // powi(x,15) generates one more multiply than it should), but this has
4300 // the benefit of being both really simple and much better than a libcall.
4301 SDValue Res; // Logically starts equal to 1.0
4302 SDValue CurSquare = LHS;
4303 while (Val) {
Mikhail Glushenkovbfdfea82010-01-01 04:41:36 +00004304 if (Val & 1) {
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004305 if (Res.getNode())
4306 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4307 else
4308 Res = CurSquare; // 1.0*CurSquare.
Mikhail Glushenkovbfdfea82010-01-01 04:41:36 +00004309 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004310
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004311 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4312 CurSquare, CurSquare);
4313 Val >>= 1;
4314 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004315
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004316 // If the original was negative, invert the result, producing 1/(x*x*x).
4317 if (RHSC->getSExtValue() < 0)
4318 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4319 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
4320 return Res;
4321 }
4322 }
4323
4324 // Otherwise, expand to a libcall.
4325 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4326}
4327
Devang Patel227dfdb2011-05-16 21:24:05 +00004328// getTruncatedArgReg - Find underlying register used for an truncated
4329// argument.
4330static unsigned getTruncatedArgReg(const SDValue &N) {
4331 if (N.getOpcode() != ISD::TRUNCATE)
4332 return 0;
4333
4334 const SDValue &Ext = N.getOperand(0);
4335 if (Ext.getOpcode() == ISD::AssertZext || Ext.getOpcode() == ISD::AssertSext){
4336 const SDValue &CFR = Ext.getOperand(0);
4337 if (CFR.getOpcode() == ISD::CopyFromReg)
4338 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
Craig Topper7eb46d82012-04-11 04:55:51 +00004339 if (CFR.getOpcode() == ISD::TRUNCATE)
4340 return getTruncatedArgReg(CFR);
Devang Patel227dfdb2011-05-16 21:24:05 +00004341 }
4342 return 0;
4343}
4344
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004345/// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4346/// argument, create the corresponding DBG_VALUE machine instruction for it now.
4347/// At the end of instruction selection, they will be inserted to the entry BB.
Evan Cheng9e8a2b92010-04-29 01:40:30 +00004348bool
Devang Patel78a06e52010-08-25 20:39:26 +00004349SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable,
Michael J. Spencere70c5262010-10-16 08:25:21 +00004350 int64_t Offset,
Dan Gohman5d11ea32010-05-01 00:33:16 +00004351 const SDValue &N) {
Devang Patel0b48ead2010-08-31 22:22:42 +00004352 const Argument *Arg = dyn_cast<Argument>(V);
4353 if (!Arg)
Evan Cheng9e8a2b92010-04-29 01:40:30 +00004354 return false;
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004355
Devang Patel719f6a92010-04-29 20:40:36 +00004356 MachineFunction &MF = DAG.getMachineFunction();
Devang Patela90b3052010-11-02 17:01:30 +00004357 const TargetInstrInfo *TII = DAG.getTarget().getInstrInfo();
4358 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4359
Devang Patela83ce982010-04-29 18:50:36 +00004360 // Ignore inlined function arguments here.
4361 DIVariable DV(Variable);
Devang Patel719f6a92010-04-29 20:40:36 +00004362 if (DV.isInlinedFnArgument(MF.getFunction()))
Devang Patela83ce982010-04-29 18:50:36 +00004363 return false;
4364
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004365 unsigned Reg = 0;
Devang Patel9aee3352011-09-08 22:59:09 +00004366 // Some arguments' frame index is recorded during argument lowering.
4367 Offset = FuncInfo.getArgumentFrameIndex(Arg);
4368 if (Offset)
Craig Topper7eb46d82012-04-11 04:55:51 +00004369 Reg = TRI->getFrameRegister(MF);
Devang Patel0b48ead2010-08-31 22:22:42 +00004370
Devang Patel9aee3352011-09-08 22:59:09 +00004371 if (!Reg && N.getNode()) {
Devang Patel227dfdb2011-05-16 21:24:05 +00004372 if (N.getOpcode() == ISD::CopyFromReg)
4373 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4374 else
4375 Reg = getTruncatedArgReg(N);
4376 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004377 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4378 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4379 if (PR)
4380 Reg = PR;
4381 }
4382 }
4383
Evan Chenga36acad2010-04-29 06:33:38 +00004384 if (!Reg) {
Devang Patela90b3052010-11-02 17:01:30 +00004385 // Check if ValueMap has reg number.
Evan Chenga36acad2010-04-29 06:33:38 +00004386 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
Devang Patel8bc9ef72010-11-02 17:19:03 +00004387 if (VMI != FuncInfo.ValueMap.end())
4388 Reg = VMI->second;
Evan Chenga36acad2010-04-29 06:33:38 +00004389 }
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004390
Devang Patel8bc9ef72010-11-02 17:19:03 +00004391 if (!Reg && N.getNode()) {
Devang Patela90b3052010-11-02 17:01:30 +00004392 // Check if frame index is available.
4393 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004394 if (FrameIndexSDNode *FINode =
Devang Patela90b3052010-11-02 17:01:30 +00004395 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) {
4396 Reg = TRI->getFrameRegister(MF);
4397 Offset = FINode->getIndex();
4398 }
Devang Patel8bc9ef72010-11-02 17:19:03 +00004399 }
4400
4401 if (!Reg)
4402 return false;
Devang Patela90b3052010-11-02 17:01:30 +00004403
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004404 MachineInstrBuilder MIB = BuildMI(MF, getCurDebugLoc(),
4405 TII->get(TargetOpcode::DBG_VALUE))
Evan Chenga36acad2010-04-29 06:33:38 +00004406 .addReg(Reg, RegState::Debug).addImm(Offset).addMetadata(Variable);
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004407 FuncInfo.ArgDbgValues.push_back(&*MIB);
Evan Cheng9e8a2b92010-04-29 01:40:30 +00004408 return true;
Evan Cheng2ad0fcf2010-04-28 23:08:54 +00004409}
Chris Lattnerf031e8a2010-01-01 03:32:16 +00004410
Douglas Gregor7d9663c2010-05-11 06:17:44 +00004411// VisualStudio defines setjmp as _setjmp
Michael J. Spencer1f409602010-09-24 19:48:47 +00004412#if defined(_MSC_VER) && defined(setjmp) && \
4413 !defined(setjmp_undefined_for_msvc)
4414# pragma push_macro("setjmp")
4415# undef setjmp
4416# define setjmp_undefined_for_msvc
Douglas Gregor7d9663c2010-05-11 06:17:44 +00004417#endif
4418
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004419/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4420/// we want to emit this as a call to a named external function, return the name
4421/// otherwise lower it and return null.
4422const char *
Dan Gohman46510a72010-04-15 01:51:59 +00004423SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00004424 DebugLoc dl = getCurDebugLoc();
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004425 SDValue Res;
4426
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004427 switch (Intrinsic) {
4428 default:
4429 // By default, turn this into a target intrinsic node.
4430 visitTargetIntrinsic(I, Intrinsic);
4431 return 0;
4432 case Intrinsic::vastart: visitVAStart(I); return 0;
4433 case Intrinsic::vaend: visitVAEnd(I); return 0;
4434 case Intrinsic::vacopy: visitVACopy(I); return 0;
4435 case Intrinsic::returnaddress:
Bill Wendling4533cac2010-01-28 21:51:40 +00004436 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
Gabor Greif0635f352010-06-25 09:38:13 +00004437 getValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004438 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00004439 case Intrinsic::frameaddress:
Bill Wendling4533cac2010-01-28 21:51:40 +00004440 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
Gabor Greif0635f352010-06-25 09:38:13 +00004441 getValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004442 return 0;
4443 case Intrinsic::setjmp:
Bill Wendlingc27facc2012-03-05 19:29:36 +00004444 return &"_setjmp"[!TLI.usesUnderscoreSetJmp()];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004445 case Intrinsic::longjmp:
Bill Wendlingc27facc2012-03-05 19:29:36 +00004446 return &"_longjmp"[!TLI.usesUnderscoreLongJmp()];
Chris Lattner824b9582008-11-21 16:42:48 +00004447 case Intrinsic::memcpy: {
Mon P Wang20adc9d2010-04-04 03:10:48 +00004448 // Assert for address < 256 since we support only user defined address
4449 // spaces.
Gabor Greif0635f352010-06-25 09:38:13 +00004450 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
Mon P Wang20adc9d2010-04-04 03:10:48 +00004451 < 256 &&
Gabor Greif0635f352010-06-25 09:38:13 +00004452 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
Mon P Wang20adc9d2010-04-04 03:10:48 +00004453 < 256 &&
4454 "Unknown address space");
Gabor Greif0635f352010-06-25 09:38:13 +00004455 SDValue Op1 = getValue(I.getArgOperand(0));
4456 SDValue Op2 = getValue(I.getArgOperand(1));
4457 SDValue Op3 = getValue(I.getArgOperand(2));
4458 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4459 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
Mon P Wang20adc9d2010-04-04 03:10:48 +00004460 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol, false,
Chris Lattnere72f2022010-09-21 05:40:29 +00004461 MachinePointerInfo(I.getArgOperand(0)),
4462 MachinePointerInfo(I.getArgOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004463 return 0;
4464 }
Chris Lattner824b9582008-11-21 16:42:48 +00004465 case Intrinsic::memset: {
Mon P Wang20adc9d2010-04-04 03:10:48 +00004466 // Assert for address < 256 since we support only user defined address
4467 // spaces.
Gabor Greif0635f352010-06-25 09:38:13 +00004468 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
Mon P Wang20adc9d2010-04-04 03:10:48 +00004469 < 256 &&
4470 "Unknown address space");
Gabor Greif0635f352010-06-25 09:38:13 +00004471 SDValue Op1 = getValue(I.getArgOperand(0));
4472 SDValue Op2 = getValue(I.getArgOperand(1));
4473 SDValue Op3 = getValue(I.getArgOperand(2));
4474 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4475 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
Mon P Wang20adc9d2010-04-04 03:10:48 +00004476 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
Chris Lattnere72f2022010-09-21 05:40:29 +00004477 MachinePointerInfo(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004478 return 0;
4479 }
Chris Lattner824b9582008-11-21 16:42:48 +00004480 case Intrinsic::memmove: {
Mon P Wang20adc9d2010-04-04 03:10:48 +00004481 // Assert for address < 256 since we support only user defined address
4482 // spaces.
Gabor Greif0635f352010-06-25 09:38:13 +00004483 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
Mon P Wang20adc9d2010-04-04 03:10:48 +00004484 < 256 &&
Gabor Greif0635f352010-06-25 09:38:13 +00004485 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
Mon P Wang20adc9d2010-04-04 03:10:48 +00004486 < 256 &&
4487 "Unknown address space");
Gabor Greif0635f352010-06-25 09:38:13 +00004488 SDValue Op1 = getValue(I.getArgOperand(0));
4489 SDValue Op2 = getValue(I.getArgOperand(1));
4490 SDValue Op3 = getValue(I.getArgOperand(2));
4491 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4492 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
Mon P Wang20adc9d2010-04-04 03:10:48 +00004493 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
Chris Lattnere72f2022010-09-21 05:40:29 +00004494 MachinePointerInfo(I.getArgOperand(0)),
4495 MachinePointerInfo(I.getArgOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004496 return 0;
4497 }
Bill Wendling92c1e122009-02-13 02:16:35 +00004498 case Intrinsic::dbg_declare: {
Dan Gohman46510a72010-04-15 01:51:59 +00004499 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Devang Patelac1ceb32009-10-09 22:42:28 +00004500 MDNode *Variable = DI.getVariable();
Dan Gohman46510a72010-04-15 01:51:59 +00004501 const Value *Address = DI.getAddress();
Eric Christopher8f2a88d2012-03-15 21:33:41 +00004502 if (!Address || !DIVariable(Variable).Verify()) {
4503 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Dale Johannesen8ac38f22010-02-08 21:53:27 +00004504 return 0;
Eric Christopher8f2a88d2012-03-15 21:33:41 +00004505 }
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004506
4507 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
4508 // but do not always have a corresponding SDNode built. The SDNodeOrder
4509 // absolute, but not relative, values are different depending on whether
4510 // debug info exists.
4511 ++SDNodeOrder;
Devang Patel3f74a112010-09-02 21:29:42 +00004512
4513 // Check if address has undef value.
4514 if (isa<UndefValue>(Address) ||
4515 (Address->use_empty() && !isa<Argument>(Address))) {
Eric Christopher24413672012-02-23 03:39:39 +00004516 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Devang Patel3f74a112010-09-02 21:29:42 +00004517 return 0;
4518 }
4519
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004520 SDValue &N = NodeMap[Address];
Devang Patel0b48ead2010-08-31 22:22:42 +00004521 if (!N.getNode() && isa<Argument>(Address))
4522 // Check unused arguments map.
4523 N = UnusedArgNodeMap[Address];
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004524 SDDbgValue *SDV;
4525 if (N.getNode()) {
Devang Patel8e741ed2010-09-02 21:02:27 +00004526 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4527 Address = BCI->getOperand(0);
Eric Christopher178606d2012-02-24 01:59:08 +00004528 // Parameters are handled specially.
4529 bool isParameter =
4530 (DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable ||
4531 isa<Argument>(Address));
4532
Devang Patel8e741ed2010-09-02 21:02:27 +00004533 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4534
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004535 if (isParameter && !AI) {
4536 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4537 if (FINode)
4538 // Byval parameter. We have a frame index at this point.
4539 SDV = DAG.getDbgValue(Variable, FINode->getIndex(),
4540 0, dl, SDNodeOrder);
Devang Patelafeaae72010-12-06 22:39:26 +00004541 else {
Devang Patel227dfdb2011-05-16 21:24:05 +00004542 // Address is an argument, so try to emit its dbg value using
4543 // virtual register info from the FuncInfo.ValueMap.
4544 EmitFuncArgumentDbgValue(Address, Variable, 0, N);
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004545 return 0;
Devang Patelafeaae72010-12-06 22:39:26 +00004546 }
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004547 } else if (AI)
4548 SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(),
4549 0, dl, SDNodeOrder);
Devang Patelafeaae72010-12-06 22:39:26 +00004550 else {
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004551 // Can't do anything with other non-AI cases yet.
Eric Christopher24413672012-02-23 03:39:39 +00004552 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Eric Christopher178606d2012-02-24 01:59:08 +00004553 DEBUG(dbgs() << "non-AllocaInst issue for Address: \n\t");
4554 DEBUG(Address->dump());
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004555 return 0;
Devang Patelafeaae72010-12-06 22:39:26 +00004556 }
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004557 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4558 } else {
Gabor Greiffb4032f2010-10-01 10:32:19 +00004559 // If Address is an argument then try to emit its dbg value using
Michael J. Spencere70c5262010-10-16 08:25:21 +00004560 // virtual register info from the FuncInfo.ValueMap.
Devang Patel6cd467b2010-08-26 22:53:27 +00004561 if (!EmitFuncArgumentDbgValue(Address, Variable, 0, N)) {
Devang Patel1397fdc2010-09-15 14:48:53 +00004562 // If variable is pinned by a alloca in dominating bb then
4563 // use StaticAllocaMap.
4564 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
Devang Patel27ede1b2010-09-15 18:13:55 +00004565 if (AI->getParent() != DI.getParent()) {
4566 DenseMap<const AllocaInst*, int>::iterator SI =
4567 FuncInfo.StaticAllocaMap.find(AI);
4568 if (SI != FuncInfo.StaticAllocaMap.end()) {
4569 SDV = DAG.getDbgValue(Variable, SI->second,
4570 0, dl, SDNodeOrder);
4571 DAG.AddDbgValue(SDV, 0, false);
4572 return 0;
4573 }
Devang Patel1397fdc2010-09-15 14:48:53 +00004574 }
4575 }
Eric Christopher0822e012012-02-23 03:39:43 +00004576 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Devang Patel6cd467b2010-08-26 22:53:27 +00004577 }
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004578 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004579 return 0;
Bill Wendling92c1e122009-02-13 02:16:35 +00004580 }
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004581 case Intrinsic::dbg_value: {
Dan Gohman46510a72010-04-15 01:51:59 +00004582 const DbgValueInst &DI = cast<DbgValueInst>(I);
Devang Patel02f0dbd2010-05-07 22:04:20 +00004583 if (!DIVariable(DI.getVariable()).Verify())
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004584 return 0;
4585
4586 MDNode *Variable = DI.getVariable();
Devang Patel00190342010-03-15 19:15:44 +00004587 uint64_t Offset = DI.getOffset();
Dan Gohman46510a72010-04-15 01:51:59 +00004588 const Value *V = DI.getValue();
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004589 if (!V)
4590 return 0;
Devang Patel00190342010-03-15 19:15:44 +00004591
4592 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
4593 // but do not always have a corresponding SDNode built. The SDNodeOrder
4594 // absolute, but not relative, values are different depending on whether
4595 // debug info exists.
4596 ++SDNodeOrder;
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004597 SDDbgValue *SDV;
Devang Patel57871242011-08-03 23:13:55 +00004598 if (isa<ConstantInt>(V) || isa<ConstantFP>(V) || isa<UndefValue>(V)) {
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004599 SDV = DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder);
4600 DAG.AddDbgValue(SDV, 0, false);
Devang Patel00190342010-03-15 19:15:44 +00004601 } else {
Dale Johannesenbdc09d92010-07-16 00:02:08 +00004602 // Do not use getValue() in here; we don't want to generate code at
4603 // this point if it hasn't been done yet.
Devang Patel9126c0d2010-06-01 19:59:01 +00004604 SDValue N = NodeMap[V];
4605 if (!N.getNode() && isa<Argument>(V))
4606 // Check unused arguments map.
4607 N = UnusedArgNodeMap[V];
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004608 if (N.getNode()) {
Devang Patel78a06e52010-08-25 20:39:26 +00004609 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, N)) {
Evan Cheng9e8a2b92010-04-29 01:40:30 +00004610 SDV = DAG.getDbgValue(Variable, N.getNode(),
4611 N.getResNo(), Offset, dl, SDNodeOrder);
4612 DAG.AddDbgValue(SDV, N.getNode(), false);
4613 }
Devang Patela778f5c2011-02-18 22:43:42 +00004614 } else if (!V->use_empty() ) {
Dale Johannesenbdc09d92010-07-16 00:02:08 +00004615 // Do not call getValue(V) yet, as we don't want to generate code.
4616 // Remember it for later.
4617 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4618 DanglingDebugInfoMap[V] = DDI;
Devang Patel0991dfb2010-08-27 22:25:51 +00004619 } else {
Devang Patel00190342010-03-15 19:15:44 +00004620 // We may expand this to cover more cases. One case where we have no
Devang Patelafeaae72010-12-06 22:39:26 +00004621 // data available is an unreferenced parameter.
Eric Christopher0822e012012-02-23 03:39:43 +00004622 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n");
Dale Johannesenfdb42fa2010-04-26 20:06:49 +00004623 }
Devang Patel00190342010-03-15 19:15:44 +00004624 }
4625
4626 // Build a debug info table entry.
Dan Gohman46510a72010-04-15 01:51:59 +00004627 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004628 V = BCI->getOperand(0);
Dan Gohman46510a72010-04-15 01:51:59 +00004629 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004630 // Don't handle byval struct arguments or VLAs, for example.
Eric Christopher7e1e18f2012-03-26 06:10:32 +00004631 if (!AI) {
Eric Christopher9fc5c832012-03-28 07:34:36 +00004632 DEBUG(dbgs() << "Dropping debug location info for:\n " << DI << "\n");
4633 DEBUG(dbgs() << " Last seen at:\n " << *V << "\n");
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004634 return 0;
Eric Christopher7e1e18f2012-03-26 06:10:32 +00004635 }
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004636 DenseMap<const AllocaInst*, int>::iterator SI =
4637 FuncInfo.StaticAllocaMap.find(AI);
4638 if (SI == FuncInfo.StaticAllocaMap.end())
4639 return 0; // VLAs.
4640 int FI = SI->second;
Michael J. Spencere70c5262010-10-16 08:25:21 +00004641
Chris Lattner512063d2010-04-05 06:19:28 +00004642 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4643 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
4644 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
Dale Johannesen904c2fa2010-02-01 19:54:53 +00004645 return 0;
4646 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004647
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00004648 case Intrinsic::eh_typeid_for: {
Chris Lattner512063d2010-04-05 06:19:28 +00004649 // Find the type id for the given typeinfo.
Gabor Greif0635f352010-06-25 09:38:13 +00004650 GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0));
Chris Lattner512063d2010-04-05 06:19:28 +00004651 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4652 Res = DAG.getConstant(TypeID, MVT::i32);
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004653 setValue(&I, Res);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004654 return 0;
4655 }
4656
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004657 case Intrinsic::eh_return_i32:
4658 case Intrinsic::eh_return_i64:
Chris Lattner512063d2010-04-05 06:19:28 +00004659 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
4660 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
4661 MVT::Other,
4662 getControlRoot(),
Gabor Greif0635f352010-06-25 09:38:13 +00004663 getValue(I.getArgOperand(0)),
4664 getValue(I.getArgOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004665 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004666 case Intrinsic::eh_unwind_init:
Chris Lattner512063d2010-04-05 06:19:28 +00004667 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004668 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004669 case Intrinsic::eh_dwarf_cfa: {
Gabor Greif0635f352010-06-25 09:38:13 +00004670 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), dl,
Duncan Sands3a66a682009-10-13 21:04:12 +00004671 TLI.getPointerTy());
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004672 SDValue Offset = DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004673 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004674 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004675 TLI.getPointerTy()),
4676 CfaArg);
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004677 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004678 TLI.getPointerTy(),
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004679 DAG.getConstant(0, TLI.getPointerTy()));
Bill Wendling4533cac2010-01-28 21:51:40 +00004680 setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
4681 FA, Offset));
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004682 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004683 }
Jim Grosbachca752c92010-01-28 01:45:32 +00004684 case Intrinsic::eh_sjlj_callsite: {
Chris Lattner512063d2010-04-05 06:19:28 +00004685 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Gabor Greif0635f352010-06-25 09:38:13 +00004686 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
Jim Grosbachca752c92010-01-28 01:45:32 +00004687 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
Chris Lattner512063d2010-04-05 06:19:28 +00004688 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
Jim Grosbachca752c92010-01-28 01:45:32 +00004689
Chris Lattner512063d2010-04-05 06:19:28 +00004690 MMI.setCurrentCallSite(CI->getZExtValue());
Jim Grosbachca752c92010-01-28 01:45:32 +00004691 return 0;
4692 }
Bill Wendling6ef94172011-09-28 03:36:43 +00004693 case Intrinsic::eh_sjlj_functioncontext: {
4694 // Get and store the index of the function context.
4695 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
Bill Wendlingadbf7b22011-09-28 03:52:41 +00004696 AllocaInst *FnCtx =
4697 cast<AllocaInst>(I.getArgOperand(0)->stripPointerCasts());
Bill Wendling6ef94172011-09-28 03:36:43 +00004698 int FI = FuncInfo.StaticAllocaMap[FnCtx];
4699 MFI->setFunctionContextIndex(FI);
4700 return 0;
4701 }
Jim Grosbach23ff7cf2010-05-26 20:22:18 +00004702 case Intrinsic::eh_sjlj_setjmp: {
Bill Wendlingce370cf2011-10-07 21:25:38 +00004703 SDValue Ops[2];
4704 Ops[0] = getRoot();
4705 Ops[1] = getValue(I.getArgOperand(0));
4706 SDValue Op = DAG.getNode(ISD::EH_SJLJ_SETJMP, dl,
4707 DAG.getVTList(MVT::i32, MVT::Other),
4708 Ops, 2);
4709 setValue(&I, Op.getValue(0));
4710 DAG.setRoot(Op.getValue(1));
Jim Grosbach23ff7cf2010-05-26 20:22:18 +00004711 return 0;
4712 }
Jim Grosbach5eb19512010-05-22 01:06:18 +00004713 case Intrinsic::eh_sjlj_longjmp: {
Jim Grosbach23ff7cf2010-05-26 20:22:18 +00004714 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, dl, MVT::Other,
Jim Grosbache4ad3872010-10-19 23:27:08 +00004715 getRoot(), getValue(I.getArgOperand(0))));
4716 return 0;
4717 }
Jim Grosbachca752c92010-01-28 01:45:32 +00004718
Dale Johannesen0488fb62010-09-30 23:57:10 +00004719 case Intrinsic::x86_mmx_pslli_w:
4720 case Intrinsic::x86_mmx_pslli_d:
4721 case Intrinsic::x86_mmx_pslli_q:
4722 case Intrinsic::x86_mmx_psrli_w:
4723 case Intrinsic::x86_mmx_psrli_d:
4724 case Intrinsic::x86_mmx_psrli_q:
4725 case Intrinsic::x86_mmx_psrai_w:
4726 case Intrinsic::x86_mmx_psrai_d: {
4727 SDValue ShAmt = getValue(I.getArgOperand(1));
4728 if (isa<ConstantSDNode>(ShAmt)) {
4729 visitTargetIntrinsic(I, Intrinsic);
4730 return 0;
4731 }
4732 unsigned NewIntrinsic = 0;
4733 EVT ShAmtVT = MVT::v2i32;
4734 switch (Intrinsic) {
4735 case Intrinsic::x86_mmx_pslli_w:
4736 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
4737 break;
4738 case Intrinsic::x86_mmx_pslli_d:
4739 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
4740 break;
4741 case Intrinsic::x86_mmx_pslli_q:
4742 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
4743 break;
4744 case Intrinsic::x86_mmx_psrli_w:
4745 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
4746 break;
4747 case Intrinsic::x86_mmx_psrli_d:
4748 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
4749 break;
4750 case Intrinsic::x86_mmx_psrli_q:
4751 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
4752 break;
4753 case Intrinsic::x86_mmx_psrai_w:
4754 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
4755 break;
4756 case Intrinsic::x86_mmx_psrai_d:
4757 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
4758 break;
4759 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4760 }
4761
4762 // The vector shift intrinsics with scalars uses 32b shift amounts but
4763 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
4764 // to be zero.
4765 // We must do this early because v2i32 is not a legal type.
Dale Johannesen0488fb62010-09-30 23:57:10 +00004766 SDValue ShOps[2];
4767 ShOps[0] = ShAmt;
4768 ShOps[1] = DAG.getConstant(0, MVT::i32);
4769 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
4770 EVT DestVT = TLI.getValueType(I.getType());
Wesley Peckbf17cfa2010-11-23 03:31:01 +00004771 ShAmt = DAG.getNode(ISD::BITCAST, dl, DestVT, ShAmt);
Dale Johannesen0488fb62010-09-30 23:57:10 +00004772 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
4773 DAG.getConstant(NewIntrinsic, MVT::i32),
4774 getValue(I.getArgOperand(0)), ShAmt);
4775 setValue(&I, Res);
4776 return 0;
4777 }
Pete Cooperd18134f2012-02-24 03:51:49 +00004778 case Intrinsic::x86_avx_vinsertf128_pd_256:
4779 case Intrinsic::x86_avx_vinsertf128_ps_256:
Craig Topperb45c9692012-04-07 22:32:29 +00004780 case Intrinsic::x86_avx_vinsertf128_si_256:
4781 case Intrinsic::x86_avx2_vinserti128: {
Pete Cooperd18134f2012-02-24 03:51:49 +00004782 EVT DestVT = TLI.getValueType(I.getType());
4783 EVT ElVT = TLI.getValueType(I.getArgOperand(1)->getType());
4784 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(2))->getZExtValue() & 1) *
4785 ElVT.getVectorNumElements();
4786 Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, DestVT,
4787 getValue(I.getArgOperand(0)),
4788 getValue(I.getArgOperand(1)),
Craig Topperf6dc7922012-09-05 05:48:09 +00004789 DAG.getIntPtrConstant(Idx));
4790 setValue(&I, Res);
4791 return 0;
4792 }
4793 case Intrinsic::x86_avx_vextractf128_pd_256:
4794 case Intrinsic::x86_avx_vextractf128_ps_256:
4795 case Intrinsic::x86_avx_vextractf128_si_256:
4796 case Intrinsic::x86_avx2_vextracti128: {
Craig Topperf6dc7922012-09-05 05:48:09 +00004797 EVT DestVT = TLI.getValueType(I.getType());
4798 uint64_t Idx = (cast<ConstantInt>(I.getArgOperand(1))->getZExtValue() & 1) *
4799 DestVT.getVectorNumElements();
4800 Res = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT,
4801 getValue(I.getArgOperand(0)),
4802 DAG.getIntPtrConstant(Idx));
Pete Cooperd18134f2012-02-24 03:51:49 +00004803 setValue(&I, Res);
4804 return 0;
4805 }
Mon P Wang77cdf302008-11-10 20:54:11 +00004806 case Intrinsic::convertff:
4807 case Intrinsic::convertfsi:
4808 case Intrinsic::convertfui:
4809 case Intrinsic::convertsif:
4810 case Intrinsic::convertuif:
4811 case Intrinsic::convertss:
4812 case Intrinsic::convertsu:
4813 case Intrinsic::convertus:
4814 case Intrinsic::convertuu: {
4815 ISD::CvtCode Code = ISD::CVT_INVALID;
4816 switch (Intrinsic) {
Craig Topperc42e6402012-04-11 04:34:11 +00004817 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
Mon P Wang77cdf302008-11-10 20:54:11 +00004818 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4819 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4820 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4821 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4822 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4823 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4824 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4825 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4826 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4827 }
Owen Andersone50ed302009-08-10 22:56:29 +00004828 EVT DestVT = TLI.getValueType(I.getType());
Gabor Greif0635f352010-06-25 09:38:13 +00004829 const Value *Op1 = I.getArgOperand(0);
Craig Topper134f78c2012-11-24 23:05:23 +00004830 Res = DAG.getConvertRndSat(DestVT, dl, getValue(Op1),
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004831 DAG.getValueType(DestVT),
4832 DAG.getValueType(getValue(Op1).getValueType()),
Gabor Greif0635f352010-06-25 09:38:13 +00004833 getValue(I.getArgOperand(1)),
4834 getValue(I.getArgOperand(2)),
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004835 Code);
4836 setValue(&I, Res);
Mon P Wang77cdf302008-11-10 20:54:11 +00004837 return 0;
4838 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004839 case Intrinsic::powi:
Gabor Greif0635f352010-06-25 09:38:13 +00004840 setValue(&I, ExpandPowI(dl, getValue(I.getArgOperand(0)),
4841 getValue(I.getArgOperand(1)), DAG));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004842 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004843 case Intrinsic::log:
Craig Topper5d1e0892012-11-23 18:38:31 +00004844 setValue(&I, expandLog(dl, getValue(I.getArgOperand(0)), DAG, TLI));
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004845 return 0;
4846 case Intrinsic::log2:
Craig Topper5d1e0892012-11-23 18:38:31 +00004847 setValue(&I, expandLog2(dl, getValue(I.getArgOperand(0)), DAG, TLI));
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004848 return 0;
4849 case Intrinsic::log10:
Craig Topper5d1e0892012-11-23 18:38:31 +00004850 setValue(&I, expandLog10(dl, getValue(I.getArgOperand(0)), DAG, TLI));
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004851 return 0;
4852 case Intrinsic::exp:
Craig Topper538cd482012-11-24 18:52:06 +00004853 setValue(&I, expandExp(dl, getValue(I.getArgOperand(0)), DAG, TLI));
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004854 return 0;
4855 case Intrinsic::exp2:
Craig Topper538cd482012-11-24 18:52:06 +00004856 setValue(&I, expandExp2(dl, getValue(I.getArgOperand(0)), DAG, TLI));
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004857 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004858 case Intrinsic::pow:
Craig Topper327e4cb2012-11-25 08:08:58 +00004859 setValue(&I, expandPow(dl, getValue(I.getArgOperand(0)),
4860 getValue(I.getArgOperand(1)), DAG, TLI));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004861 return 0;
Craig Topper9bd4dd72012-11-16 07:48:23 +00004862 case Intrinsic::sqrt:
Peter Collingbourneb34d3aa2012-05-28 21:48:37 +00004863 case Intrinsic::fabs:
Craig Topper9bd4dd72012-11-16 07:48:23 +00004864 case Intrinsic::sin:
4865 case Intrinsic::cos:
Dan Gohman27db99f2012-07-26 17:43:27 +00004866 case Intrinsic::floor:
Craig Topper49010472012-11-15 06:51:10 +00004867 case Intrinsic::ceil:
Craig Topper49010472012-11-15 06:51:10 +00004868 case Intrinsic::trunc:
Craig Topper49010472012-11-15 06:51:10 +00004869 case Intrinsic::rint:
Craig Topper9bd4dd72012-11-16 07:48:23 +00004870 case Intrinsic::nearbyint: {
4871 unsigned Opcode;
4872 switch (Intrinsic) {
4873 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4874 case Intrinsic::sqrt: Opcode = ISD::FSQRT; break;
4875 case Intrinsic::fabs: Opcode = ISD::FABS; break;
4876 case Intrinsic::sin: Opcode = ISD::FSIN; break;
4877 case Intrinsic::cos: Opcode = ISD::FCOS; break;
4878 case Intrinsic::floor: Opcode = ISD::FFLOOR; break;
4879 case Intrinsic::ceil: Opcode = ISD::FCEIL; break;
4880 case Intrinsic::trunc: Opcode = ISD::FTRUNC; break;
4881 case Intrinsic::rint: Opcode = ISD::FRINT; break;
4882 case Intrinsic::nearbyint: Opcode = ISD::FNEARBYINT; break;
4883 }
4884
4885 setValue(&I, DAG.getNode(Opcode, dl,
Craig Topper49010472012-11-15 06:51:10 +00004886 getValue(I.getArgOperand(0)).getValueType(),
4887 getValue(I.getArgOperand(0))));
4888 return 0;
Craig Topper9bd4dd72012-11-16 07:48:23 +00004889 }
Cameron Zwarich33390842011-07-08 21:39:21 +00004890 case Intrinsic::fma:
4891 setValue(&I, DAG.getNode(ISD::FMA, dl,
4892 getValue(I.getArgOperand(0)).getValueType(),
4893 getValue(I.getArgOperand(0)),
4894 getValue(I.getArgOperand(1)),
4895 getValue(I.getArgOperand(2))));
4896 return 0;
Lang Hames5afba6f2012-06-05 19:07:46 +00004897 case Intrinsic::fmuladd: {
4898 EVT VT = TLI.getValueType(I.getType());
Lang Hamese0231412012-06-22 01:09:09 +00004899 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict &&
Lang Hamesb47ec402012-11-22 03:31:45 +00004900 TLI.isOperationLegalOrCustom(ISD::FMA, VT) &&
Lang Hamese0231412012-06-22 01:09:09 +00004901 TLI.isFMAFasterThanMulAndAdd(VT)){
Lang Hames5afba6f2012-06-05 19:07:46 +00004902 setValue(&I, DAG.getNode(ISD::FMA, dl,
4903 getValue(I.getArgOperand(0)).getValueType(),
4904 getValue(I.getArgOperand(0)),
4905 getValue(I.getArgOperand(1)),
4906 getValue(I.getArgOperand(2))));
4907 } else {
4908 SDValue Mul = DAG.getNode(ISD::FMUL, dl,
4909 getValue(I.getArgOperand(0)).getValueType(),
4910 getValue(I.getArgOperand(0)),
4911 getValue(I.getArgOperand(1)));
4912 SDValue Add = DAG.getNode(ISD::FADD, dl,
4913 getValue(I.getArgOperand(0)).getValueType(),
4914 Mul,
4915 getValue(I.getArgOperand(2)));
4916 setValue(&I, Add);
4917 }
4918 return 0;
4919 }
Anton Korobeynikovbe5b0322010-03-14 18:42:15 +00004920 case Intrinsic::convert_to_fp16:
4921 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, dl,
Gabor Greif0635f352010-06-25 09:38:13 +00004922 MVT::i16, getValue(I.getArgOperand(0))));
Anton Korobeynikovbe5b0322010-03-14 18:42:15 +00004923 return 0;
4924 case Intrinsic::convert_from_fp16:
4925 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, dl,
Gabor Greif0635f352010-06-25 09:38:13 +00004926 MVT::f32, getValue(I.getArgOperand(0))));
Anton Korobeynikovbe5b0322010-03-14 18:42:15 +00004927 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004928 case Intrinsic::pcmarker: {
Gabor Greif0635f352010-06-25 09:38:13 +00004929 SDValue Tmp = getValue(I.getArgOperand(0));
Bill Wendling4533cac2010-01-28 21:51:40 +00004930 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004931 return 0;
4932 }
4933 case Intrinsic::readcyclecounter: {
4934 SDValue Op = getRoot();
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004935 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4936 DAG.getVTList(MVT::i64, MVT::Other),
4937 &Op, 1);
4938 setValue(&I, Res);
4939 DAG.setRoot(Res.getValue(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004940 return 0;
4941 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004942 case Intrinsic::bswap:
Bill Wendling4533cac2010-01-28 21:51:40 +00004943 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
Gabor Greif0635f352010-06-25 09:38:13 +00004944 getValue(I.getArgOperand(0)).getValueType(),
4945 getValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004946 return 0;
4947 case Intrinsic::cttz: {
Gabor Greif0635f352010-06-25 09:38:13 +00004948 SDValue Arg = getValue(I.getArgOperand(0));
Chandler Carruth63974b22011-12-13 01:56:10 +00004949 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00004950 EVT Ty = Arg.getValueType();
Chandler Carruth63974b22011-12-13 01:56:10 +00004951 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTTZ : ISD::CTTZ_ZERO_UNDEF,
4952 dl, Ty, Arg));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004953 return 0;
4954 }
4955 case Intrinsic::ctlz: {
Gabor Greif0635f352010-06-25 09:38:13 +00004956 SDValue Arg = getValue(I.getArgOperand(0));
Chandler Carruth63974b22011-12-13 01:56:10 +00004957 ConstantInt *CI = cast<ConstantInt>(I.getArgOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00004958 EVT Ty = Arg.getValueType();
Chandler Carruth63974b22011-12-13 01:56:10 +00004959 setValue(&I, DAG.getNode(CI->isZero() ? ISD::CTLZ : ISD::CTLZ_ZERO_UNDEF,
4960 dl, Ty, Arg));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004961 return 0;
4962 }
4963 case Intrinsic::ctpop: {
Gabor Greif0635f352010-06-25 09:38:13 +00004964 SDValue Arg = getValue(I.getArgOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00004965 EVT Ty = Arg.getValueType();
Bill Wendling4533cac2010-01-28 21:51:40 +00004966 setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004967 return 0;
4968 }
4969 case Intrinsic::stacksave: {
4970 SDValue Op = getRoot();
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004971 Res = DAG.getNode(ISD::STACKSAVE, dl,
4972 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4973 setValue(&I, Res);
4974 DAG.setRoot(Res.getValue(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004975 return 0;
4976 }
4977 case Intrinsic::stackrestore: {
Gabor Greif0635f352010-06-25 09:38:13 +00004978 Res = getValue(I.getArgOperand(0));
Bill Wendling4533cac2010-01-28 21:51:40 +00004979 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004980 return 0;
4981 }
Bill Wendling57344502008-11-18 11:01:33 +00004982 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00004983 // Emit code into the DAG to store the stack guard onto the stack.
4984 MachineFunction &MF = DAG.getMachineFunction();
4985 MachineFrameInfo *MFI = MF.getFrameInfo();
Owen Andersone50ed302009-08-10 22:56:29 +00004986 EVT PtrTy = TLI.getPointerTy();
Bill Wendlingb2a42982008-11-06 02:29:10 +00004987
Gabor Greif0635f352010-06-25 09:38:13 +00004988 SDValue Src = getValue(I.getArgOperand(0)); // The guard's value.
4989 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
Bill Wendlingb2a42982008-11-06 02:29:10 +00004990
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004991 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00004992 MFI->setStackProtectorIndex(FI);
4993
4994 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4995
4996 // Store the stack protector onto the stack.
Craig Topper134f78c2012-11-24 23:05:23 +00004997 Res = DAG.getStore(getRoot(), dl, Src, FIN,
Chris Lattner84bd98a2010-09-21 18:58:22 +00004998 MachinePointerInfo::getFixedStack(FI),
4999 true, false, 0);
Bill Wendlingd0283fa2009-12-22 00:40:51 +00005000 setValue(&I, Res);
5001 DAG.setRoot(Res);
Bill Wendlingb2a42982008-11-06 02:29:10 +00005002 return 0;
5003 }
Eric Christopher7b5e6172009-10-27 00:52:25 +00005004 case Intrinsic::objectsize: {
5005 // If we don't know by now, we're never going to know.
Gabor Greif0635f352010-06-25 09:38:13 +00005006 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
Eric Christopher7b5e6172009-10-27 00:52:25 +00005007
5008 assert(CI && "Non-constant type in __builtin_object_size?");
5009
Gabor Greif0635f352010-06-25 09:38:13 +00005010 SDValue Arg = getValue(I.getCalledValue());
Eric Christopher7e5d2ff2009-10-28 21:32:16 +00005011 EVT Ty = Arg.getValueType();
5012
Dan Gohmane368b462010-06-18 14:22:04 +00005013 if (CI->isZero())
Bill Wendlingd0283fa2009-12-22 00:40:51 +00005014 Res = DAG.getConstant(-1ULL, Ty);
Eric Christopher7b5e6172009-10-27 00:52:25 +00005015 else
Bill Wendlingd0283fa2009-12-22 00:40:51 +00005016 Res = DAG.getConstant(0, Ty);
5017
5018 setValue(&I, Res);
Eric Christopher7b5e6172009-10-27 00:52:25 +00005019 return 0;
5020 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005021 case Intrinsic::var_annotation:
5022 // Discard annotate attributes
5023 return 0;
5024
5025 case Intrinsic::init_trampoline: {
Gabor Greif0635f352010-06-25 09:38:13 +00005026 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005027
5028 SDValue Ops[6];
5029 Ops[0] = getRoot();
Gabor Greif0635f352010-06-25 09:38:13 +00005030 Ops[1] = getValue(I.getArgOperand(0));
5031 Ops[2] = getValue(I.getArgOperand(1));
5032 Ops[3] = getValue(I.getArgOperand(2));
5033 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005034 Ops[5] = DAG.getSrcValue(F);
5035
Duncan Sands4a544a72011-09-06 13:37:06 +00005036 Res = DAG.getNode(ISD::INIT_TRAMPOLINE, dl, MVT::Other, Ops, 6);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005037
Duncan Sands4a544a72011-09-06 13:37:06 +00005038 DAG.setRoot(Res);
5039 return 0;
5040 }
5041 case Intrinsic::adjust_trampoline: {
5042 setValue(&I, DAG.getNode(ISD::ADJUST_TRAMPOLINE, dl,
5043 TLI.getPointerTy(),
5044 getValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005045 return 0;
5046 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005047 case Intrinsic::gcroot:
5048 if (GFI) {
Bill Wendling95dd4422012-05-01 22:50:45 +00005049 const Value *Alloca = I.getArgOperand(0)->stripPointerCasts();
Gabor Greif0635f352010-06-25 09:38:13 +00005050 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005051
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005052 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
5053 GFI->addStackRoot(FI->getIndex(), TypeMap);
5054 }
5055 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005056 case Intrinsic::gcread:
5057 case Intrinsic::gcwrite:
Torok Edwinc23197a2009-07-14 16:55:14 +00005058 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
Bill Wendlingd0283fa2009-12-22 00:40:51 +00005059 case Intrinsic::flt_rounds:
Bill Wendling4533cac2010-01-28 21:51:40 +00005060 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005061 return 0;
Jakub Staszak9da99342011-07-06 18:22:43 +00005062
5063 case Intrinsic::expect: {
5064 // Just replace __builtin_expect(exp, c) with EXP.
5065 setValue(&I, getValue(I.getArgOperand(0)));
5066 return 0;
5067 }
5068
Shuxin Yang970755e2012-10-19 20:11:16 +00005069 case Intrinsic::debugtrap:
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005070 case Intrinsic::trap: {
Nick Lewycky8a8d4792011-12-02 22:16:29 +00005071 StringRef TrapFuncName = TM.Options.getTrapFunctionName();
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005072 if (TrapFuncName.empty()) {
Shuxin Yang970755e2012-10-19 20:11:16 +00005073 ISD::NodeType Op = (Intrinsic == Intrinsic::trap) ?
5074 ISD::TRAP : ISD::DEBUGTRAP;
5075 DAG.setRoot(DAG.getNode(Op, dl,MVT::Other, getRoot()));
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005076 return 0;
5077 }
5078 TargetLowering::ArgListTy Args;
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00005079 TargetLowering::
5080 CallLoweringInfo CLI(getRoot(), I.getType(),
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005081 false, false, false, false, 0, CallingConv::C,
Evan Cheng4bfcd4a2012-02-28 18:51:51 +00005082 /*isTailCall=*/false,
5083 /*doesNotRet=*/false, /*isReturnValueUsed=*/true,
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005084 DAG.getExternalSymbol(TrapFuncName.data(), TLI.getPointerTy()),
Craig Topper134f78c2012-11-24 23:05:23 +00005085 Args, DAG, dl);
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00005086 std::pair<SDValue, SDValue> Result = TLI.LowerCallTo(CLI);
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005087 DAG.setRoot(Result.second);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005088 return 0;
Evan Cheng4da0c7c2011-04-08 21:37:21 +00005089 }
Shuxin Yang970755e2012-10-19 20:11:16 +00005090
Bill Wendlingef375462008-11-21 02:38:44 +00005091 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00005092 case Intrinsic::sadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00005093 case Intrinsic::usub_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00005094 case Intrinsic::ssub_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00005095 case Intrinsic::umul_with_overflow:
Craig Topperc42e6402012-04-11 04:34:11 +00005096 case Intrinsic::smul_with_overflow: {
5097 ISD::NodeType Op;
5098 switch (Intrinsic) {
5099 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
5100 case Intrinsic::uadd_with_overflow: Op = ISD::UADDO; break;
5101 case Intrinsic::sadd_with_overflow: Op = ISD::SADDO; break;
5102 case Intrinsic::usub_with_overflow: Op = ISD::USUBO; break;
5103 case Intrinsic::ssub_with_overflow: Op = ISD::SSUBO; break;
5104 case Intrinsic::umul_with_overflow: Op = ISD::UMULO; break;
5105 case Intrinsic::smul_with_overflow: Op = ISD::SMULO; break;
5106 }
5107 SDValue Op1 = getValue(I.getArgOperand(0));
5108 SDValue Op2 = getValue(I.getArgOperand(1));
Bill Wendling7cdc3c82008-11-21 02:03:52 +00005109
Craig Topperc42e6402012-04-11 04:34:11 +00005110 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
Craig Topper134f78c2012-11-24 23:05:23 +00005111 setValue(&I, DAG.getNode(Op, dl, VTs, Op1, Op2));
Craig Topperc42e6402012-04-11 04:34:11 +00005112 return 0;
5113 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005114 case Intrinsic::prefetch: {
Bruno Cardoso Lopes9a767332011-06-14 04:58:37 +00005115 SDValue Ops[5];
Dale Johannesen1de4aa92010-10-26 23:11:10 +00005116 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005117 Ops[0] = getRoot();
Gabor Greif0635f352010-06-25 09:38:13 +00005118 Ops[1] = getValue(I.getArgOperand(0));
5119 Ops[2] = getValue(I.getArgOperand(1));
5120 Ops[3] = getValue(I.getArgOperand(2));
Bruno Cardoso Lopes9a767332011-06-14 04:58:37 +00005121 Ops[4] = getValue(I.getArgOperand(3));
Dale Johannesen1de4aa92010-10-26 23:11:10 +00005122 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, dl,
5123 DAG.getVTList(MVT::Other),
Bruno Cardoso Lopes9a767332011-06-14 04:58:37 +00005124 &Ops[0], 5,
Dale Johannesen1de4aa92010-10-26 23:11:10 +00005125 EVT::getIntegerVT(*Context, 8),
5126 MachinePointerInfo(I.getArgOperand(0)),
5127 0, /* align */
5128 false, /* volatile */
5129 rw==0, /* read */
5130 rw==1)); /* write */
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005131 return 0;
5132 }
Duncan Sandsf07c9492009-11-10 09:08:09 +00005133 case Intrinsic::lifetime_start:
Nadav Rotemc05d3062012-09-06 09:17:37 +00005134 case Intrinsic::lifetime_end: {
Nadav Rotemc05d3062012-09-06 09:17:37 +00005135 bool IsStart = (Intrinsic == Intrinsic::lifetime_start);
Nadav Rotem9a2ae002012-09-10 08:43:23 +00005136 // Stack coloring is not enabled in O0, discard region information.
5137 if (TM.getOptLevel() == CodeGenOpt::None)
5138 return 0;
Nadav Rotemc05d3062012-09-06 09:17:37 +00005139
Nadav Rotem9a2ae002012-09-10 08:43:23 +00005140 SmallVector<Value *, 4> Allocas;
5141 GetUnderlyingObjects(I.getArgOperand(1), Allocas, TD);
5142
5143 for (SmallVector<Value*, 4>::iterator Object = Allocas.begin(),
5144 E = Allocas.end(); Object != E; ++Object) {
5145 AllocaInst *LifetimeObject = dyn_cast_or_null<AllocaInst>(*Object);
5146
5147 // Could not find an Alloca.
5148 if (!LifetimeObject)
5149 continue;
5150
5151 int FI = FuncInfo.StaticAllocaMap[LifetimeObject];
5152
5153 SDValue Ops[2];
5154 Ops[0] = getRoot();
5155 Ops[1] = DAG.getFrameIndex(FI, TLI.getPointerTy(), true);
5156 unsigned Opcode = (IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END);
5157
5158 Res = DAG.getNode(Opcode, dl, MVT::Other, Ops, 2);
5159 DAG.setRoot(Res);
5160 }
Nadav Rotemc05d3062012-09-06 09:17:37 +00005161 }
5162 case Intrinsic::invariant_start:
Duncan Sandsf07c9492009-11-10 09:08:09 +00005163 // Discard region information.
Bill Wendling4533cac2010-01-28 21:51:40 +00005164 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
Duncan Sandsf07c9492009-11-10 09:08:09 +00005165 return 0;
5166 case Intrinsic::invariant_end:
Duncan Sandsf07c9492009-11-10 09:08:09 +00005167 // Discard region information.
5168 return 0;
Nuno Lopes85b40892012-06-28 22:30:12 +00005169 case Intrinsic::donothing:
5170 // ignore
5171 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005172 }
5173}
5174
Dan Gohman46510a72010-04-15 01:51:59 +00005175void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
Dan Gohman2048b852009-11-23 18:04:58 +00005176 bool isTailCall,
5177 MachineBasicBlock *LandingPad) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005178 PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
5179 FunctionType *FTy = cast<FunctionType>(PT->getElementType());
5180 Type *RetTy = FTy->getReturnType();
Chris Lattner512063d2010-04-05 06:19:28 +00005181 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Chris Lattner16112732010-03-14 01:41:15 +00005182 MCSymbol *BeginLabel = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005183
5184 TargetLowering::ArgListTy Args;
5185 TargetLowering::ArgListEntry Entry;
5186 Args.reserve(CS.arg_size());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005187
5188 // Check whether the function can return without sret-demotion.
Dan Gohman84023e02010-07-10 09:00:22 +00005189 SmallVector<ISD::OutputArg, 4> Outs;
Dan Gohman84023e02010-07-10 09:00:22 +00005190 GetReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
Eli Friedman2db0e9e2012-05-25 00:09:29 +00005191 Outs, TLI);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005192
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005193 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
Bill Wendling96cb1122012-07-19 00:04:14 +00005194 DAG.getMachineFunction(),
5195 FTy->isVarArg(), Outs,
5196 FTy->getContext());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005197
5198 SDValue DemoteStackSlot;
Chris Lattnerecf42c42010-09-21 16:36:31 +00005199 int DemoteStackIdx = -100;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005200
5201 if (!CanLowerReturn) {
Micah Villmow3574eca2012-10-08 16:38:25 +00005202 uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005203 FTy->getReturnType());
Micah Villmow3574eca2012-10-08 16:38:25 +00005204 unsigned Align = TLI.getDataLayout()->getPrefTypeAlignment(
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005205 FTy->getReturnType());
5206 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattnerecf42c42010-09-21 16:36:31 +00005207 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005208 Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005209
Chris Lattnerecf42c42010-09-21 16:36:31 +00005210 DemoteStackSlot = DAG.getFrameIndex(DemoteStackIdx, TLI.getPointerTy());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005211 Entry.Node = DemoteStackSlot;
5212 Entry.Ty = StackSlotPtrType;
5213 Entry.isSExt = false;
5214 Entry.isZExt = false;
5215 Entry.isInReg = false;
5216 Entry.isSRet = true;
5217 Entry.isNest = false;
5218 Entry.isByVal = false;
5219 Entry.Alignment = Align;
5220 Args.push_back(Entry);
5221 RetTy = Type::getVoidTy(FTy->getContext());
5222 }
5223
Dan Gohman46510a72010-04-15 01:51:59 +00005224 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005225 i != e; ++i) {
Rafael Espindola3fa82832011-05-13 15:18:06 +00005226 const Value *V = *i;
5227
5228 // Skip empty types
5229 if (V->getType()->isEmptyTy())
5230 continue;
5231
5232 SDValue ArgNode = getValue(V);
5233 Entry.Node = ArgNode; Entry.Ty = V->getType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005234
5235 unsigned attrInd = i - CS.arg_begin() + 1;
Bill Wendling3e2d76c2012-10-09 21:38:14 +00005236 Entry.isSExt = CS.paramHasAttr(attrInd, Attributes::SExt);
5237 Entry.isZExt = CS.paramHasAttr(attrInd, Attributes::ZExt);
5238 Entry.isInReg = CS.paramHasAttr(attrInd, Attributes::InReg);
5239 Entry.isSRet = CS.paramHasAttr(attrInd, Attributes::StructRet);
5240 Entry.isNest = CS.paramHasAttr(attrInd, Attributes::Nest);
5241 Entry.isByVal = CS.paramHasAttr(attrInd, Attributes::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005242 Entry.Alignment = CS.getParamAlignment(attrInd);
5243 Args.push_back(Entry);
5244 }
5245
Chris Lattner512063d2010-04-05 06:19:28 +00005246 if (LandingPad) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005247 // Insert a label before the invoke call to mark the try range. This can be
5248 // used to detect deletion of the invoke via the MachineModuleInfo.
Chris Lattner512063d2010-04-05 06:19:28 +00005249 BeginLabel = MMI.getContext().CreateTempSymbol();
Jim Grosbach1b747ad2009-08-11 00:09:57 +00005250
Jim Grosbachca752c92010-01-28 01:45:32 +00005251 // For SjLj, keep track of which landing pads go with which invokes
5252 // so as to maintain the ordering of pads in the LSDA.
Chris Lattner512063d2010-04-05 06:19:28 +00005253 unsigned CallSiteIndex = MMI.getCurrentCallSite();
Jim Grosbachca752c92010-01-28 01:45:32 +00005254 if (CallSiteIndex) {
Chris Lattner512063d2010-04-05 06:19:28 +00005255 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
Bill Wendling30e67402011-10-05 22:24:35 +00005256 LPadToCallSiteMap[LandingPad].push_back(CallSiteIndex);
Bill Wendlinga8512ed2011-10-04 22:00:35 +00005257
Jim Grosbachca752c92010-01-28 01:45:32 +00005258 // Now that the call site is handled, stop tracking it.
Chris Lattner512063d2010-04-05 06:19:28 +00005259 MMI.setCurrentCallSite(0);
Jim Grosbachca752c92010-01-28 01:45:32 +00005260 }
5261
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005262 // Both PendingLoads and PendingExports must be flushed here;
5263 // this call might not return.
5264 (void)getRoot();
Chris Lattner7561d482010-03-14 02:33:54 +00005265 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getControlRoot(), BeginLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005266 }
5267
Dan Gohman98ca4f22009-08-05 01:29:28 +00005268 // Check if target-independent constraints permit a tail call here.
5269 // Target-dependent constraints are checked within TLI.LowerCallTo.
5270 if (isTailCall &&
Evan Cheng86809cc2010-02-03 03:28:02 +00005271 !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI))
Dan Gohman98ca4f22009-08-05 01:29:28 +00005272 isTailCall = false;
5273
Dan Gohmanbadcda42010-08-28 00:51:03 +00005274 // If there's a possibility that fast-isel has already selected some amount
5275 // of the current basic block, don't emit a tail call.
Nick Lewycky8a8d4792011-12-02 22:16:29 +00005276 if (isTailCall && TM.Options.EnableFastISel)
Dan Gohmanbadcda42010-08-28 00:51:03 +00005277 isTailCall = false;
5278
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00005279 TargetLowering::
5280 CallLoweringInfo CLI(getRoot(), RetTy, FTy, isTailCall, Callee, Args, DAG,
5281 getCurDebugLoc(), CS);
5282 std::pair<SDValue,SDValue> Result = TLI.LowerCallTo(CLI);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005283 assert((isTailCall || Result.second.getNode()) &&
5284 "Non-null chain expected with non-tail call!");
5285 assert((Result.second.getNode() || !Result.first.getNode()) &&
5286 "Null value expected with tail call!");
Bill Wendlinge80ae832009-12-22 00:50:32 +00005287 if (Result.first.getNode()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005288 setValue(CS.getInstruction(), Result.first);
Bill Wendlinge80ae832009-12-22 00:50:32 +00005289 } else if (!CanLowerReturn && Result.second.getNode()) {
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005290 // The instruction result is the result of loading from the
5291 // hidden sret parameter.
5292 SmallVector<EVT, 1> PVTs;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005293 Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005294
5295 ComputeValueVTs(TLI, PtrRetTy, PVTs);
5296 assert(PVTs.size() == 1 && "Pointers should fit in one register");
5297 EVT PtrVT = PVTs[0];
Eli Friedman2db0e9e2012-05-25 00:09:29 +00005298
5299 SmallVector<EVT, 4> RetTys;
5300 SmallVector<uint64_t, 4> Offsets;
5301 RetTy = FTy->getReturnType();
5302 ComputeValueVTs(TLI, RetTy, RetTys, &Offsets);
5303
5304 unsigned NumValues = RetTys.size();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005305 SmallVector<SDValue, 4> Values(NumValues);
5306 SmallVector<SDValue, 4> Chains(NumValues);
5307
5308 for (unsigned i = 0; i < NumValues; ++i) {
Bill Wendlinge80ae832009-12-22 00:50:32 +00005309 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
5310 DemoteStackSlot,
5311 DAG.getConstant(Offsets[i], PtrVT));
Eli Friedman2db0e9e2012-05-25 00:09:29 +00005312 SDValue L = DAG.getLoad(RetTys[i], getCurDebugLoc(), Result.second, Add,
Chris Lattnerecf42c42010-09-21 16:36:31 +00005313 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]),
Pete Cooperd752e0f2011-11-08 18:42:53 +00005314 false, false, false, 1);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005315 Values[i] = L;
5316 Chains[i] = L.getValue(1);
5317 }
Bill Wendlinge80ae832009-12-22 00:50:32 +00005318
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005319 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
5320 MVT::Other, &Chains[0], NumValues);
5321 PendingLoads.push_back(Chain);
Michael J. Spencere70c5262010-10-16 08:25:21 +00005322
Bill Wendling4533cac2010-01-28 21:51:40 +00005323 setValue(CS.getInstruction(),
5324 DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
5325 DAG.getVTList(&RetTys[0], RetTys.size()),
Eli Friedman2db0e9e2012-05-25 00:09:29 +00005326 &Values[0], Values.size()));
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005327 }
Bill Wendlinge80ae832009-12-22 00:50:32 +00005328
Evan Chengc249e482011-04-01 19:57:01 +00005329 // Assign order to nodes here. If the call does not produce a result, it won't
5330 // be mapped to a SDNode and visit() will not assign it an order number.
Evan Cheng8380c032011-04-01 19:42:22 +00005331 if (!Result.second.getNode()) {
Evan Chengc249e482011-04-01 19:57:01 +00005332 // As a special case, a null chain means that a tail call has been emitted and
5333 // the DAG root is already updated.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005334 HasTailCall = true;
Evan Cheng8380c032011-04-01 19:42:22 +00005335 ++SDNodeOrder;
5336 AssignOrderingToNode(DAG.getRoot().getNode());
5337 } else {
5338 DAG.setRoot(Result.second);
5339 ++SDNodeOrder;
5340 AssignOrderingToNode(Result.second.getNode());
5341 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005342
Chris Lattner512063d2010-04-05 06:19:28 +00005343 if (LandingPad) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005344 // Insert a label at the end of the invoke call to mark the try range. This
5345 // can be used to detect deletion of the invoke via the MachineModuleInfo.
Chris Lattner512063d2010-04-05 06:19:28 +00005346 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
Chris Lattner7561d482010-03-14 02:33:54 +00005347 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getRoot(), EndLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005348
5349 // Inform MachineModuleInfo of range.
Chris Lattner512063d2010-04-05 06:19:28 +00005350 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005351 }
5352}
5353
Chris Lattner8047d9a2009-12-24 00:37:38 +00005354/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5355/// value is equal or not-equal to zero.
Dan Gohman46510a72010-04-15 01:51:59 +00005356static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
5357 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
Chris Lattner8047d9a2009-12-24 00:37:38 +00005358 UI != E; ++UI) {
Dan Gohman46510a72010-04-15 01:51:59 +00005359 if (const ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
Chris Lattner8047d9a2009-12-24 00:37:38 +00005360 if (IC->isEquality())
Dan Gohman46510a72010-04-15 01:51:59 +00005361 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
Chris Lattner8047d9a2009-12-24 00:37:38 +00005362 if (C->isNullValue())
5363 continue;
5364 // Unknown instruction.
5365 return false;
5366 }
5367 return true;
5368}
5369
Dan Gohman46510a72010-04-15 01:51:59 +00005370static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005371 Type *LoadTy,
Chris Lattner8047d9a2009-12-24 00:37:38 +00005372 SelectionDAGBuilder &Builder) {
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005373
Chris Lattner8047d9a2009-12-24 00:37:38 +00005374 // Check to see if this load can be trivially constant folded, e.g. if the
5375 // input is from a string literal.
Dan Gohman46510a72010-04-15 01:51:59 +00005376 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
Chris Lattner8047d9a2009-12-24 00:37:38 +00005377 // Cast pointer to the type we really want to load.
Dan Gohman46510a72010-04-15 01:51:59 +00005378 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
Chris Lattner8047d9a2009-12-24 00:37:38 +00005379 PointerType::getUnqual(LoadTy));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005380
Dan Gohman46510a72010-04-15 01:51:59 +00005381 if (const Constant *LoadCst =
5382 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
5383 Builder.TD))
Chris Lattner8047d9a2009-12-24 00:37:38 +00005384 return Builder.getValue(LoadCst);
5385 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005386
Chris Lattner8047d9a2009-12-24 00:37:38 +00005387 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
5388 // still constant memory, the input chain can be the entry node.
5389 SDValue Root;
5390 bool ConstantMemory = false;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005391
Chris Lattner8047d9a2009-12-24 00:37:38 +00005392 // Do not serialize (non-volatile) loads of constant memory with anything.
5393 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5394 Root = Builder.DAG.getEntryNode();
5395 ConstantMemory = true;
5396 } else {
5397 // Do not serialize non-volatile loads against each other.
5398 Root = Builder.DAG.getRoot();
5399 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005400
Chris Lattner8047d9a2009-12-24 00:37:38 +00005401 SDValue Ptr = Builder.getValue(PtrVal);
5402 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root,
Chris Lattnerecf42c42010-09-21 16:36:31 +00005403 Ptr, MachinePointerInfo(PtrVal),
David Greene1e559442010-02-15 17:00:31 +00005404 false /*volatile*/,
Pete Cooperd752e0f2011-11-08 18:42:53 +00005405 false /*nontemporal*/,
5406 false /*isinvariant*/, 1 /* align=1 */);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005407
Chris Lattner8047d9a2009-12-24 00:37:38 +00005408 if (!ConstantMemory)
5409 Builder.PendingLoads.push_back(LoadVal.getValue(1));
5410 return LoadVal;
5411}
5412
5413
5414/// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5415/// If so, return true and lower it, otherwise return false and it will be
5416/// lowered like a normal call.
Dan Gohman46510a72010-04-15 01:51:59 +00005417bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
Chris Lattner8047d9a2009-12-24 00:37:38 +00005418 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
Gabor Greif37387d52010-06-30 12:55:46 +00005419 if (I.getNumArgOperands() != 3)
Chris Lattner8047d9a2009-12-24 00:37:38 +00005420 return false;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005421
Gabor Greif0635f352010-06-25 09:38:13 +00005422 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
Duncan Sands1df98592010-02-16 11:11:14 +00005423 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
Gabor Greif0635f352010-06-25 09:38:13 +00005424 !I.getArgOperand(2)->getType()->isIntegerTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00005425 !I.getType()->isIntegerTy())
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005426 return false;
5427
Gabor Greif0635f352010-06-25 09:38:13 +00005428 const ConstantInt *Size = dyn_cast<ConstantInt>(I.getArgOperand(2));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005429
Chris Lattner8047d9a2009-12-24 00:37:38 +00005430 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
5431 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
Chris Lattner04b091a2009-12-24 01:07:17 +00005432 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) {
5433 bool ActuallyDoIt = true;
5434 MVT LoadVT;
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005435 Type *LoadTy;
Chris Lattner04b091a2009-12-24 01:07:17 +00005436 switch (Size->getZExtValue()) {
5437 default:
5438 LoadVT = MVT::Other;
5439 LoadTy = 0;
5440 ActuallyDoIt = false;
5441 break;
5442 case 2:
5443 LoadVT = MVT::i16;
5444 LoadTy = Type::getInt16Ty(Size->getContext());
5445 break;
5446 case 4:
5447 LoadVT = MVT::i32;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005448 LoadTy = Type::getInt32Ty(Size->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00005449 break;
5450 case 8:
5451 LoadVT = MVT::i64;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005452 LoadTy = Type::getInt64Ty(Size->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00005453 break;
5454 /*
5455 case 16:
5456 LoadVT = MVT::v4i32;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005457 LoadTy = Type::getInt32Ty(Size->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00005458 LoadTy = VectorType::get(LoadTy, 4);
5459 break;
5460 */
5461 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005462
Chris Lattner04b091a2009-12-24 01:07:17 +00005463 // This turns into unaligned loads. We only do this if the target natively
5464 // supports the MVT we'll be loading or if it is small enough (<= 4) that
5465 // we'll only produce a small number of byte loads.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005466
Chris Lattner04b091a2009-12-24 01:07:17 +00005467 // Require that we can find a legal MVT, and only do this if the target
5468 // supports unaligned loads of that type. Expanding into byte loads would
5469 // bloat the code.
5470 if (ActuallyDoIt && Size->getZExtValue() > 4) {
5471 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5472 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
5473 if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT))
5474 ActuallyDoIt = false;
5475 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005476
Chris Lattner04b091a2009-12-24 01:07:17 +00005477 if (ActuallyDoIt) {
5478 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5479 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005480
Chris Lattner04b091a2009-12-24 01:07:17 +00005481 SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal,
5482 ISD::SETNE);
5483 EVT CallVT = TLI.getValueType(I.getType(), true);
5484 setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT));
5485 return true;
5486 }
Chris Lattner8047d9a2009-12-24 00:37:38 +00005487 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005488
5489
Chris Lattner8047d9a2009-12-24 00:37:38 +00005490 return false;
5491}
5492
Bob Wilson53624a22012-08-03 23:29:17 +00005493/// visitUnaryFloatCall - If a call instruction is a unary floating-point
5494/// operation (as expected), translate it to an SDNode with the specified opcode
5495/// and return true.
5496bool SelectionDAGBuilder::visitUnaryFloatCall(const CallInst &I,
5497 unsigned Opcode) {
5498 // Sanity check that it really is a unary floating-point call.
5499 if (I.getNumArgOperands() != 1 ||
5500 !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
5501 I.getType() != I.getArgOperand(0)->getType() ||
5502 !I.onlyReadsMemory())
5503 return false;
5504
5505 SDValue Tmp = getValue(I.getArgOperand(0));
5506 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(), Tmp.getValueType(), Tmp));
5507 return true;
5508}
Chris Lattner8047d9a2009-12-24 00:37:38 +00005509
Dan Gohman46510a72010-04-15 01:51:59 +00005510void SelectionDAGBuilder::visitCall(const CallInst &I) {
Chris Lattner598751e2010-07-05 05:36:21 +00005511 // Handle inline assembly differently.
5512 if (isa<InlineAsm>(I.getCalledValue())) {
5513 visitInlineAsm(&I);
5514 return;
5515 }
Michael J. Spencere70c5262010-10-16 08:25:21 +00005516
Michael J. Spencer391b43b2010-10-21 20:49:23 +00005517 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Michael J. Spencerc9c137b2012-02-22 19:06:13 +00005518 ComputeUsesVAFloatArgument(I, &MMI);
Michael J. Spencer391b43b2010-10-21 20:49:23 +00005519
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005520 const char *RenameFn = 0;
5521 if (Function *F = I.getCalledFunction()) {
5522 if (F->isDeclaration()) {
Chris Lattner598751e2010-07-05 05:36:21 +00005523 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
Dale Johannesen49de9822009-02-05 01:49:45 +00005524 if (unsigned IID = II->getIntrinsicID(F)) {
5525 RenameFn = visitIntrinsicCall(I, IID);
5526 if (!RenameFn)
5527 return;
5528 }
5529 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005530 if (unsigned IID = F->getIntrinsicID()) {
5531 RenameFn = visitIntrinsicCall(I, IID);
5532 if (!RenameFn)
5533 return;
5534 }
5535 }
5536
5537 // Check for well-known libc/libm calls. If the function is internal, it
5538 // can't be a library call.
Bob Wilson982dc842012-08-03 21:26:24 +00005539 LibFunc::Func Func;
5540 if (!F->hasLocalLinkage() && F->hasName() &&
5541 LibInfo->getLibFunc(F->getName(), Func) &&
5542 LibInfo->hasOptimizedCodeGen(Func)) {
5543 switch (Func) {
5544 default: break;
5545 case LibFunc::copysign:
5546 case LibFunc::copysignf:
5547 case LibFunc::copysignl:
Gabor Greif37387d52010-06-30 12:55:46 +00005548 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
Gabor Greif0635f352010-06-25 09:38:13 +00005549 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5550 I.getType() == I.getArgOperand(0)->getType() &&
Bob Wilson53624a22012-08-03 23:29:17 +00005551 I.getType() == I.getArgOperand(1)->getType() &&
5552 I.onlyReadsMemory()) {
Gabor Greif0635f352010-06-25 09:38:13 +00005553 SDValue LHS = getValue(I.getArgOperand(0));
5554 SDValue RHS = getValue(I.getArgOperand(1));
Bill Wendling0d580132009-12-23 01:28:19 +00005555 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
5556 LHS.getValueType(), LHS, RHS));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005557 return;
5558 }
Bob Wilson982dc842012-08-03 21:26:24 +00005559 break;
5560 case LibFunc::fabs:
5561 case LibFunc::fabsf:
5562 case LibFunc::fabsl:
Bob Wilson53624a22012-08-03 23:29:17 +00005563 if (visitUnaryFloatCall(I, ISD::FABS))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005564 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005565 break;
5566 case LibFunc::sin:
5567 case LibFunc::sinf:
5568 case LibFunc::sinl:
Bob Wilson53624a22012-08-03 23:29:17 +00005569 if (visitUnaryFloatCall(I, ISD::FSIN))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005570 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005571 break;
5572 case LibFunc::cos:
5573 case LibFunc::cosf:
5574 case LibFunc::cosl:
Bob Wilson53624a22012-08-03 23:29:17 +00005575 if (visitUnaryFloatCall(I, ISD::FCOS))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005576 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005577 break;
5578 case LibFunc::sqrt:
5579 case LibFunc::sqrtf:
5580 case LibFunc::sqrtl:
Bob Wilson53624a22012-08-03 23:29:17 +00005581 if (visitUnaryFloatCall(I, ISD::FSQRT))
Dale Johannesen52fb79b2009-09-25 17:23:22 +00005582 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005583 break;
5584 case LibFunc::floor:
5585 case LibFunc::floorf:
5586 case LibFunc::floorl:
Bob Wilson53624a22012-08-03 23:29:17 +00005587 if (visitUnaryFloatCall(I, ISD::FFLOOR))
Owen Anderson4a4fdf32011-12-08 19:32:14 +00005588 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005589 break;
5590 case LibFunc::nearbyint:
5591 case LibFunc::nearbyintf:
5592 case LibFunc::nearbyintl:
Bob Wilson53624a22012-08-03 23:29:17 +00005593 if (visitUnaryFloatCall(I, ISD::FNEARBYINT))
Owen Anderson4a4fdf32011-12-08 19:32:14 +00005594 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005595 break;
5596 case LibFunc::ceil:
5597 case LibFunc::ceilf:
5598 case LibFunc::ceill:
Bob Wilson53624a22012-08-03 23:29:17 +00005599 if (visitUnaryFloatCall(I, ISD::FCEIL))
Owen Anderson4a4fdf32011-12-08 19:32:14 +00005600 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005601 break;
5602 case LibFunc::rint:
5603 case LibFunc::rintf:
5604 case LibFunc::rintl:
Bob Wilson53624a22012-08-03 23:29:17 +00005605 if (visitUnaryFloatCall(I, ISD::FRINT))
Owen Anderson4a4fdf32011-12-08 19:32:14 +00005606 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005607 break;
5608 case LibFunc::trunc:
5609 case LibFunc::truncf:
5610 case LibFunc::truncl:
Bob Wilson53624a22012-08-03 23:29:17 +00005611 if (visitUnaryFloatCall(I, ISD::FTRUNC))
Owen Anderson4a4fdf32011-12-08 19:32:14 +00005612 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005613 break;
5614 case LibFunc::log2:
5615 case LibFunc::log2f:
5616 case LibFunc::log2l:
Bob Wilson53624a22012-08-03 23:29:17 +00005617 if (visitUnaryFloatCall(I, ISD::FLOG2))
Owen Anderson4e0adfa2011-12-15 00:54:12 +00005618 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005619 break;
5620 case LibFunc::exp2:
5621 case LibFunc::exp2f:
5622 case LibFunc::exp2l:
Bob Wilson53624a22012-08-03 23:29:17 +00005623 if (visitUnaryFloatCall(I, ISD::FEXP2))
Owen Anderson4e0adfa2011-12-15 00:54:12 +00005624 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005625 break;
5626 case LibFunc::memcmp:
Chris Lattner8047d9a2009-12-24 00:37:38 +00005627 if (visitMemCmpCall(I))
5628 return;
Bob Wilson982dc842012-08-03 21:26:24 +00005629 break;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005630 }
5631 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005632 }
Michael J. Spencere70c5262010-10-16 08:25:21 +00005633
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005634 SDValue Callee;
5635 if (!RenameFn)
Gabor Greif0635f352010-06-25 09:38:13 +00005636 Callee = getValue(I.getCalledValue());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005637 else
Bill Wendling056292f2008-09-16 21:48:12 +00005638 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005639
Bill Wendling0d580132009-12-23 01:28:19 +00005640 // Check if we can potentially perform a tail call. More detailed checking is
5641 // be done within LowerCallTo, after more information about the call is known.
Evan Cheng11e67932010-01-26 23:13:04 +00005642 LowerCallTo(&I, Callee, I.isTailCall());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005643}
5644
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00005645namespace {
Dan Gohman462f6b52010-05-29 17:53:24 +00005646
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005647/// AsmOperandInfo - This contains information for each constraint that we are
5648/// lowering.
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00005649class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
Cedric Venetaff9c272009-02-14 16:06:42 +00005650public:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005651 /// CallOperand - If this is the result output operand or a clobber
5652 /// this is null, otherwise it is the incoming operand to the CallInst.
5653 /// This gets modified as the asm is processed.
5654 SDValue CallOperand;
5655
5656 /// AssignedRegs - If this is a register or register class operand, this
5657 /// contains the set of register corresponding to the operand.
5658 RegsForValue AssignedRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005659
John Thompsoneac6e1d2010-09-13 18:15:37 +00005660 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005661 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
5662 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005663
Owen Andersone50ed302009-08-10 22:56:29 +00005664 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
Chris Lattner81249c92008-10-17 17:05:25 +00005665 /// corresponds to. If there is no Value* for this operand, it returns
Owen Anderson825b72b2009-08-11 20:47:22 +00005666 /// MVT::Other.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005667 EVT getCallOperandValEVT(LLVMContext &Context,
Owen Anderson1d0be152009-08-13 21:58:54 +00005668 const TargetLowering &TLI,
Micah Villmow3574eca2012-10-08 16:38:25 +00005669 const DataLayout *TD) const {
Owen Anderson825b72b2009-08-11 20:47:22 +00005670 if (CallOperandVal == 0) return MVT::Other;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005671
Chris Lattner81249c92008-10-17 17:05:25 +00005672 if (isa<BasicBlock>(CallOperandVal))
5673 return TLI.getPointerTy();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005674
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005675 llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005676
Eric Christophercef81b72011-05-09 20:04:43 +00005677 // FIXME: code duplicated from TargetLowering::ParseConstraints().
Chris Lattner81249c92008-10-17 17:05:25 +00005678 // If this is an indirect operand, the operand is a pointer to the
5679 // accessed type.
Bob Wilsone261b0c2009-12-22 18:34:19 +00005680 if (isIndirect) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005681 llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
Bob Wilsone261b0c2009-12-22 18:34:19 +00005682 if (!PtrTy)
Chris Lattner75361b62010-04-07 22:58:41 +00005683 report_fatal_error("Indirect operand for inline asm not a pointer!");
Bob Wilsone261b0c2009-12-22 18:34:19 +00005684 OpTy = PtrTy->getElementType();
5685 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005686
Eric Christophercef81b72011-05-09 20:04:43 +00005687 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005688 if (StructType *STy = dyn_cast<StructType>(OpTy))
Eric Christophercef81b72011-05-09 20:04:43 +00005689 if (STy->getNumElements() == 1)
5690 OpTy = STy->getElementType(0);
5691
Chris Lattner81249c92008-10-17 17:05:25 +00005692 // If OpTy is not a single value, it may be a struct/union that we
5693 // can tile with integers.
5694 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5695 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
5696 switch (BitSize) {
5697 default: break;
5698 case 1:
5699 case 8:
5700 case 16:
5701 case 32:
5702 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00005703 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00005704 OpTy = IntegerType::get(Context, BitSize);
Chris Lattner81249c92008-10-17 17:05:25 +00005705 break;
5706 }
5707 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005708
Chris Lattner81249c92008-10-17 17:05:25 +00005709 return TLI.getValueType(OpTy, true);
5710 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005711};
Dan Gohman462f6b52010-05-29 17:53:24 +00005712
John Thompson44ab89e2010-10-29 17:29:13 +00005713typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
5714
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00005715} // end anonymous namespace
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005716
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005717/// GetRegistersForValue - Assign registers (virtual or physical) for the
5718/// specified operand. We prefer to assign virtual registers, to allow the
Bob Wilson266d9452009-12-17 05:07:36 +00005719/// register allocator to handle the assignment process. However, if the asm
5720/// uses features that we can't model on machineinstrs, we have SDISel do the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005721/// allocation. This produces generally horrible, but correct, code.
5722///
5723/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005724///
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00005725static void GetRegistersForValue(SelectionDAG &DAG,
5726 const TargetLowering &TLI,
5727 DebugLoc DL,
Benjamin Kramer8b93ff22012-02-24 14:01:17 +00005728 SDISelAsmOperandInfo &OpInfo) {
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00005729 LLVMContext &Context = *DAG.getContext();
Owen Anderson23b9b192009-08-12 00:36:31 +00005730
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005731 MachineFunction &MF = DAG.getMachineFunction();
5732 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005733
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005734 // If this is a constraint for a single physreg, or a constraint for a
5735 // register class, find it.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005736 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005737 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5738 OpInfo.ConstraintVT);
5739
5740 unsigned NumRegs = 1;
Owen Anderson825b72b2009-08-11 20:47:22 +00005741 if (OpInfo.ConstraintVT != MVT::Other) {
Chris Lattner01426e12008-10-21 00:45:36 +00005742 // If this is a FP input in an integer register (or visa versa) insert a bit
5743 // cast of the input value. More generally, handle any case where the input
5744 // value disagrees with the register class we plan to stick this in.
5745 if (OpInfo.Type == InlineAsm::isInput &&
5746 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
Owen Andersone50ed302009-08-10 22:56:29 +00005747 // Try to convert to the first EVT that the reg class contains. If the
Chris Lattner01426e12008-10-21 00:45:36 +00005748 // types are identical size, use a bitcast to convert (e.g. two differing
5749 // vector types).
Owen Andersone50ed302009-08-10 22:56:29 +00005750 EVT RegVT = *PhysReg.second->vt_begin();
Chris Lattner01426e12008-10-21 00:45:36 +00005751 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00005752 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005753 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00005754 OpInfo.ConstraintVT = RegVT;
5755 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5756 // If the input is a FP value and we want it in FP registers, do a
5757 // bitcast to the corresponding integer type. This turns an f64 value
5758 // into i64, which can be passed with two i32 values on a 32-bit
5759 // machine.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005760 RegVT = EVT::getIntegerVT(Context,
Owen Anderson23b9b192009-08-12 00:36:31 +00005761 OpInfo.ConstraintVT.getSizeInBits());
Benjamin Kramer7d706ed2011-03-26 16:35:10 +00005762 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005763 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00005764 OpInfo.ConstraintVT = RegVT;
5765 }
5766 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005767
Owen Anderson23b9b192009-08-12 00:36:31 +00005768 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00005769 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005770
Owen Andersone50ed302009-08-10 22:56:29 +00005771 EVT RegVT;
5772 EVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005773
5774 // If this is a constraint for a specific physical register, like {r17},
5775 // assign it now.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005776 if (unsigned AssignedReg = PhysReg.first) {
5777 const TargetRegisterClass *RC = PhysReg.second;
Owen Anderson825b72b2009-08-11 20:47:22 +00005778 if (OpInfo.ConstraintVT == MVT::Other)
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005779 ValueVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005780
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005781 // Get the actual register value type. This is important, because the user
5782 // may have asked for (e.g.) the AX register in i32 type. We need to
5783 // remember that AX is actually i16 to get the right extension.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005784 RegVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005785
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005786 // This is a explicit reference to a physical register.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005787 Regs.push_back(AssignedReg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005788
5789 // If this is an expanded reference, add the rest of the regs to Regs.
5790 if (NumRegs != 1) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005791 TargetRegisterClass::iterator I = RC->begin();
5792 for (; *I != AssignedReg; ++I)
5793 assert(I != RC->end() && "Didn't find reg!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005794
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005795 // Already added the first reg.
5796 --NumRegs; ++I;
5797 for (; NumRegs; --NumRegs, ++I) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005798 assert(I != RC->end() && "Ran out of registers to allocate!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005799 Regs.push_back(*I);
5800 }
5801 }
Bill Wendling651ad132009-12-22 01:25:10 +00005802
Dan Gohman7451d3e2010-05-29 17:03:36 +00005803 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005804 return;
5805 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005806
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005807 // Otherwise, if this was a reference to an LLVM register class, create vregs
5808 // for this reference.
Chris Lattnerb3b44842009-03-24 15:25:07 +00005809 if (const TargetRegisterClass *RC = PhysReg.second) {
5810 RegVT = *RC->vt_begin();
Owen Anderson825b72b2009-08-11 20:47:22 +00005811 if (OpInfo.ConstraintVT == MVT::Other)
Evan Chengfb112882009-03-23 08:01:15 +00005812 ValueVT = RegVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005813
Evan Chengfb112882009-03-23 08:01:15 +00005814 // Create the appropriate number of virtual registers.
5815 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5816 for (; NumRegs; --NumRegs)
Chris Lattnerb3b44842009-03-24 15:25:07 +00005817 Regs.push_back(RegInfo.createVirtualRegister(RC));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005818
Dan Gohman7451d3e2010-05-29 17:03:36 +00005819 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
Evan Chengfb112882009-03-23 08:01:15 +00005820 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005821 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005822
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005823 // Otherwise, we couldn't allocate enough registers for this.
5824}
5825
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005826/// visitInlineAsm - Handle a call to an InlineAsm object.
5827///
Dan Gohman46510a72010-04-15 01:51:59 +00005828void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
5829 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005830
5831 /// ConstraintOperands - Information about all of the constraints.
John Thompson44ab89e2010-10-29 17:29:13 +00005832 SDISelAsmOperandInfoVector ConstraintOperands;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005833
Evan Chengce1cdac2011-05-06 20:52:23 +00005834 TargetLowering::AsmOperandInfoVector
5835 TargetConstraints = TLI.ParseConstraints(CS);
5836
John Thompsoneac6e1d2010-09-13 18:15:37 +00005837 bool hasMemory = false;
Michael J. Spencere70c5262010-10-16 08:25:21 +00005838
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005839 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5840 unsigned ResNo = 0; // ResNo - The result number of the next output.
John Thompsoneac6e1d2010-09-13 18:15:37 +00005841 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
5842 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005843 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Michael J. Spencere70c5262010-10-16 08:25:21 +00005844
Owen Anderson825b72b2009-08-11 20:47:22 +00005845 EVT OpVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005846
5847 // Compute the value type for each operand.
5848 switch (OpInfo.Type) {
5849 case InlineAsm::isOutput:
5850 // Indirect outputs just consume an argument.
5851 if (OpInfo.isIndirect) {
Dan Gohman46510a72010-04-15 01:51:59 +00005852 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005853 break;
5854 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005855
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005856 // The return value of the call is this value. As such, there is no
5857 // corresponding argument.
Nick Lewycky8de34002011-09-30 22:19:53 +00005858 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005859 if (StructType *STy = dyn_cast<StructType>(CS.getType())) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005860 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5861 } else {
5862 assert(ResNo == 0 && "Asm only has one result!");
5863 OpVT = TLI.getValueType(CS.getType());
5864 }
5865 ++ResNo;
5866 break;
5867 case InlineAsm::isInput:
Dan Gohman46510a72010-04-15 01:51:59 +00005868 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005869 break;
5870 case InlineAsm::isClobber:
5871 // Nothing to do.
5872 break;
5873 }
5874
5875 // If this is an input or an indirect output, process the call argument.
5876 // BasicBlocks are labels, currently appearing only in asm's.
5877 if (OpInfo.CallOperandVal) {
Dan Gohman46510a72010-04-15 01:51:59 +00005878 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005879 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00005880 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005881 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005882 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005883
Owen Anderson1d0be152009-08-13 21:58:54 +00005884 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005885 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005886
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005887 OpInfo.ConstraintVT = OpVT;
Michael J. Spencere70c5262010-10-16 08:25:21 +00005888
John Thompsoneac6e1d2010-09-13 18:15:37 +00005889 // Indirect operand accesses access memory.
5890 if (OpInfo.isIndirect)
5891 hasMemory = true;
5892 else {
5893 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
Evan Chengce1cdac2011-05-06 20:52:23 +00005894 TargetLowering::ConstraintType
5895 CType = TLI.getConstraintType(OpInfo.Codes[j]);
John Thompsoneac6e1d2010-09-13 18:15:37 +00005896 if (CType == TargetLowering::C_Memory) {
5897 hasMemory = true;
5898 break;
5899 }
5900 }
5901 }
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005902 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005903
John Thompsoneac6e1d2010-09-13 18:15:37 +00005904 SDValue Chain, Flag;
5905
5906 // We won't need to flush pending loads if this asm doesn't touch
5907 // memory and is nonvolatile.
5908 if (hasMemory || IA->hasSideEffects())
5909 Chain = getRoot();
5910 else
5911 Chain = DAG.getRoot();
5912
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005913 // Second pass over the constraints: compute which constraint option to use
5914 // and assign registers to constraints that want a specific physreg.
John Thompsoneac6e1d2010-09-13 18:15:37 +00005915 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005916 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005917
John Thompson54584742010-09-24 22:24:05 +00005918 // If this is an output operand with a matching input operand, look up the
5919 // matching input. If their types mismatch, e.g. one is an integer, the
5920 // other is floating point, or their sizes are different, flag it as an
5921 // error.
5922 if (OpInfo.hasMatchingInput()) {
5923 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
Michael J. Spencere70c5262010-10-16 08:25:21 +00005924
John Thompson54584742010-09-24 22:24:05 +00005925 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Bill Wendling96cb1122012-07-19 00:04:14 +00005926 std::pair<unsigned, const TargetRegisterClass*> MatchRC =
5927 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
Evan Cheng1dafa702011-08-23 19:17:21 +00005928 OpInfo.ConstraintVT);
Bill Wendling96cb1122012-07-19 00:04:14 +00005929 std::pair<unsigned, const TargetRegisterClass*> InputRC =
5930 TLI.getRegForInlineAsmConstraint(Input.ConstraintCode,
Evan Cheng1dafa702011-08-23 19:17:21 +00005931 Input.ConstraintVT);
John Thompson54584742010-09-24 22:24:05 +00005932 if ((OpInfo.ConstraintVT.isInteger() !=
5933 Input.ConstraintVT.isInteger()) ||
Eric Christopher5427ede2011-07-14 20:13:52 +00005934 (MatchRC.second != InputRC.second)) {
John Thompson54584742010-09-24 22:24:05 +00005935 report_fatal_error("Unsupported asm: input constraint"
5936 " with a matching output constraint of"
5937 " incompatible type!");
5938 }
5939 Input.ConstraintVT = OpInfo.ConstraintVT;
5940 }
5941 }
5942
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005943 // Compute the constraint code and ConstraintType to use.
Dale Johannesen1784d162010-06-25 21:55:36 +00005944 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005945
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005946 // If this is a memory input, and if the operand is not indirect, do what we
5947 // need to to provide an address for the memory input.
5948 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5949 !OpInfo.isIndirect) {
Evan Chengce1cdac2011-05-06 20:52:23 +00005950 assert((OpInfo.isMultipleAlternative ||
5951 (OpInfo.Type == InlineAsm::isInput)) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005952 "Can only indirectify direct input operands!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005953
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005954 // Memory operands really want the address of the value. If we don't have
5955 // an indirect input, put it in the constpool if we can, otherwise spill
5956 // it to a stack slot.
Eric Christophere0b42c02011-06-03 17:21:23 +00005957 // TODO: This isn't quite right. We need to handle these according to
5958 // the addressing mode that the constraint wants. Also, this may take
5959 // an additional register for the computation and we don't want that
5960 // either.
Eric Christopher471e4222011-06-08 23:55:35 +00005961
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005962 // If the operand is a float, integer, or vector constant, spill to a
5963 // constant pool entry to get its address.
Dan Gohman46510a72010-04-15 01:51:59 +00005964 const Value *OpVal = OpInfo.CallOperandVal;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005965 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
Chris Lattnera78fa8c2012-01-27 03:08:05 +00005966 isa<ConstantVector>(OpVal) || isa<ConstantDataVector>(OpVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005967 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5968 TLI.getPointerTy());
5969 } else {
5970 // Otherwise, create a stack slot and emit a store to it before the
5971 // asm.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00005972 Type *Ty = OpVal->getType();
Micah Villmow3574eca2012-10-08 16:38:25 +00005973 uint64_t TySize = TLI.getDataLayout()->getTypeAllocSize(Ty);
5974 unsigned Align = TLI.getDataLayout()->getPrefTypeAlignment(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005975 MachineFunction &MF = DAG.getMachineFunction();
David Greene3f2bf852009-11-12 20:49:22 +00005976 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005977 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Dale Johannesen66978ee2009-01-31 02:22:37 +00005978 Chain = DAG.getStore(Chain, getCurDebugLoc(),
Chris Lattnerecf42c42010-09-21 16:36:31 +00005979 OpInfo.CallOperand, StackSlot,
5980 MachinePointerInfo::getFixedStack(SSFI),
David Greene1e559442010-02-15 17:00:31 +00005981 false, false, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005982 OpInfo.CallOperand = StackSlot;
5983 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005984
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005985 // There is no longer a Value* corresponding to this operand.
5986 OpInfo.CallOperandVal = 0;
Bill Wendling651ad132009-12-22 01:25:10 +00005987
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005988 // It is now an indirect operand.
5989 OpInfo.isIndirect = true;
5990 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005991
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005992 // If this constraint is for a specific register, allocate it before
5993 // anything else.
5994 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Benjamin Kramer8b93ff22012-02-24 14:01:17 +00005995 GetRegistersForValue(DAG, TLI, getCurDebugLoc(), OpInfo);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005996 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005997
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005998 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00005999 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006000 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6001 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006002
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006003 // C_Register operands have already been allocated, Other/Memory don't need
6004 // to be.
6005 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Benjamin Kramer8b93ff22012-02-24 14:01:17 +00006006 GetRegistersForValue(DAG, TLI, getCurDebugLoc(), OpInfo);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006007 }
6008
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006009 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
6010 std::vector<SDValue> AsmNodeOperands;
6011 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
6012 AsmNodeOperands.push_back(
Dan Gohmanf2d7fb32010-01-04 21:00:54 +00006013 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
6014 TLI.getPointerTy()));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006015
Chris Lattnerdecc2672010-04-07 05:20:54 +00006016 // If we have a !srcloc metadata node associated with it, we want to attach
6017 // this to the ultimately generated inline asm machineinstr. To do this, we
6018 // pass in the third operand as this (potentially null) inline asm MDNode.
6019 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
6020 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006021
Chad Rosier3d716882012-10-30 19:11:54 +00006022 // Remember the HasSideEffect, AlignStack, AsmDialect, MayLoad and MayStore
6023 // bits as operand 3.
Evan Chengc36b7062011-01-07 23:50:32 +00006024 unsigned ExtraInfo = 0;
6025 if (IA->hasSideEffects())
6026 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
6027 if (IA->isAlignStack())
6028 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
Chad Rosier77fffa62012-09-05 22:17:43 +00006029 // Set the asm dialect.
Chad Rosier2f1d8152012-09-05 22:40:13 +00006030 ExtraInfo |= IA->getDialect() * InlineAsm::Extra_AsmDialect;
Chad Rosier3d716882012-10-30 19:11:54 +00006031
6032 // Determine if this InlineAsm MayLoad or MayStore based on the constraints.
6033 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
6034 TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
6035
6036 // Compute the constraint code and ConstraintType to use.
6037 TLI.ComputeConstraintToUse(OpInfo, SDValue());
6038
Chad Rosierdfa4cec2012-10-30 20:01:12 +00006039 // Ideally, we would only check against memory constraints. However, the
6040 // meaning of an other constraint can be target-specific and we can't easily
6041 // reason about it. Therefore, be conservative and set MayLoad/MayStore
6042 // for other constriants as well.
Chad Rosier3d716882012-10-30 19:11:54 +00006043 if (OpInfo.ConstraintType == TargetLowering::C_Memory ||
6044 OpInfo.ConstraintType == TargetLowering::C_Other) {
6045 if (OpInfo.Type == InlineAsm::isInput)
6046 ExtraInfo |= InlineAsm::Extra_MayLoad;
6047 else if (OpInfo.Type == InlineAsm::isOutput)
6048 ExtraInfo |= InlineAsm::Extra_MayStore;
6049 }
6050 }
6051
Evan Chengc36b7062011-01-07 23:50:32 +00006052 AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
6053 TLI.getPointerTy()));
Dale Johannesenf1e309e2010-07-02 20:16:09 +00006054
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006055 // Loop over all of the inputs, copying the operand values into the
6056 // appropriate registers and processing the output regs.
6057 RegsForValue RetValRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006058
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006059 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
6060 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006061
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006062 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
6063 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
6064
6065 switch (OpInfo.Type) {
6066 case InlineAsm::isOutput: {
6067 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
6068 OpInfo.ConstraintType != TargetLowering::C_Register) {
6069 // Memory output, or 'other' output (e.g. 'X' constraint).
6070 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
6071
6072 // Add information to the INLINEASM node to know about this output.
Chris Lattnerdecc2672010-04-07 05:20:54 +00006073 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6074 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006075 TLI.getPointerTy()));
6076 AsmNodeOperands.push_back(OpInfo.CallOperand);
6077 break;
6078 }
6079
6080 // Otherwise, this is a register or register class output.
6081
6082 // Copy the output from the appropriate register. Find a register that
6083 // we can use.
Chris Lattnerfcd70902012-01-03 23:51:01 +00006084 if (OpInfo.AssignedRegs.Regs.empty()) {
6085 LLVMContext &Ctx = *DAG.getContext();
6086 Ctx.emitError(CS.getInstruction(),
6087 "couldn't allocate output register for constraint '" +
6088 Twine(OpInfo.ConstraintCode) + "'");
6089 break;
6090 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006091
6092 // If this is an indirect operand, store through the pointer after the
6093 // asm.
6094 if (OpInfo.isIndirect) {
6095 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
6096 OpInfo.CallOperandVal));
6097 } else {
6098 // This is the result value of the call.
Benjamin Kramerf0127052010-01-05 13:12:22 +00006099 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006100 // Concatenate this output onto the outputs list.
6101 RetValRegs.append(OpInfo.AssignedRegs);
6102 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006103
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006104 // Add information to the INLINEASM node to know that this register is
6105 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00006106 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
Chris Lattnerdecc2672010-04-07 05:20:54 +00006107 InlineAsm::Kind_RegDefEarlyClobber :
6108 InlineAsm::Kind_RegDef,
Evan Chengfb112882009-03-23 08:01:15 +00006109 false,
6110 0,
Bill Wendling46ada192010-03-02 01:55:18 +00006111 DAG,
Bill Wendling651ad132009-12-22 01:25:10 +00006112 AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006113 break;
6114 }
6115 case InlineAsm::isInput: {
6116 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006117
Chris Lattner6bdcda32008-10-17 16:47:46 +00006118 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006119 // If this is required to match an output register we have already set,
6120 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00006121 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006122
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006123 // Scan until we find the definition we already emitted of this operand.
6124 // When we find it, create a RegsForValue operand.
Chris Lattnerdecc2672010-04-07 05:20:54 +00006125 unsigned CurOp = InlineAsm::Op_FirstOperand;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006126 for (; OperandNo; --OperandNo) {
6127 // Advance to the next operand.
Evan Cheng697cbbf2009-03-20 18:03:34 +00006128 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00006129 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Chris Lattnerdecc2672010-04-07 05:20:54 +00006130 assert((InlineAsm::isRegDefKind(OpFlag) ||
6131 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
6132 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
Evan Cheng697cbbf2009-03-20 18:03:34 +00006133 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006134 }
6135
Evan Cheng697cbbf2009-03-20 18:03:34 +00006136 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00006137 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Chris Lattnerdecc2672010-04-07 05:20:54 +00006138 if (InlineAsm::isRegDefKind(OpFlag) ||
6139 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
Evan Cheng697cbbf2009-03-20 18:03:34 +00006140 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
Chris Lattner6129c372010-04-08 00:09:16 +00006141 if (OpInfo.isIndirect) {
6142 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
Dan Gohman99be8ae2010-04-19 22:41:47 +00006143 LLVMContext &Ctx = *DAG.getContext();
Chris Lattner6129c372010-04-08 00:09:16 +00006144 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
6145 " don't know how to handle tied "
6146 "indirect register inputs");
6147 }
Michael J. Spencere70c5262010-10-16 08:25:21 +00006148
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006149 RegsForValue MatchedRegs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006150 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
Owen Andersone50ed302009-08-10 22:56:29 +00006151 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
Evan Chengfb112882009-03-23 08:01:15 +00006152 MatchedRegs.RegVTs.push_back(RegVT);
6153 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
Evan Cheng697cbbf2009-03-20 18:03:34 +00006154 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
Evan Chengfb112882009-03-23 08:01:15 +00006155 i != e; ++i)
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00006156 MatchedRegs.Regs.push_back
6157 (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006158
6159 // Use the produced MatchedRegs object to
Dale Johannesen66978ee2009-01-31 02:22:37 +00006160 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
Bill Wendlingf18eb582012-09-26 06:16:18 +00006161 Chain, &Flag, CS.getInstruction());
Chris Lattnerdecc2672010-04-07 05:20:54 +00006162 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
Evan Chengfb112882009-03-23 08:01:15 +00006163 true, OpInfo.getMatchedOperand(),
Bill Wendling46ada192010-03-02 01:55:18 +00006164 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006165 break;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006166 }
Michael J. Spencere70c5262010-10-16 08:25:21 +00006167
Chris Lattnerdecc2672010-04-07 05:20:54 +00006168 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
6169 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
6170 "Unexpected number of operands");
6171 // Add information to the INLINEASM node to know about this input.
6172 // See InlineAsm.h isUseOperandTiedToDef.
6173 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
6174 OpInfo.getMatchedOperand());
6175 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
6176 TLI.getPointerTy()));
6177 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
6178 break;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006179 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006180
Dale Johannesenb5611a62010-07-13 20:17:05 +00006181 // Treat indirect 'X' constraint as memory.
Michael J. Spencere70c5262010-10-16 08:25:21 +00006182 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
6183 OpInfo.isIndirect)
Dale Johannesenb5611a62010-07-13 20:17:05 +00006184 OpInfo.ConstraintType = TargetLowering::C_Memory;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006185
Dale Johannesenb5611a62010-07-13 20:17:05 +00006186 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006187 std::vector<SDValue> Ops;
Eric Christopher100c8332011-06-02 23:16:42 +00006188 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
Dale Johannesen1784d162010-06-25 21:55:36 +00006189 Ops, DAG);
Chris Lattnerfcd70902012-01-03 23:51:01 +00006190 if (Ops.empty()) {
6191 LLVMContext &Ctx = *DAG.getContext();
6192 Ctx.emitError(CS.getInstruction(),
6193 "invalid operand for inline asm constraint '" +
6194 Twine(OpInfo.ConstraintCode) + "'");
6195 break;
6196 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006197
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006198 // Add information to the INLINEASM node to know about this input.
Chris Lattnerdecc2672010-04-07 05:20:54 +00006199 unsigned ResOpType =
6200 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006201 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006202 TLI.getPointerTy()));
6203 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
6204 break;
Chris Lattnerdecc2672010-04-07 05:20:54 +00006205 }
Michael J. Spencere70c5262010-10-16 08:25:21 +00006206
Chris Lattnerdecc2672010-04-07 05:20:54 +00006207 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006208 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
6209 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
6210 "Memory operands expect pointer values");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006211
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006212 // Add information to the INLINEASM node to know about this input.
Chris Lattnerdecc2672010-04-07 05:20:54 +00006213 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
Dale Johannesen86b49f82008-09-24 01:07:17 +00006214 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006215 TLI.getPointerTy()));
6216 AsmNodeOperands.push_back(InOperandVal);
6217 break;
6218 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006219
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006220 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6221 OpInfo.ConstraintType == TargetLowering::C_Register) &&
6222 "Unknown constraint type!");
Eric Christopher9eb4f8a2012-07-02 21:16:43 +00006223
6224 // TODO: Support this.
6225 if (OpInfo.isIndirect) {
6226 LLVMContext &Ctx = *DAG.getContext();
6227 Ctx.emitError(CS.getInstruction(),
6228 "Don't know how to handle indirect register inputs yet "
6229 "for constraint '" + Twine(OpInfo.ConstraintCode) + "'");
6230 break;
6231 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006232
6233 // Copy the input into the appropriate registers.
Chris Lattnerfcd70902012-01-03 23:51:01 +00006234 if (OpInfo.AssignedRegs.Regs.empty()) {
6235 LLVMContext &Ctx = *DAG.getContext();
6236 Ctx.emitError(CS.getInstruction(),
6237 "couldn't allocate input reg for constraint '" +
6238 Twine(OpInfo.ConstraintCode) + "'");
6239 break;
6240 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006241
Dale Johannesen66978ee2009-01-31 02:22:37 +00006242 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
Bill Wendlingf18eb582012-09-26 06:16:18 +00006243 Chain, &Flag, CS.getInstruction());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006244
Chris Lattnerdecc2672010-04-07 05:20:54 +00006245 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
Bill Wendling46ada192010-03-02 01:55:18 +00006246 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006247 break;
6248 }
6249 case InlineAsm::isClobber: {
6250 // Add the clobbered value to the operand list, so that the register
6251 // allocator is aware that the physreg got clobbered.
6252 if (!OpInfo.AssignedRegs.Regs.empty())
Jakob Stoklund Olesenf792fa92011-06-27 04:08:33 +00006253 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_Clobber,
Bill Wendling46ada192010-03-02 01:55:18 +00006254 false, 0, DAG,
Bill Wendling651ad132009-12-22 01:25:10 +00006255 AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006256 break;
6257 }
6258 }
6259 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006260
Chris Lattnerdecc2672010-04-07 05:20:54 +00006261 // Finish up input operands. Set the input chain and add the flag last.
Dale Johannesenf1e309e2010-07-02 20:16:09 +00006262 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006263 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006264
Dale Johannesen66978ee2009-01-31 02:22:37 +00006265 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
Chris Lattnerf1b4eaf2010-12-21 02:38:05 +00006266 DAG.getVTList(MVT::Other, MVT::Glue),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006267 &AsmNodeOperands[0], AsmNodeOperands.size());
6268 Flag = Chain.getValue(1);
6269
6270 // If this asm returns a register value, copy the result from that register
6271 // and set it as the value of the call.
6272 if (!RetValRegs.Regs.empty()) {
Dan Gohman7451d3e2010-05-29 17:03:36 +00006273 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(),
Bill Wendling12931302012-09-26 04:04:19 +00006274 Chain, &Flag, CS.getInstruction());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006275
Chris Lattner2a0b96c2008-10-18 18:49:30 +00006276 // FIXME: Why don't we do this for inline asms with MRVs?
6277 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
Owen Andersone50ed302009-08-10 22:56:29 +00006278 EVT ResultType = TLI.getValueType(CS.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006279
Chris Lattner2a0b96c2008-10-18 18:49:30 +00006280 // If any of the results of the inline asm is a vector, it may have the
6281 // wrong width/num elts. This can happen for register classes that can
6282 // contain multiple different value types. The preg or vreg allocated may
6283 // not have the same VT as was expected. Convert it to the right type
6284 // with bit_convert.
6285 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
Wesley Peckbf17cfa2010-11-23 03:31:01 +00006286 Val = DAG.getNode(ISD::BITCAST, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00006287 ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00006288
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006289 } else if (ResultType != Val.getValueType() &&
Chris Lattner2a0b96c2008-10-18 18:49:30 +00006290 ResultType.isInteger() && Val.getValueType().isInteger()) {
6291 // If a result value was tied to an input value, the computed result may
6292 // have a wider width than the expected result. Extract the relevant
6293 // portion.
Dale Johannesen66978ee2009-01-31 02:22:37 +00006294 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00006295 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006296
Chris Lattner2a0b96c2008-10-18 18:49:30 +00006297 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00006298 }
Dan Gohman95915732008-10-18 01:03:45 +00006299
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006300 setValue(CS.getInstruction(), Val);
Dale Johannesenec65a7d2009-04-14 00:56:56 +00006301 // Don't need to use this as a chain in this case.
6302 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6303 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006304 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006305
Dan Gohman46510a72010-04-15 01:51:59 +00006306 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006307
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006308 // Process indirect outputs, first output all of the flagged copies out of
6309 // physregs.
6310 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6311 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
Dan Gohman46510a72010-04-15 01:51:59 +00006312 const Value *Ptr = IndirectStoresToEmit[i].second;
Dan Gohman7451d3e2010-05-29 17:03:36 +00006313 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(),
Bill Wendling12931302012-09-26 04:04:19 +00006314 Chain, &Flag, IA);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006315 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6316 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006317
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006318 // Emit the non-flagged stores from the physregs.
6319 SmallVector<SDValue, 8> OutChains;
Bill Wendling651ad132009-12-22 01:25:10 +00006320 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6321 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
6322 StoresToEmit[i].first,
6323 getValue(StoresToEmit[i].second),
Chris Lattner84bd98a2010-09-21 18:58:22 +00006324 MachinePointerInfo(StoresToEmit[i].second),
David Greene1e559442010-02-15 17:00:31 +00006325 false, false, 0);
Bill Wendling651ad132009-12-22 01:25:10 +00006326 OutChains.push_back(Val);
Bill Wendling651ad132009-12-22 01:25:10 +00006327 }
6328
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006329 if (!OutChains.empty())
Owen Anderson825b72b2009-08-11 20:47:22 +00006330 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006331 &OutChains[0], OutChains.size());
Bill Wendling651ad132009-12-22 01:25:10 +00006332
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006333 DAG.setRoot(Chain);
6334}
6335
Dan Gohman46510a72010-04-15 01:51:59 +00006336void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
Bill Wendlingc1d3c942009-12-23 00:44:51 +00006337 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
6338 MVT::Other, getRoot(),
Gabor Greif0635f352010-06-25 09:38:13 +00006339 getValue(I.getArgOperand(0)),
6340 DAG.getSrcValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006341}
6342
Dan Gohman46510a72010-04-15 01:51:59 +00006343void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
Micah Villmow3574eca2012-10-08 16:38:25 +00006344 const DataLayout &TD = *TLI.getDataLayout();
Dale Johannesena04b7572009-02-03 23:04:43 +00006345 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
6346 getRoot(), getValue(I.getOperand(0)),
Rafael Espindolacbeeae22010-07-11 04:01:49 +00006347 DAG.getSrcValue(I.getOperand(0)),
Rafael Espindola9d544d02010-07-12 18:11:17 +00006348 TD.getABITypeAlignment(I.getType()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006349 setValue(&I, V);
6350 DAG.setRoot(V.getValue(1));
6351}
6352
Dan Gohman46510a72010-04-15 01:51:59 +00006353void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
Bill Wendlingc1d3c942009-12-23 00:44:51 +00006354 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
6355 MVT::Other, getRoot(),
Gabor Greif0635f352010-06-25 09:38:13 +00006356 getValue(I.getArgOperand(0)),
6357 DAG.getSrcValue(I.getArgOperand(0))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006358}
6359
Dan Gohman46510a72010-04-15 01:51:59 +00006360void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
Bill Wendlingc1d3c942009-12-23 00:44:51 +00006361 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
6362 MVT::Other, getRoot(),
Gabor Greif0635f352010-06-25 09:38:13 +00006363 getValue(I.getArgOperand(0)),
6364 getValue(I.getArgOperand(1)),
6365 DAG.getSrcValue(I.getArgOperand(0)),
6366 DAG.getSrcValue(I.getArgOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006367}
6368
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006369/// TargetLowering::LowerCallTo - This is the default LowerCallTo
Dan Gohman98ca4f22009-08-05 01:29:28 +00006370/// implementation, which just calls LowerCall.
6371/// FIXME: When all targets are
6372/// migrated to using LowerCall, this hook should be integrated into SDISel.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006373std::pair<SDValue, SDValue>
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006374TargetLowering::LowerCallTo(TargetLowering::CallLoweringInfo &CLI) const {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006375 // Handle all of the outgoing arguments.
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006376 CLI.Outs.clear();
6377 CLI.OutVals.clear();
6378 ArgListTy &Args = CLI.Args;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006379 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Owen Andersone50ed302009-08-10 22:56:29 +00006380 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006381 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
6382 for (unsigned Value = 0, NumValues = ValueVTs.size();
6383 Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00006384 EVT VT = ValueVTs[Value];
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006385 Type *ArgTy = VT.getTypeForEVT(CLI.RetTy->getContext());
Chris Lattner2a0b96c2008-10-18 18:49:30 +00006386 SDValue Op = SDValue(Args[i].Node.getNode(),
6387 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006388 ISD::ArgFlagsTy Flags;
6389 unsigned OriginalAlignment =
Micah Villmow3574eca2012-10-08 16:38:25 +00006390 getDataLayout()->getABITypeAlignment(ArgTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006391
6392 if (Args[i].isZExt)
6393 Flags.setZExt();
6394 if (Args[i].isSExt)
6395 Flags.setSExt();
6396 if (Args[i].isInReg)
6397 Flags.setInReg();
6398 if (Args[i].isSRet)
6399 Flags.setSRet();
6400 if (Args[i].isByVal) {
6401 Flags.setByVal();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00006402 PointerType *Ty = cast<PointerType>(Args[i].Ty);
6403 Type *ElementTy = Ty->getElementType();
Micah Villmow3574eca2012-10-08 16:38:25 +00006404 Flags.setByValSize(getDataLayout()->getTypeAllocSize(ElementTy));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006405 // For ByVal, alignment should come from FE. BE will guess if this
6406 // info is not there but there are cases it cannot get right.
Chris Lattner9db20f32011-05-22 23:23:02 +00006407 unsigned FrameAlign;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006408 if (Args[i].Alignment)
6409 FrameAlign = Args[i].Alignment;
Chris Lattner9db20f32011-05-22 23:23:02 +00006410 else
6411 FrameAlign = getByValTypeAlignment(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006412 Flags.setByValAlign(FrameAlign);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006413 }
6414 if (Args[i].isNest)
6415 Flags.setNest();
6416 Flags.setOrigAlign(OriginalAlignment);
6417
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006418 EVT PartVT = getRegisterType(CLI.RetTy->getContext(), VT);
6419 unsigned NumParts = getNumRegisters(CLI.RetTy->getContext(), VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006420 SmallVector<SDValue, 4> Parts(NumParts);
6421 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
6422
6423 if (Args[i].isSExt)
6424 ExtendKind = ISD::SIGN_EXTEND;
6425 else if (Args[i].isZExt)
6426 ExtendKind = ISD::ZERO_EXTEND;
6427
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006428 getCopyToParts(CLI.DAG, CLI.DL, Op, &Parts[0], NumParts,
Bill Wendlingf18eb582012-09-26 06:16:18 +00006429 PartVT, CLI.CS ? CLI.CS->getInstruction() : 0, ExtendKind);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006430
Dan Gohman98ca4f22009-08-05 01:29:28 +00006431 for (unsigned j = 0; j != NumParts; ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006432 // if it isn't first piece, alignment must be 1
Dan Gohmanc9403652010-07-07 15:54:55 +00006433 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(),
Manman Ren0a1544d2012-11-01 23:49:58 +00006434 i < CLI.NumFixedArgs,
6435 i, j*Parts[j].getValueType().getStoreSize());
Dan Gohman98ca4f22009-08-05 01:29:28 +00006436 if (NumParts > 1 && j == 0)
6437 MyFlags.Flags.setSplit();
6438 else if (j != 0)
6439 MyFlags.Flags.setOrigAlign(1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006440
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006441 CLI.Outs.push_back(MyFlags);
6442 CLI.OutVals.push_back(Parts[j]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006443 }
6444 }
6445 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006446
Dan Gohman98ca4f22009-08-05 01:29:28 +00006447 // Handle the incoming return values from the call.
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006448 CLI.Ins.clear();
Owen Andersone50ed302009-08-10 22:56:29 +00006449 SmallVector<EVT, 4> RetTys;
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006450 ComputeValueVTs(*this, CLI.RetTy, RetTys);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006451 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Owen Andersone50ed302009-08-10 22:56:29 +00006452 EVT VT = RetTys[I];
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006453 EVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
6454 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006455 for (unsigned i = 0; i != NumRegs; ++i) {
6456 ISD::InputArg MyFlags;
Duncan Sands1440e8b2010-11-03 11:35:31 +00006457 MyFlags.VT = RegisterVT.getSimpleVT();
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006458 MyFlags.Used = CLI.IsReturnValueUsed;
6459 if (CLI.RetSExt)
Dan Gohman98ca4f22009-08-05 01:29:28 +00006460 MyFlags.Flags.setSExt();
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006461 if (CLI.RetZExt)
Dan Gohman98ca4f22009-08-05 01:29:28 +00006462 MyFlags.Flags.setZExt();
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006463 if (CLI.IsInReg)
Dan Gohman98ca4f22009-08-05 01:29:28 +00006464 MyFlags.Flags.setInReg();
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006465 CLI.Ins.push_back(MyFlags);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006466 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006467 }
6468
Dan Gohman98ca4f22009-08-05 01:29:28 +00006469 SmallVector<SDValue, 4> InVals;
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006470 CLI.Chain = LowerCall(CLI, InVals);
Dan Gohman5e866062009-08-06 15:37:27 +00006471
6472 // Verify that the target's LowerCall behaved as expected.
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006473 assert(CLI.Chain.getNode() && CLI.Chain.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00006474 "LowerCall didn't return a valid chain!");
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006475 assert((!CLI.IsTailCall || InVals.empty()) &&
Dan Gohman5e866062009-08-06 15:37:27 +00006476 "LowerCall emitted a return value for a tail call!");
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006477 assert((CLI.IsTailCall || InVals.size() == CLI.Ins.size()) &&
Dan Gohman5e866062009-08-06 15:37:27 +00006478 "LowerCall didn't emit the correct number of values!");
Dan Gohman98ca4f22009-08-05 01:29:28 +00006479
6480 // For a tail call, the return value is merely live-out and there aren't
6481 // any nodes in the DAG representing it. Return a special value to
6482 // indicate that a tail call has been emitted and no more Instructions
6483 // should be processed in the current block.
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006484 if (CLI.IsTailCall) {
6485 CLI.DAG.setRoot(CLI.Chain);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006486 return std::make_pair(SDValue(), SDValue());
6487 }
6488
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006489 DEBUG(for (unsigned i = 0, e = CLI.Ins.size(); i != e; ++i) {
Evan Chengaf1871f2010-03-11 19:38:18 +00006490 assert(InVals[i].getNode() &&
6491 "LowerCall emitted a null value!");
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006492 assert(EVT(CLI.Ins[i].VT) == InVals[i].getValueType() &&
Evan Chengaf1871f2010-03-11 19:38:18 +00006493 "LowerCall emitted a value with the wrong type!");
6494 });
6495
Dan Gohman98ca4f22009-08-05 01:29:28 +00006496 // Collect the legal value parts into potentially illegal values
6497 // that correspond to the original function's return values.
6498 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006499 if (CLI.RetSExt)
Dan Gohman98ca4f22009-08-05 01:29:28 +00006500 AssertOp = ISD::AssertSext;
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006501 else if (CLI.RetZExt)
Dan Gohman98ca4f22009-08-05 01:29:28 +00006502 AssertOp = ISD::AssertZext;
6503 SmallVector<SDValue, 4> ReturnValues;
6504 unsigned CurReg = 0;
6505 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Owen Andersone50ed302009-08-10 22:56:29 +00006506 EVT VT = RetTys[I];
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006507 EVT RegisterVT = getRegisterType(CLI.RetTy->getContext(), VT);
6508 unsigned NumRegs = getNumRegisters(CLI.RetTy->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006509
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006510 ReturnValues.push_back(getCopyFromParts(CLI.DAG, CLI.DL, &InVals[CurReg],
Bill Wendling12931302012-09-26 04:04:19 +00006511 NumRegs, RegisterVT, VT, NULL,
Bill Wendling4533cac2010-01-28 21:51:40 +00006512 AssertOp));
Dan Gohman98ca4f22009-08-05 01:29:28 +00006513 CurReg += NumRegs;
6514 }
6515
6516 // For a function returning void, there is no return value. We can't create
6517 // such a node, so we just return a null return value in that case. In
Chris Lattner7a2bdde2011-04-15 05:18:47 +00006518 // that case, nothing will actually look at the value.
Dan Gohman98ca4f22009-08-05 01:29:28 +00006519 if (ReturnValues.empty())
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006520 return std::make_pair(SDValue(), CLI.Chain);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006521
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006522 SDValue Res = CLI.DAG.getNode(ISD::MERGE_VALUES, CLI.DL,
6523 CLI.DAG.getVTList(&RetTys[0], RetTys.size()),
Dan Gohman98ca4f22009-08-05 01:29:28 +00006524 &ReturnValues[0], ReturnValues.size());
Justin Holewinskid2ea0e12012-05-25 16:35:28 +00006525 return std::make_pair(Res, CLI.Chain);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006526}
6527
Duncan Sands9fbc7e22009-01-21 09:00:29 +00006528void TargetLowering::LowerOperationWrapper(SDNode *N,
6529 SmallVectorImpl<SDValue> &Results,
Dan Gohmand858e902010-04-17 15:26:15 +00006530 SelectionDAG &DAG) const {
Duncan Sands9fbc7e22009-01-21 09:00:29 +00006531 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptabb326bb2009-01-21 04:48:39 +00006532 if (Res.getNode())
6533 Results.push_back(Res);
6534}
6535
Dan Gohmand858e902010-04-17 15:26:15 +00006536SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
Torok Edwinc23197a2009-07-14 16:55:14 +00006537 llvm_unreachable("LowerOperation not implemented for this target!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006538}
6539
Dan Gohman46510a72010-04-15 01:51:59 +00006540void
6541SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
Dan Gohman28a17352010-07-01 01:59:43 +00006542 SDValue Op = getNonRegisterValue(V);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006543 assert((Op.getOpcode() != ISD::CopyFromReg ||
6544 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
6545 "Copy from a reg to the same reg!");
6546 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
6547
Owen Anderson23b9b192009-08-12 00:36:31 +00006548 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006549 SDValue Chain = DAG.getEntryNode();
Bill Wendlingf18eb582012-09-26 06:16:18 +00006550 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0, V);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006551 PendingExports.push_back(Chain);
6552}
6553
6554#include "llvm/CodeGen/SelectionDAGISel.h"
6555
Eli Friedman23d32432011-05-05 16:53:34 +00006556/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
6557/// entry block, return true. This includes arguments used by switches, since
6558/// the switch may expand into multiple basic blocks.
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006559static bool isOnlyUsedInEntryBlock(const Argument *A, bool FastISel) {
Eli Friedman23d32432011-05-05 16:53:34 +00006560 // With FastISel active, we may be splitting blocks, so force creation
6561 // of virtual registers for all non-dead arguments.
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006562 if (FastISel)
Eli Friedman23d32432011-05-05 16:53:34 +00006563 return A->use_empty();
6564
6565 const BasicBlock *Entry = A->getParent()->begin();
6566 for (Value::const_use_iterator UI = A->use_begin(), E = A->use_end();
6567 UI != E; ++UI) {
6568 const User *U = *UI;
6569 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
6570 return false; // Use not in entry block.
6571 }
6572 return true;
6573}
6574
Dan Gohman46510a72010-04-15 01:51:59 +00006575void SelectionDAGISel::LowerArguments(const BasicBlock *LLVMBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006576 // If this is the entry block, emit arguments.
Dan Gohman46510a72010-04-15 01:51:59 +00006577 const Function &F = *LLVMBB->getParent();
Dan Gohman2048b852009-11-23 18:04:58 +00006578 SelectionDAG &DAG = SDB->DAG;
Dan Gohman2048b852009-11-23 18:04:58 +00006579 DebugLoc dl = SDB->getCurDebugLoc();
Micah Villmow3574eca2012-10-08 16:38:25 +00006580 const DataLayout *TD = TLI.getDataLayout();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006581 SmallVector<ISD::InputArg, 16> Ins;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006582
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +00006583 // Check whether the function can return without sret-demotion.
Dan Gohman84023e02010-07-10 09:00:22 +00006584 SmallVector<ISD::OutputArg, 4> Outs;
6585 GetReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
6586 Outs, TLI);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006587
Dan Gohman7451d3e2010-05-29 17:03:36 +00006588 if (!FuncInfo->CanLowerReturn) {
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006589 // Put in an sret pointer parameter before all the other parameters.
6590 SmallVector<EVT, 1> ValueVTs;
6591 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6592
6593 // NOTE: Assuming that a pointer will never break down to more than one VT
6594 // or one register.
6595 ISD::ArgFlagsTy Flags;
6596 Flags.setSRet();
Dan Gohmanf81eca02010-04-22 20:46:50 +00006597 EVT RegisterVT = TLI.getRegisterType(*DAG.getContext(), ValueVTs[0]);
Stepan Dyatkovskiy661afe72012-10-10 11:37:36 +00006598 ISD::InputArg RetArg(Flags, RegisterVT, true, 0, 0);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006599 Ins.push_back(RetArg);
6600 }
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +00006601
Dan Gohman98ca4f22009-08-05 01:29:28 +00006602 // Set up the incoming argument description vector.
Dan Gohman98ca4f22009-08-05 01:29:28 +00006603 unsigned Idx = 1;
Dan Gohman46510a72010-04-15 01:51:59 +00006604 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
Dan Gohman98ca4f22009-08-05 01:29:28 +00006605 I != E; ++I, ++Idx) {
Owen Andersone50ed302009-08-10 22:56:29 +00006606 SmallVector<EVT, 4> ValueVTs;
Dan Gohman98ca4f22009-08-05 01:29:28 +00006607 ComputeValueVTs(TLI, I->getType(), ValueVTs);
6608 bool isArgValueUsed = !I->use_empty();
6609 for (unsigned Value = 0, NumValues = ValueVTs.size();
6610 Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00006611 EVT VT = ValueVTs[Value];
Chris Lattnerdb125cf2011-07-18 04:54:35 +00006612 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Dan Gohman98ca4f22009-08-05 01:29:28 +00006613 ISD::ArgFlagsTy Flags;
6614 unsigned OriginalAlignment =
6615 TD->getABITypeAlignment(ArgTy);
6616
Bill Wendling67658342012-10-09 07:45:08 +00006617 if (F.getParamAttributes(Idx).hasAttribute(Attributes::ZExt))
Dan Gohman98ca4f22009-08-05 01:29:28 +00006618 Flags.setZExt();
Bill Wendling67658342012-10-09 07:45:08 +00006619 if (F.getParamAttributes(Idx).hasAttribute(Attributes::SExt))
Dan Gohman98ca4f22009-08-05 01:29:28 +00006620 Flags.setSExt();
Bill Wendling67658342012-10-09 07:45:08 +00006621 if (F.getParamAttributes(Idx).hasAttribute(Attributes::InReg))
Dan Gohman98ca4f22009-08-05 01:29:28 +00006622 Flags.setInReg();
Bill Wendling67658342012-10-09 07:45:08 +00006623 if (F.getParamAttributes(Idx).hasAttribute(Attributes::StructRet))
Dan Gohman98ca4f22009-08-05 01:29:28 +00006624 Flags.setSRet();
Bill Wendling67658342012-10-09 07:45:08 +00006625 if (F.getParamAttributes(Idx).hasAttribute(Attributes::ByVal)) {
Dan Gohman98ca4f22009-08-05 01:29:28 +00006626 Flags.setByVal();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00006627 PointerType *Ty = cast<PointerType>(I->getType());
6628 Type *ElementTy = Ty->getElementType();
Chris Lattner9db20f32011-05-22 23:23:02 +00006629 Flags.setByValSize(TD->getTypeAllocSize(ElementTy));
Dan Gohman98ca4f22009-08-05 01:29:28 +00006630 // For ByVal, alignment should be passed from FE. BE will guess if
6631 // this info is not there but there are cases it cannot get right.
Chris Lattner9db20f32011-05-22 23:23:02 +00006632 unsigned FrameAlign;
Dan Gohman98ca4f22009-08-05 01:29:28 +00006633 if (F.getParamAlignment(Idx))
6634 FrameAlign = F.getParamAlignment(Idx);
Chris Lattner9db20f32011-05-22 23:23:02 +00006635 else
6636 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006637 Flags.setByValAlign(FrameAlign);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006638 }
Bill Wendling67658342012-10-09 07:45:08 +00006639 if (F.getParamAttributes(Idx).hasAttribute(Attributes::Nest))
Dan Gohman98ca4f22009-08-05 01:29:28 +00006640 Flags.setNest();
6641 Flags.setOrigAlign(OriginalAlignment);
6642
Owen Anderson23b9b192009-08-12 00:36:31 +00006643 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6644 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006645 for (unsigned i = 0; i != NumRegs; ++i) {
Stepan Dyatkovskiy661afe72012-10-10 11:37:36 +00006646 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed,
6647 Idx-1, i*RegisterVT.getStoreSize());
Dan Gohman98ca4f22009-08-05 01:29:28 +00006648 if (NumRegs > 1 && i == 0)
6649 MyFlags.Flags.setSplit();
6650 // if it isn't first piece, alignment must be 1
6651 else if (i > 0)
6652 MyFlags.Flags.setOrigAlign(1);
6653 Ins.push_back(MyFlags);
6654 }
6655 }
6656 }
6657
6658 // Call the target to set up the argument values.
6659 SmallVector<SDValue, 8> InVals;
6660 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
6661 F.isVarArg(), Ins,
6662 dl, DAG, InVals);
Dan Gohman5e866062009-08-06 15:37:27 +00006663
6664 // Verify that the target's LowerFormalArguments behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +00006665 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00006666 "LowerFormalArguments didn't return a valid chain!");
6667 assert(InVals.size() == Ins.size() &&
6668 "LowerFormalArguments didn't emit the correct number of values!");
Bill Wendling3ea58b62009-12-22 21:35:02 +00006669 DEBUG({
6670 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6671 assert(InVals[i].getNode() &&
6672 "LowerFormalArguments emitted a null value!");
Duncan Sands1440e8b2010-11-03 11:35:31 +00006673 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
Bill Wendling3ea58b62009-12-22 21:35:02 +00006674 "LowerFormalArguments emitted a value with the wrong type!");
6675 }
6676 });
Bill Wendling3ea3c242009-12-22 02:10:19 +00006677
Dan Gohman5e866062009-08-06 15:37:27 +00006678 // Update the DAG with the new chain value resulting from argument lowering.
Dan Gohman98ca4f22009-08-05 01:29:28 +00006679 DAG.setRoot(NewRoot);
6680
6681 // Set up the argument values.
6682 unsigned i = 0;
6683 Idx = 1;
Dan Gohman7451d3e2010-05-29 17:03:36 +00006684 if (!FuncInfo->CanLowerReturn) {
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006685 // Create a virtual register for the sret pointer, and put in a copy
6686 // from the sret argument into it.
6687 SmallVector<EVT, 1> ValueVTs;
6688 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6689 EVT VT = ValueVTs[0];
6690 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6691 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Bill Wendling46ada192010-03-02 01:55:18 +00006692 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
Bill Wendling12931302012-09-26 04:04:19 +00006693 RegVT, VT, NULL, AssertOp);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006694
Dan Gohman2048b852009-11-23 18:04:58 +00006695 MachineFunction& MF = SDB->DAG.getMachineFunction();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006696 MachineRegisterInfo& RegInfo = MF.getRegInfo();
6697 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
Dan Gohman7451d3e2010-05-29 17:03:36 +00006698 FuncInfo->DemoteRegister = SRetReg;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00006699 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(),
6700 SRetReg, ArgValue);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006701 DAG.setRoot(NewRoot);
Bill Wendling3ea3c242009-12-22 02:10:19 +00006702
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006703 // i indexes lowered arguments. Bump it past the hidden sret argument.
6704 // Idx indexes LLVM arguments. Don't touch it.
6705 ++i;
6706 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006707
Dan Gohman46510a72010-04-15 01:51:59 +00006708 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
Dan Gohman98ca4f22009-08-05 01:29:28 +00006709 ++I, ++Idx) {
6710 SmallVector<SDValue, 4> ArgValues;
Owen Andersone50ed302009-08-10 22:56:29 +00006711 SmallVector<EVT, 4> ValueVTs;
Dan Gohman98ca4f22009-08-05 01:29:28 +00006712 ComputeValueVTs(TLI, I->getType(), ValueVTs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006713 unsigned NumValues = ValueVTs.size();
Devang Patel9126c0d2010-06-01 19:59:01 +00006714
6715 // If this argument is unused then remember its value. It is used to generate
6716 // debugging information.
6717 if (I->use_empty() && NumValues)
6718 SDB->setUnusedArgValue(I, InVals[i]);
6719
Eli Friedman23d32432011-05-05 16:53:34 +00006720 for (unsigned Val = 0; Val != NumValues; ++Val) {
6721 EVT VT = ValueVTs[Val];
Owen Anderson23b9b192009-08-12 00:36:31 +00006722 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6723 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006724
6725 if (!I->use_empty()) {
6726 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Bill Wendling67658342012-10-09 07:45:08 +00006727 if (F.getParamAttributes(Idx).hasAttribute(Attributes::SExt))
Dan Gohman98ca4f22009-08-05 01:29:28 +00006728 AssertOp = ISD::AssertSext;
Bill Wendling67658342012-10-09 07:45:08 +00006729 else if (F.getParamAttributes(Idx).hasAttribute(Attributes::ZExt))
Dan Gohman98ca4f22009-08-05 01:29:28 +00006730 AssertOp = ISD::AssertZext;
6731
Bill Wendling46ada192010-03-02 01:55:18 +00006732 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
Bill Wendling3ea3c242009-12-22 02:10:19 +00006733 NumParts, PartVT, VT,
Bill Wendling12931302012-09-26 04:04:19 +00006734 NULL, AssertOp));
Dan Gohman98ca4f22009-08-05 01:29:28 +00006735 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006736
Dan Gohman98ca4f22009-08-05 01:29:28 +00006737 i += NumParts;
6738 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006739
Eli Friedman23d32432011-05-05 16:53:34 +00006740 // We don't need to do anything else for unused arguments.
6741 if (ArgValues.empty())
6742 continue;
6743
Devang Patel9aee3352011-09-08 22:59:09 +00006744 // Note down frame index.
6745 if (FrameIndexSDNode *FI =
Bill Wendling96cb1122012-07-19 00:04:14 +00006746 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
Devang Patel9aee3352011-09-08 22:59:09 +00006747 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
Devang Patel0b48ead2010-08-31 22:22:42 +00006748
Eli Friedman23d32432011-05-05 16:53:34 +00006749 SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues,
6750 SDB->getCurDebugLoc());
Devang Patel9aee3352011-09-08 22:59:09 +00006751
Eli Friedman23d32432011-05-05 16:53:34 +00006752 SDB->setValue(I, Res);
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006753 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::BUILD_PAIR) {
Devang Patel9aee3352011-09-08 22:59:09 +00006754 if (LoadSDNode *LNode =
6755 dyn_cast<LoadSDNode>(Res.getOperand(0).getNode()))
6756 if (FrameIndexSDNode *FI =
6757 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode()))
6758 FuncInfo->setArgumentFrameIndex(I, FI->getIndex());
6759 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006760
Eli Friedman23d32432011-05-05 16:53:34 +00006761 // If this argument is live outside of the entry block, insert a copy from
6762 // wherever we got it to the vreg that other BB's will reference it as.
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006763 if (!TM.Options.EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
Eli Friedman23d32432011-05-05 16:53:34 +00006764 // If we can, though, try to skip creating an unnecessary vreg.
6765 // FIXME: This isn't very clean... it would be nice to make this more
Eli Friedman7f33d672011-05-10 21:50:58 +00006766 // general. It's also subtly incompatible with the hacks FastISel
6767 // uses with vregs.
Eli Friedman23d32432011-05-05 16:53:34 +00006768 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
6769 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
6770 FuncInfo->ValueMap[I] = Reg;
6771 continue;
6772 }
6773 }
Nick Lewycky8a8d4792011-12-02 22:16:29 +00006774 if (!isOnlyUsedInEntryBlock(I, TM.Options.EnableFastISel)) {
Eli Friedman23d32432011-05-05 16:53:34 +00006775 FuncInfo->InitializeRegForValue(I);
Dan Gohman2048b852009-11-23 18:04:58 +00006776 SDB->CopyToExportRegsIfNeeded(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006777 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006778 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006779
Dan Gohman98ca4f22009-08-05 01:29:28 +00006780 assert(i == InVals.size() && "Argument register count mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006781
6782 // Finally, if the target has anything special to do, allow it to do so.
6783 // FIXME: this should insert code into the DAG!
Dan Gohman64652652010-04-14 20:17:22 +00006784 EmitFunctionEntryCode();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006785}
6786
6787/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
6788/// ensure constants are generated when needed. Remember the virtual registers
6789/// that need to be added to the Machine PHI nodes as input. We cannot just
6790/// directly add them, because expansion might result in multiple MBB's for one
6791/// BB. As such, the start of the BB might correspond to a different MBB than
6792/// the end.
6793///
6794void
Dan Gohmanf81eca02010-04-22 20:46:50 +00006795SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
Dan Gohman46510a72010-04-15 01:51:59 +00006796 const TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006797
6798 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6799
6800 // Check successor nodes' PHI nodes that expect a constant to be available
6801 // from this block.
6802 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
Dan Gohman46510a72010-04-15 01:51:59 +00006803 const BasicBlock *SuccBB = TI->getSuccessor(succ);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006804 if (!isa<PHINode>(SuccBB->begin())) continue;
Dan Gohmanf81eca02010-04-22 20:46:50 +00006805 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006806
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006807 // If this terminator has multiple identical successors (common for
6808 // switches), only handle each succ once.
6809 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006810
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006811 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006812
6813 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6814 // nodes and Machine PHI nodes, but the incoming operands have not been
6815 // emitted yet.
Dan Gohman46510a72010-04-15 01:51:59 +00006816 for (BasicBlock::const_iterator I = SuccBB->begin();
6817 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006818 // Ignore dead phi's.
6819 if (PN->use_empty()) continue;
6820
Rafael Espindola3fa82832011-05-13 15:18:06 +00006821 // Skip empty types
6822 if (PN->getType()->isEmptyTy())
6823 continue;
6824
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006825 unsigned Reg;
Dan Gohman46510a72010-04-15 01:51:59 +00006826 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006827
Dan Gohman46510a72010-04-15 01:51:59 +00006828 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
Dan Gohmanf81eca02010-04-22 20:46:50 +00006829 unsigned &RegOut = ConstantsOut[C];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006830 if (RegOut == 0) {
Dan Gohman89496d02010-07-02 00:10:16 +00006831 RegOut = FuncInfo.CreateRegs(C->getType());
Dan Gohmanf81eca02010-04-22 20:46:50 +00006832 CopyValueToVirtualRegister(C, RegOut);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006833 }
6834 Reg = RegOut;
6835 } else {
Dan Gohmanc25ad632010-07-01 01:33:21 +00006836 DenseMap<const Value *, unsigned>::iterator I =
6837 FuncInfo.ValueMap.find(PHIOp);
6838 if (I != FuncInfo.ValueMap.end())
6839 Reg = I->second;
6840 else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006841 assert(isa<AllocaInst>(PHIOp) &&
Dan Gohmanf81eca02010-04-22 20:46:50 +00006842 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006843 "Didn't codegen value into a register!??");
Dan Gohman89496d02010-07-02 00:10:16 +00006844 Reg = FuncInfo.CreateRegs(PHIOp->getType());
Dan Gohmanf81eca02010-04-22 20:46:50 +00006845 CopyValueToVirtualRegister(PHIOp, Reg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006846 }
6847 }
6848
6849 // Remember that this register needs to added to the machine PHI node as
6850 // the input for this MBB.
Owen Andersone50ed302009-08-10 22:56:29 +00006851 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006852 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6853 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
Owen Andersone50ed302009-08-10 22:56:29 +00006854 EVT VT = ValueVTs[vti];
Dan Gohmanf81eca02010-04-22 20:46:50 +00006855 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006856 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Dan Gohmanf81eca02010-04-22 20:46:50 +00006857 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006858 Reg += NumRegisters;
6859 }
6860 }
6861 }
Dan Gohmanf81eca02010-04-22 20:46:50 +00006862 ConstantsOut.clear();
Dan Gohman3df24e62008-09-03 23:12:08 +00006863}