blob: ed939a7f6fecaeb23433eb3c7a1003cf58f826a3 [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"
Dan Gohman2048b852009-11-23 18:04:58 +000015#include "SelectionDAGBuilder.h"
Dan Gohman6277eb22009-11-23 17:16:22 +000016#include "FunctionLoweringInfo.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000017#include "llvm/ADT/BitVector.h"
Dan Gohman5b229802008-09-04 20:49:27 +000018#include "llvm/ADT/SmallSet.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000019#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner8047d9a2009-12-24 00:37:38 +000020#include "llvm/Analysis/ConstantFolding.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000021#include "llvm/Constants.h"
22#include "llvm/CallingConv.h"
23#include "llvm/DerivedTypes.h"
24#include "llvm/Function.h"
25#include "llvm/GlobalVariable.h"
26#include "llvm/InlineAsm.h"
27#include "llvm/Instructions.h"
28#include "llvm/Intrinsics.h"
29#include "llvm/IntrinsicInst.h"
Bill Wendlingb2a42982008-11-06 02:29:10 +000030#include "llvm/Module.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000031#include "llvm/CodeGen/FastISel.h"
32#include "llvm/CodeGen/GCStrategy.h"
33#include "llvm/CodeGen/GCMetadata.h"
34#include "llvm/CodeGen/MachineFunction.h"
35#include "llvm/CodeGen/MachineFrameInfo.h"
36#include "llvm/CodeGen/MachineInstrBuilder.h"
37#include "llvm/CodeGen/MachineJumpTableInfo.h"
38#include "llvm/CodeGen/MachineModuleInfo.h"
39#include "llvm/CodeGen/MachineRegisterInfo.h"
Bill Wendlingb2a42982008-11-06 02:29:10 +000040#include "llvm/CodeGen/PseudoSourceValue.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000041#include "llvm/CodeGen/SelectionDAG.h"
Devang Patel83489bb2009-01-13 00:35:13 +000042#include "llvm/CodeGen/DwarfWriter.h"
43#include "llvm/Analysis/DebugInfo.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000044#include "llvm/Target/TargetRegisterInfo.h"
45#include "llvm/Target/TargetData.h"
46#include "llvm/Target/TargetFrameInfo.h"
47#include "llvm/Target/TargetInstrInfo.h"
Dale Johannesen49de9822009-02-05 01:49:45 +000048#include "llvm/Target/TargetIntrinsicInfo.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000049#include "llvm/Target/TargetLowering.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000050#include "llvm/Target/TargetOptions.h"
51#include "llvm/Support/Compiler.h"
Mikhail Glushenkov2388a582009-01-16 07:02:28 +000052#include "llvm/Support/CommandLine.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000053#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000054#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000055#include "llvm/Support/MathExtras.h"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +000056#include "llvm/Support/raw_ostream.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000057#include <algorithm>
58using namespace llvm;
59
Dale Johannesen601d3c02008-09-05 01:48:15 +000060/// LimitFloatPrecision - Generate low-precision inline sequences for
61/// some float libcalls (6, 8 or 12 bits).
62static unsigned LimitFloatPrecision;
63
64static cl::opt<unsigned, true>
65LimitFPPrecision("limit-float-precision",
66 cl::desc("Generate low-precision inline sequences "
67 "for some float libcalls"),
68 cl::location(LimitFloatPrecision),
69 cl::init(0));
70
Dan Gohmanf9bd4502009-11-23 17:46:23 +000071namespace {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000072 /// RegsForValue - This struct represents the registers (physical or virtual)
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +000073 /// that a particular set of values is assigned, and the type information
74 /// about the value. The most common situation is to represent one value at a
75 /// time, but struct or array values are handled element-wise as multiple
76 /// values. The splitting of aggregates is performed recursively, so that we
77 /// never have aggregate-typed registers. The values at this point do not
78 /// necessarily have legal types, so each value may require one or more
79 /// registers of some legal type.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000080 ///
Dan Gohmanf9bd4502009-11-23 17:46:23 +000081 struct RegsForValue {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000082 /// TLI - The TargetLowering object.
83 ///
84 const TargetLowering *TLI;
85
86 /// ValueVTs - The value types of the values, which may not be legal, and
87 /// may need be promoted or synthesized from one or more registers.
88 ///
Owen Andersone50ed302009-08-10 22:56:29 +000089 SmallVector<EVT, 4> ValueVTs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000090
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000091 /// RegVTs - The value types of the registers. This is the same size as
92 /// ValueVTs and it records, for each value, what the type of the assigned
93 /// register or registers are. (Individual values are never synthesized
94 /// from more than one type of register.)
95 ///
96 /// With virtual registers, the contents of RegVTs is redundant with TLI's
97 /// getRegisterType member function, however when with physical registers
98 /// it is necessary to have a separate record of the types.
99 ///
Owen Andersone50ed302009-08-10 22:56:29 +0000100 SmallVector<EVT, 4> RegVTs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000101
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000102 /// Regs - This list holds the registers assigned to the values.
103 /// Each legal or promoted value requires one register, and each
104 /// expanded value requires multiple registers.
105 ///
106 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000107
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000108 RegsForValue() : TLI(0) {}
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000109
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000110 RegsForValue(const TargetLowering &tli,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000111 const SmallVector<unsigned, 4> &regs,
Owen Andersone50ed302009-08-10 22:56:29 +0000112 EVT regvt, EVT valuevt)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000113 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
114 RegsForValue(const TargetLowering &tli,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000115 const SmallVector<unsigned, 4> &regs,
Owen Andersone50ed302009-08-10 22:56:29 +0000116 const SmallVector<EVT, 4> &regvts,
117 const SmallVector<EVT, 4> &valuevts)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000118 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
Owen Anderson23b9b192009-08-12 00:36:31 +0000119 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000120 unsigned Reg, const Type *Ty) : TLI(&tli) {
121 ComputeValueVTs(tli, Ty, ValueVTs);
122
123 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +0000124 EVT ValueVT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +0000125 unsigned NumRegs = TLI->getNumRegisters(Context, ValueVT);
126 EVT RegisterVT = TLI->getRegisterType(Context, ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000127 for (unsigned i = 0; i != NumRegs; ++i)
128 Regs.push_back(Reg + i);
129 RegVTs.push_back(RegisterVT);
130 Reg += NumRegs;
131 }
132 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000133
Evan Cheng8112b532010-02-10 01:21:02 +0000134 /// areValueTypesLegal - Return true if types of all the values are legal.
135 bool areValueTypesLegal() {
136 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
137 EVT RegisterVT = RegVTs[Value];
138 if (!TLI->isTypeLegal(RegisterVT))
139 return false;
140 }
141 return true;
142 }
143
144
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000145 /// append - Add the specified values to this one.
146 void append(const RegsForValue &RHS) {
147 TLI = RHS.TLI;
148 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
149 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
150 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
151 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000152
153
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000154 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000155 /// this value and returns the result as a ValueVTs value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000156 /// Chain/Flag as the input and updates them for the output Chain/Flag.
157 /// If the Flag pointer is NULL, no flag is used.
Bill Wendlingec72e322009-12-22 01:11:43 +0000158 SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl, unsigned Order,
159 SDValue &Chain, SDValue *Flag) const;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000160
161 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000162 /// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000163 /// Chain/Flag as the input and updates them for the output Chain/Flag.
164 /// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000165 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Bill Wendlingec72e322009-12-22 01:11:43 +0000166 unsigned Order, SDValue &Chain, SDValue *Flag) const;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000167
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000168 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
Evan Cheng697cbbf2009-03-20 18:03:34 +0000169 /// operand list. This adds the code marker, matching input operand index
170 /// (if applicable), and includes the number of values added into it.
171 void AddInlineAsmOperands(unsigned Code,
172 bool HasMatching, unsigned MatchingIdx,
Bill Wendling651ad132009-12-22 01:25:10 +0000173 SelectionDAG &DAG, unsigned Order,
174 std::vector<SDValue> &Ops) const;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000175 };
176}
177
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000178/// getCopyFromParts - Create a value that contains the specified legal parts
179/// combined into the value they represent. If the parts combine to a type
180/// larger then ValueVT then AssertOp can be used to specify whether the extra
181/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
182/// (ISD::AssertSext).
Bill Wendling3ea3c242009-12-22 02:10:19 +0000183static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl, unsigned Order,
Dale Johannesen66978ee2009-01-31 02:22:37 +0000184 const SDValue *Parts,
Owen Andersone50ed302009-08-10 22:56:29 +0000185 unsigned NumParts, EVT PartVT, EVT ValueVT,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000186 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000187 assert(NumParts > 0 && "No parts to assemble!");
Dan Gohmane9530ec2009-01-15 16:58:17 +0000188 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000189 SDValue Val = Parts[0];
190
191 if (NumParts > 1) {
192 // Assemble the value from multiple parts.
Eli Friedman2ac8b322009-05-20 06:02:09 +0000193 if (!ValueVT.isVector() && ValueVT.isInteger()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000194 unsigned PartBits = PartVT.getSizeInBits();
195 unsigned ValueBits = ValueVT.getSizeInBits();
196
197 // Assemble the power of 2 part.
198 unsigned RoundParts = NumParts & (NumParts - 1) ?
199 1 << Log2_32(NumParts) : NumParts;
200 unsigned RoundBits = PartBits * RoundParts;
Owen Andersone50ed302009-08-10 22:56:29 +0000201 EVT RoundVT = RoundBits == ValueBits ?
Owen Anderson23b9b192009-08-12 00:36:31 +0000202 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000203 SDValue Lo, Hi;
204
Owen Anderson23b9b192009-08-12 00:36:31 +0000205 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000206
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000207 if (RoundParts > 2) {
Bill Wendling3ea3c242009-12-22 02:10:19 +0000208 Lo = getCopyFromParts(DAG, dl, Order, Parts, RoundParts / 2,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000209 PartVT, HalfVT);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000210 Hi = getCopyFromParts(DAG, dl, Order, Parts + RoundParts / 2,
211 RoundParts / 2, PartVT, HalfVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000212 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000213 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
214 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000215 }
Bill Wendling3ea3c242009-12-22 02:10:19 +0000216
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000217 if (TLI.isBigEndian())
218 std::swap(Lo, Hi);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000219
Dale Johannesen66978ee2009-01-31 02:22:37 +0000220 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000221
222 if (RoundParts < NumParts) {
223 // Assemble the trailing non-power-of-2 part.
224 unsigned OddParts = NumParts - RoundParts;
Owen Anderson23b9b192009-08-12 00:36:31 +0000225 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000226 Hi = getCopyFromParts(DAG, dl, Order,
227 Parts + RoundParts, OddParts, PartVT, OddVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000228
229 // Combine the round and odd parts.
230 Lo = Val;
231 if (TLI.isBigEndian())
232 std::swap(Lo, Hi);
Owen Anderson23b9b192009-08-12 00:36:31 +0000233 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000234 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
235 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000236 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands92abc622009-01-31 15:50:11 +0000237 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000238 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
239 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000240 }
Eli Friedman2ac8b322009-05-20 06:02:09 +0000241 } else if (ValueVT.isVector()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000242 // Handle a multi-element vector.
Owen Andersone50ed302009-08-10 22:56:29 +0000243 EVT IntermediateVT, RegisterVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000244 unsigned NumIntermediates;
245 unsigned NumRegs =
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000246 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
Owen Anderson23b9b192009-08-12 00:36:31 +0000247 NumIntermediates, RegisterVT);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000248 assert(NumRegs == NumParts
249 && "Part count doesn't match vector breakdown!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000250 NumParts = NumRegs; // Silence a compiler warning.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000251 assert(RegisterVT == PartVT
252 && "Part type doesn't match vector breakdown!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000253 assert(RegisterVT == Parts[0].getValueType() &&
254 "Part type doesn't match part!");
255
256 // Assemble the parts into intermediate operands.
257 SmallVector<SDValue, 8> Ops(NumIntermediates);
258 if (NumIntermediates == NumParts) {
259 // If the register was not expanded, truncate or copy the value,
260 // as appropriate.
261 for (unsigned i = 0; i != NumParts; ++i)
Bill Wendling3ea3c242009-12-22 02:10:19 +0000262 Ops[i] = getCopyFromParts(DAG, dl, Order, &Parts[i], 1,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000263 PartVT, IntermediateVT);
264 } else if (NumParts > 0) {
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000265 // If the intermediate type was expanded, build the intermediate
266 // operands from the parts.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000267 assert(NumParts % NumIntermediates == 0 &&
268 "Must expand into a divisible number of parts!");
269 unsigned Factor = NumParts / NumIntermediates;
270 for (unsigned i = 0; i != NumIntermediates; ++i)
Bill Wendling3ea3c242009-12-22 02:10:19 +0000271 Ops[i] = getCopyFromParts(DAG, dl, Order, &Parts[i * Factor], Factor,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000272 PartVT, IntermediateVT);
273 }
274
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000275 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
276 // intermediate operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000277 Val = DAG.getNode(IntermediateVT.isVector() ?
Dale Johannesen66978ee2009-01-31 02:22:37 +0000278 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000279 ValueVT, &Ops[0], NumIntermediates);
Eli Friedman2ac8b322009-05-20 06:02:09 +0000280 } else if (PartVT.isFloatingPoint()) {
281 // FP split into multiple FP parts (for ppcf128)
Owen Anderson825b72b2009-08-11 20:47:22 +0000282 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
Eli Friedman2ac8b322009-05-20 06:02:09 +0000283 "Unexpected split");
284 SDValue Lo, Hi;
Owen Anderson825b72b2009-08-11 20:47:22 +0000285 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[0]);
286 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[1]);
Eli Friedman2ac8b322009-05-20 06:02:09 +0000287 if (TLI.isBigEndian())
288 std::swap(Lo, Hi);
289 Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi);
290 } else {
291 // FP split into integer parts (soft fp)
292 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
293 !PartVT.isVector() && "Unexpected split");
Owen Anderson23b9b192009-08-12 00:36:31 +0000294 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
Bill Wendling3ea3c242009-12-22 02:10:19 +0000295 Val = getCopyFromParts(DAG, dl, Order, Parts, NumParts, PartVT, IntVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000296 }
297 }
298
299 // There is now one part, held in Val. Correct it to match ValueVT.
300 PartVT = Val.getValueType();
301
302 if (PartVT == ValueVT)
303 return Val;
304
305 if (PartVT.isVector()) {
306 assert(ValueVT.isVector() && "Unknown vector conversion!");
Bill Wendling4533cac2010-01-28 21:51:40 +0000307 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000308 }
309
310 if (ValueVT.isVector()) {
311 assert(ValueVT.getVectorElementType() == PartVT &&
312 ValueVT.getVectorNumElements() == 1 &&
313 "Only trivial scalar-to-vector conversions should get here!");
Bill Wendling4533cac2010-01-28 21:51:40 +0000314 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000315 }
316
317 if (PartVT.isInteger() &&
318 ValueVT.isInteger()) {
319 if (ValueVT.bitsLT(PartVT)) {
320 // For a truncate, see if we have any information to
321 // indicate whether the truncated bits will always be
322 // zero or sign-extension.
323 if (AssertOp != ISD::DELETED_NODE)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000324 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000325 DAG.getValueType(ValueVT));
Bill Wendling4533cac2010-01-28 21:51:40 +0000326 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000327 } else {
Bill Wendling4533cac2010-01-28 21:51:40 +0000328 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000329 }
330 }
331
332 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Bill Wendling3ea3c242009-12-22 02:10:19 +0000333 if (ValueVT.bitsLT(Val.getValueType())) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000334 // FP_ROUND's are always exact here.
Bill Wendling4533cac2010-01-28 21:51:40 +0000335 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
336 DAG.getIntPtrConstant(1));
Bill Wendling3ea3c242009-12-22 02:10:19 +0000337 }
338
Bill Wendling4533cac2010-01-28 21:51:40 +0000339 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000340 }
341
Bill Wendling4533cac2010-01-28 21:51:40 +0000342 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
343 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000344
Torok Edwinc23197a2009-07-14 16:55:14 +0000345 llvm_unreachable("Unknown mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000346 return SDValue();
347}
348
349/// getCopyToParts - Create a series of nodes that contain the specified value
350/// split into legal parts. If the parts contain more bits than Val, then, for
351/// integers, ExtendKind can be used to specify how to generate the extra bits.
Bill Wendling3ea3c242009-12-22 02:10:19 +0000352static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, unsigned Order,
353 SDValue Val, SDValue *Parts, unsigned NumParts,
354 EVT PartVT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000355 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohmane9530ec2009-01-15 16:58:17 +0000356 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Owen Andersone50ed302009-08-10 22:56:29 +0000357 EVT PtrVT = TLI.getPointerTy();
358 EVT ValueVT = Val.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000359 unsigned PartBits = PartVT.getSizeInBits();
Dale Johannesen8a36f502009-02-25 22:39:13 +0000360 unsigned OrigNumParts = NumParts;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000361 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
362
363 if (!NumParts)
364 return;
365
366 if (!ValueVT.isVector()) {
367 if (PartVT == ValueVT) {
368 assert(NumParts == 1 && "No-op copy with multiple parts!");
369 Parts[0] = Val;
370 return;
371 }
372
373 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
374 // If the parts cover more bits than the value has, promote the value.
375 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
376 assert(NumParts == 1 && "Do not know what to promote to!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000377 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000378 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
Owen Anderson23b9b192009-08-12 00:36:31 +0000379 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000380 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000381 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000382 llvm_unreachable("Unknown mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000383 }
384 } else if (PartBits == ValueVT.getSizeInBits()) {
385 // Different types of the same size.
386 assert(NumParts == 1 && PartVT != ValueVT);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000387 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000388 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
389 // If the parts cover less bits than value has, truncate the value.
390 if (PartVT.isInteger() && ValueVT.isInteger()) {
Owen Anderson23b9b192009-08-12 00:36:31 +0000391 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000392 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000393 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000394 llvm_unreachable("Unknown mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000395 }
396 }
397
398 // The value may have changed - recompute ValueVT.
399 ValueVT = Val.getValueType();
400 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
401 "Failed to tile the value with PartVT!");
402
403 if (NumParts == 1) {
404 assert(PartVT == ValueVT && "Type conversion failed!");
405 Parts[0] = Val;
406 return;
407 }
408
409 // Expand the value into multiple parts.
410 if (NumParts & (NumParts - 1)) {
411 // The number of parts is not a power of 2. Split off and copy the tail.
412 assert(PartVT.isInteger() && ValueVT.isInteger() &&
413 "Do not know what to expand to!");
414 unsigned RoundParts = 1 << Log2_32(NumParts);
415 unsigned RoundBits = RoundParts * PartBits;
416 unsigned OddParts = NumParts - RoundParts;
Dale Johannesen66978ee2009-01-31 02:22:37 +0000417 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000418 DAG.getConstant(RoundBits,
Duncan Sands92abc622009-01-31 15:50:11 +0000419 TLI.getPointerTy()));
Bill Wendling3ea3c242009-12-22 02:10:19 +0000420 getCopyToParts(DAG, dl, Order, OddVal, Parts + RoundParts,
421 OddParts, PartVT);
422
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000423 if (TLI.isBigEndian())
424 // The odd parts were reversed by getCopyToParts - unreverse them.
425 std::reverse(Parts + RoundParts, Parts + NumParts);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000426
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000427 NumParts = RoundParts;
Owen Anderson23b9b192009-08-12 00:36:31 +0000428 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000429 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000430 }
431
432 // The number of parts is a power of 2. Repeatedly bisect the value using
433 // EXTRACT_ELEMENT.
Scott Michelfdc40a02009-02-17 22:15:04 +0000434 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
Chris Lattnerf031e8a2010-01-01 03:32:16 +0000435 EVT::getIntegerVT(*DAG.getContext(),
436 ValueVT.getSizeInBits()),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000437 Val);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000438
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000439 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
440 for (unsigned i = 0; i < NumParts; i += StepSize) {
441 unsigned ThisBits = StepSize * PartBits / 2;
Owen Anderson23b9b192009-08-12 00:36:31 +0000442 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000443 SDValue &Part0 = Parts[i];
444 SDValue &Part1 = Parts[i+StepSize/2];
445
Scott Michelfdc40a02009-02-17 22:15:04 +0000446 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000447 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000448 DAG.getConstant(1, PtrVT));
Scott Michelfdc40a02009-02-17 22:15:04 +0000449 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000450 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000451 DAG.getConstant(0, PtrVT));
452
453 if (ThisBits == PartBits && ThisVT != PartVT) {
Scott Michelfdc40a02009-02-17 22:15:04 +0000454 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000455 PartVT, Part0);
Scott Michelfdc40a02009-02-17 22:15:04 +0000456 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000457 PartVT, Part1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000458 }
459 }
460 }
461
462 if (TLI.isBigEndian())
Dale Johannesen8a36f502009-02-25 22:39:13 +0000463 std::reverse(Parts, Parts + OrigNumParts);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000464
465 return;
466 }
467
468 // Vector ValueVT.
469 if (NumParts == 1) {
470 if (PartVT != ValueVT) {
Bob Wilson5afffae2009-12-18 01:03:29 +0000471 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000472 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000473 } else {
474 assert(ValueVT.getVectorElementType() == PartVT &&
475 ValueVT.getVectorNumElements() == 1 &&
476 "Only trivial vector-to-scalar conversions should get here!");
Scott Michelfdc40a02009-02-17 22:15:04 +0000477 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000478 PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000479 DAG.getConstant(0, PtrVT));
480 }
481 }
482
483 Parts[0] = Val;
484 return;
485 }
486
487 // Handle a multi-element vector.
Owen Andersone50ed302009-08-10 22:56:29 +0000488 EVT IntermediateVT, RegisterVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000489 unsigned NumIntermediates;
Owen Anderson23b9b192009-08-12 00:36:31 +0000490 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
491 IntermediateVT, NumIntermediates, RegisterVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000492 unsigned NumElements = ValueVT.getVectorNumElements();
493
494 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
495 NumParts = NumRegs; // Silence a compiler warning.
496 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
497
498 // Split the vector into intermediate operands.
499 SmallVector<SDValue, 8> Ops(NumIntermediates);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000500 for (unsigned i = 0; i != NumIntermediates; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000501 if (IntermediateVT.isVector())
Scott Michelfdc40a02009-02-17 22:15:04 +0000502 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000503 IntermediateVT, Val,
504 DAG.getConstant(i * (NumElements / NumIntermediates),
505 PtrVT));
506 else
Scott Michelfdc40a02009-02-17 22:15:04 +0000507 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000508 IntermediateVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000509 DAG.getConstant(i, PtrVT));
Bill Wendling3ea3c242009-12-22 02:10:19 +0000510 }
511
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000512 // Split the intermediate operands into legal parts.
513 if (NumParts == NumIntermediates) {
514 // If the register was not expanded, promote or copy the value,
515 // as appropriate.
516 for (unsigned i = 0; i != NumParts; ++i)
Bill Wendling3ea3c242009-12-22 02:10:19 +0000517 getCopyToParts(DAG, dl, Order, Ops[i], &Parts[i], 1, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000518 } else if (NumParts > 0) {
519 // If the intermediate type was expanded, split each the value into
520 // legal parts.
521 assert(NumParts % NumIntermediates == 0 &&
522 "Must expand into a divisible number of parts!");
523 unsigned Factor = NumParts / NumIntermediates;
524 for (unsigned i = 0; i != NumIntermediates; ++i)
Bill Wendling3ea3c242009-12-22 02:10:19 +0000525 getCopyToParts(DAG, dl, Order, Ops[i], &Parts[i*Factor], Factor, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000526 }
527}
528
529
Dan Gohman2048b852009-11-23 18:04:58 +0000530void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000531 AA = &aa;
532 GFI = gfi;
533 TD = DAG.getTarget().getTargetData();
534}
535
536/// clear - Clear out the curret SelectionDAG and the associated
Dan Gohman2048b852009-11-23 18:04:58 +0000537/// state and prepare this SelectionDAGBuilder object to be used
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000538/// for a new block. This doesn't clear out information about
539/// additional blocks that are needed to complete switch lowering
540/// or PHI node updating; that information is cleared out as it is
541/// consumed.
Dan Gohman2048b852009-11-23 18:04:58 +0000542void SelectionDAGBuilder::clear() {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000543 NodeMap.clear();
544 PendingLoads.clear();
545 PendingExports.clear();
Evan Chengfb2e7522009-09-18 21:02:19 +0000546 EdgeMapping.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000547 DAG.clear();
Bill Wendling8fcf1702009-02-06 21:36:23 +0000548 CurDebugLoc = DebugLoc::getUnknownLoc();
Dan Gohman98ca4f22009-08-05 01:29:28 +0000549 HasTailCall = false;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000550}
551
552/// getRoot - Return the current virtual root of the Selection DAG,
553/// flushing any PendingLoad items. This must be done before emitting
554/// a store or any other node that may need to be ordered after any
555/// prior load instructions.
556///
Dan Gohman2048b852009-11-23 18:04:58 +0000557SDValue SelectionDAGBuilder::getRoot() {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000558 if (PendingLoads.empty())
559 return DAG.getRoot();
560
561 if (PendingLoads.size() == 1) {
562 SDValue Root = PendingLoads[0];
563 DAG.setRoot(Root);
564 PendingLoads.clear();
565 return Root;
566 }
567
568 // Otherwise, we have to make a token factor node.
Owen Anderson825b72b2009-08-11 20:47:22 +0000569 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000570 &PendingLoads[0], PendingLoads.size());
571 PendingLoads.clear();
572 DAG.setRoot(Root);
573 return Root;
574}
575
576/// getControlRoot - Similar to getRoot, but instead of flushing all the
577/// PendingLoad items, flush all the PendingExports items. It is necessary
578/// to do this before emitting a terminator instruction.
579///
Dan Gohman2048b852009-11-23 18:04:58 +0000580SDValue SelectionDAGBuilder::getControlRoot() {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000581 SDValue Root = DAG.getRoot();
582
583 if (PendingExports.empty())
584 return Root;
585
586 // Turn all of the CopyToReg chains into one factored node.
587 if (Root.getOpcode() != ISD::EntryToken) {
588 unsigned i = 0, e = PendingExports.size();
589 for (; i != e; ++i) {
590 assert(PendingExports[i].getNode()->getNumOperands() > 1);
591 if (PendingExports[i].getNode()->getOperand(0) == Root)
592 break; // Don't add the root if we already indirectly depend on it.
593 }
594
595 if (i == e)
596 PendingExports.push_back(Root);
597 }
598
Owen Anderson825b72b2009-08-11 20:47:22 +0000599 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000600 &PendingExports[0],
601 PendingExports.size());
602 PendingExports.clear();
603 DAG.setRoot(Root);
604 return Root;
605}
606
Bill Wendling4533cac2010-01-28 21:51:40 +0000607void SelectionDAGBuilder::AssignOrderingToNode(const SDNode *Node) {
608 if (DAG.GetOrdering(Node) != 0) return; // Already has ordering.
609 DAG.AssignOrdering(Node, SDNodeOrder);
610
611 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)
612 AssignOrderingToNode(Node->getOperand(I).getNode());
613}
614
Dan Gohman2048b852009-11-23 18:04:58 +0000615void SelectionDAGBuilder::visit(Instruction &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000616 visit(I.getOpcode(), I);
617}
618
Dan Gohman2048b852009-11-23 18:04:58 +0000619void SelectionDAGBuilder::visit(unsigned Opcode, User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000620 // Note: this doesn't use InstVisitor, because it has to work with
621 // ConstantExpr's in addition to instructions.
622 switch (Opcode) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000623 default: llvm_unreachable("Unknown instruction type encountered!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000624 // Build the switch statement using the Instruction.def file.
625#define HANDLE_INST(NUM, OPCODE, CLASS) \
Bill Wendling4533cac2010-01-28 21:51:40 +0000626 case Instruction::OPCODE: visit##OPCODE((CLASS&)I); break;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000627#include "llvm/Instruction.def"
628 }
Bill Wendling4533cac2010-01-28 21:51:40 +0000629
630 // Assign the ordering to the freshly created DAG nodes.
631 if (NodeMap.count(&I)) {
632 ++SDNodeOrder;
633 AssignOrderingToNode(getValue(&I).getNode());
634 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000635}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000636
Dan Gohman2048b852009-11-23 18:04:58 +0000637SDValue SelectionDAGBuilder::getValue(const Value *V) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000638 SDValue &N = NodeMap[V];
639 if (N.getNode()) return N;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000640
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000641 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
Owen Andersone50ed302009-08-10 22:56:29 +0000642 EVT VT = TLI.getValueType(V->getType(), true);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000643
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000644 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000645 return N = DAG.getConstant(*CI, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000646
647 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
648 return N = DAG.getGlobalAddress(GV, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000649
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000650 if (isa<ConstantPointerNull>(C))
651 return N = DAG.getConstant(0, TLI.getPointerTy());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000652
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000653 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000654 return N = DAG.getConstantFP(*CFP, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000655
Nate Begeman9008ca62009-04-27 18:41:29 +0000656 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
Dale Johannesene8d72302009-02-06 23:05:02 +0000657 return N = DAG.getUNDEF(VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000658
659 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
660 visit(CE->getOpcode(), *CE);
661 SDValue N1 = NodeMap[V];
662 assert(N1.getNode() && "visit didn't populate the ValueMap!");
663 return N1;
664 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000665
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000666 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
667 SmallVector<SDValue, 4> Constants;
668 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
669 OI != OE; ++OI) {
670 SDNode *Val = getValue(*OI).getNode();
Dan Gohmaned48caf2009-09-08 01:44:02 +0000671 // If the operand is an empty aggregate, there are no values.
672 if (!Val) continue;
673 // Add each leaf value from the operand to the Constants list
674 // to form a flattened list of all the values.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000675 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
676 Constants.push_back(SDValue(Val, i));
677 }
Bill Wendling87710f02009-12-21 23:47:40 +0000678
Bill Wendling4533cac2010-01-28 21:51:40 +0000679 return DAG.getMergeValues(&Constants[0], Constants.size(),
680 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000681 }
682
Duncan Sands1df98592010-02-16 11:11:14 +0000683 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000684 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
685 "Unknown struct or array constant!");
686
Owen Andersone50ed302009-08-10 22:56:29 +0000687 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000688 ComputeValueVTs(TLI, C->getType(), ValueVTs);
689 unsigned NumElts = ValueVTs.size();
690 if (NumElts == 0)
691 return SDValue(); // empty struct
692 SmallVector<SDValue, 4> Constants(NumElts);
693 for (unsigned i = 0; i != NumElts; ++i) {
Owen Andersone50ed302009-08-10 22:56:29 +0000694 EVT EltVT = ValueVTs[i];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000695 if (isa<UndefValue>(C))
Dale Johannesene8d72302009-02-06 23:05:02 +0000696 Constants[i] = DAG.getUNDEF(EltVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000697 else if (EltVT.isFloatingPoint())
698 Constants[i] = DAG.getConstantFP(0, EltVT);
699 else
700 Constants[i] = DAG.getConstant(0, EltVT);
701 }
Bill Wendling87710f02009-12-21 23:47:40 +0000702
Bill Wendling4533cac2010-01-28 21:51:40 +0000703 return DAG.getMergeValues(&Constants[0], NumElts,
704 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000705 }
706
Dan Gohman8c2b5252009-10-30 01:27:03 +0000707 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
Dan Gohman29cbade2009-11-20 23:18:13 +0000708 return DAG.getBlockAddress(BA, VT);
Dan Gohman8c2b5252009-10-30 01:27:03 +0000709
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000710 const VectorType *VecTy = cast<VectorType>(V->getType());
711 unsigned NumElements = VecTy->getNumElements();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000712
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000713 // Now that we know the number and type of the elements, get that number of
714 // elements into the Ops array based on what kind of constant it is.
715 SmallVector<SDValue, 16> Ops;
716 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
717 for (unsigned i = 0; i != NumElements; ++i)
718 Ops.push_back(getValue(CP->getOperand(i)));
719 } else {
Nate Begeman9008ca62009-04-27 18:41:29 +0000720 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
Owen Andersone50ed302009-08-10 22:56:29 +0000721 EVT EltVT = TLI.getValueType(VecTy->getElementType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000722
723 SDValue Op;
Nate Begeman9008ca62009-04-27 18:41:29 +0000724 if (EltVT.isFloatingPoint())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000725 Op = DAG.getConstantFP(0, EltVT);
726 else
727 Op = DAG.getConstant(0, EltVT);
728 Ops.assign(NumElements, Op);
729 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000730
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000731 // Create a BUILD_VECTOR node.
Bill Wendling4533cac2010-01-28 21:51:40 +0000732 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
733 VT, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000734 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000735
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000736 // If this is a static alloca, generate it as the frameindex instead of
737 // computation.
738 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
739 DenseMap<const AllocaInst*, int>::iterator SI =
740 FuncInfo.StaticAllocaMap.find(AI);
741 if (SI != FuncInfo.StaticAllocaMap.end())
742 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
743 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000744
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000745 unsigned InReg = FuncInfo.ValueMap[V];
746 assert(InReg && "Value not in map!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000747
Owen Anderson23b9b192009-08-12 00:36:31 +0000748 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000749 SDValue Chain = DAG.getEntryNode();
Bill Wendlingec72e322009-12-22 01:11:43 +0000750 return RFV.getCopyFromRegs(DAG, getCurDebugLoc(),
751 SDNodeOrder, Chain, NULL);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000752}
753
Kenneth Uildriks93ae4072010-01-16 23:37:33 +0000754/// Get the EVTs and ArgFlags collections that represent the legalized return
755/// type of the given function. This does not require a DAG or a return value,
756/// and is suitable for use before any DAGs for the function are constructed.
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000757static void getReturnInfo(const Type* ReturnType,
758 Attributes attr, SmallVectorImpl<EVT> &OutVTs,
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000759 SmallVectorImpl<ISD::ArgFlagsTy> &OutFlags,
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000760 TargetLowering &TLI,
761 SmallVectorImpl<uint64_t> *Offsets = 0) {
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000762 SmallVector<EVT, 4> ValueVTs;
Kenneth Uildriks93ae4072010-01-16 23:37:33 +0000763 ComputeValueVTs(TLI, ReturnType, ValueVTs);
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000764 unsigned NumValues = ValueVTs.size();
Kenneth Uildriks93ae4072010-01-16 23:37:33 +0000765 if (NumValues == 0) return;
766 unsigned Offset = 0;
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000767
768 for (unsigned j = 0, f = NumValues; j != f; ++j) {
769 EVT VT = ValueVTs[j];
770 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000771
772 if (attr & Attribute::SExt)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000773 ExtendKind = ISD::SIGN_EXTEND;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000774 else if (attr & Attribute::ZExt)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000775 ExtendKind = ISD::ZERO_EXTEND;
776
777 // FIXME: C calling convention requires the return type to be promoted to
778 // at least 32-bit. But this is not necessary for non-C calling
779 // conventions. The frontend should mark functions whose return values
780 // require promoting with signext or zeroext attributes.
781 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000782 EVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000783 if (VT.bitsLT(MinVT))
784 VT = MinVT;
785 }
786
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000787 unsigned NumParts = TLI.getNumRegisters(ReturnType->getContext(), VT);
788 EVT PartVT = TLI.getRegisterType(ReturnType->getContext(), VT);
Kenneth Uildriks93ae4072010-01-16 23:37:33 +0000789 unsigned PartSize = TLI.getTargetData()->getTypeAllocSize(
790 PartVT.getTypeForEVT(ReturnType->getContext()));
791
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000792 // 'inreg' on function refers to return value
793 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000794 if (attr & Attribute::InReg)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000795 Flags.setInReg();
796
797 // Propagate extension type if any
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000798 if (attr & Attribute::SExt)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000799 Flags.setSExt();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000800 else if (attr & Attribute::ZExt)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000801 Flags.setZExt();
802
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000803 for (unsigned i = 0; i < NumParts; ++i) {
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000804 OutVTs.push_back(PartVT);
805 OutFlags.push_back(Flags);
Kenneth Uildriks93ae4072010-01-16 23:37:33 +0000806 if (Offsets)
807 {
808 Offsets->push_back(Offset);
809 Offset += PartSize;
810 }
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000811 }
812 }
813}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000814
Dan Gohman2048b852009-11-23 18:04:58 +0000815void SelectionDAGBuilder::visitRet(ReturnInst &I) {
Dan Gohman98ca4f22009-08-05 01:29:28 +0000816 SDValue Chain = getControlRoot();
817 SmallVector<ISD::OutputArg, 8> Outs;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000818 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000819
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000820 if (!FLI.CanLowerReturn) {
821 unsigned DemoteReg = FLI.DemoteRegister;
822 const Function *F = I.getParent()->getParent();
823
824 // Emit a store of the return value through the virtual register.
825 // Leave Outs empty so that LowerReturn won't try to load return
826 // registers the usual way.
827 SmallVector<EVT, 1> PtrValueVTs;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000828 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000829 PtrValueVTs);
830
831 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
832 SDValue RetOp = getValue(I.getOperand(0));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000833
Owen Andersone50ed302009-08-10 22:56:29 +0000834 SmallVector<EVT, 4> ValueVTs;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000835 SmallVector<uint64_t, 4> Offsets;
836 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
Dan Gohman7ea1ca62008-10-21 20:00:42 +0000837 unsigned NumValues = ValueVTs.size();
Dan Gohman7ea1ca62008-10-21 20:00:42 +0000838
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000839 SmallVector<SDValue, 4> Chains(NumValues);
840 EVT PtrVT = PtrValueVTs[0];
Bill Wendling87710f02009-12-21 23:47:40 +0000841 for (unsigned i = 0; i != NumValues; ++i) {
842 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, RetPtr,
843 DAG.getConstant(Offsets[i], PtrVT));
844 Chains[i] =
845 DAG.getStore(Chain, getCurDebugLoc(),
846 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
David Greene1e559442010-02-15 17:00:31 +0000847 Add, NULL, Offsets[i], false, false, 0);
Bill Wendling87710f02009-12-21 23:47:40 +0000848 }
849
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000850 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
851 MVT::Other, &Chains[0], NumValues);
Chris Lattner25d58372010-02-28 18:53:13 +0000852 } else if (I.getNumOperands() != 0) {
853 SmallVector<EVT, 4> ValueVTs;
854 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
855 unsigned NumValues = ValueVTs.size();
856 if (NumValues) {
857 SDValue RetOp = getValue(I.getOperand(0));
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000858 for (unsigned j = 0, f = NumValues; j != f; ++j) {
859 EVT VT = ValueVTs[j];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000860
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000861 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000862
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000863 const Function *F = I.getParent()->getParent();
864 if (F->paramHasAttr(0, Attribute::SExt))
865 ExtendKind = ISD::SIGN_EXTEND;
866 else if (F->paramHasAttr(0, Attribute::ZExt))
867 ExtendKind = ISD::ZERO_EXTEND;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000868
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000869 // FIXME: C calling convention requires the return type to be promoted
870 // to at least 32-bit. But this is not necessary for non-C calling
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000871 // conventions. The frontend should mark functions whose return values
872 // require promoting with signext or zeroext attributes.
873 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
874 EVT MinVT = TLI.getRegisterType(*DAG.getContext(), MVT::i32);
875 if (VT.bitsLT(MinVT))
876 VT = MinVT;
877 }
878
879 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
880 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
881 SmallVector<SDValue, 4> Parts(NumParts);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000882 getCopyToParts(DAG, getCurDebugLoc(), SDNodeOrder,
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000883 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
884 &Parts[0], NumParts, PartVT, ExtendKind);
885
886 // 'inreg' on function refers to return value
887 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
888 if (F->paramHasAttr(0, Attribute::InReg))
889 Flags.setInReg();
890
891 // Propagate extension type if any
892 if (F->paramHasAttr(0, Attribute::SExt))
893 Flags.setSExt();
894 else if (F->paramHasAttr(0, Attribute::ZExt))
895 Flags.setZExt();
896
897 for (unsigned i = 0; i < NumParts; ++i)
898 Outs.push_back(ISD::OutputArg(Flags, Parts[i], /*isfixed=*/true));
Evan Cheng3927f432009-03-25 20:20:11 +0000899 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000900 }
901 }
Dan Gohman98ca4f22009-08-05 01:29:28 +0000902
903 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +0000904 CallingConv::ID CallConv =
905 DAG.getMachineFunction().getFunction()->getCallingConv();
Dan Gohman98ca4f22009-08-05 01:29:28 +0000906 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
907 Outs, getCurDebugLoc(), DAG);
Dan Gohman5e866062009-08-06 15:37:27 +0000908
909 // Verify that the target's LowerReturn behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +0000910 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +0000911 "LowerReturn didn't return a valid chain!");
912
913 // Update the DAG with the new chain value resulting from return lowering.
Dan Gohman98ca4f22009-08-05 01:29:28 +0000914 DAG.setRoot(Chain);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000915}
916
Dan Gohmanad62f532009-04-23 23:13:24 +0000917/// CopyToExportRegsIfNeeded - If the given value has virtual registers
918/// created for it, emit nodes to copy the value into the virtual
919/// registers.
Dan Gohman2048b852009-11-23 18:04:58 +0000920void SelectionDAGBuilder::CopyToExportRegsIfNeeded(Value *V) {
Dan Gohmanad62f532009-04-23 23:13:24 +0000921 if (!V->use_empty()) {
922 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
923 if (VMI != FuncInfo.ValueMap.end())
924 CopyValueToVirtualRegister(V, VMI->second);
925 }
926}
927
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000928/// ExportFromCurrentBlock - If this condition isn't known to be exported from
929/// the current basic block, add it to ValueMap now so that we'll get a
930/// CopyTo/FromReg.
Dan Gohman2048b852009-11-23 18:04:58 +0000931void SelectionDAGBuilder::ExportFromCurrentBlock(Value *V) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000932 // No need to export constants.
933 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000934
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000935 // Already exported?
936 if (FuncInfo.isExportedInst(V)) return;
937
938 unsigned Reg = FuncInfo.InitializeRegForValue(V);
939 CopyValueToVirtualRegister(V, Reg);
940}
941
Dan Gohman2048b852009-11-23 18:04:58 +0000942bool SelectionDAGBuilder::isExportableFromCurrentBlock(Value *V,
943 const BasicBlock *FromBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000944 // The operands of the setcc have to be in this block. We don't know
945 // how to export them from some other block.
946 if (Instruction *VI = dyn_cast<Instruction>(V)) {
947 // Can export from current BB.
948 if (VI->getParent() == FromBB)
949 return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000950
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000951 // Is already exported, noop.
952 return FuncInfo.isExportedInst(V);
953 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000954
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000955 // If this is an argument, we can export it if the BB is the entry block or
956 // if it is already exported.
957 if (isa<Argument>(V)) {
958 if (FromBB == &FromBB->getParent()->getEntryBlock())
959 return true;
960
961 // Otherwise, can only export this if it is already exported.
962 return FuncInfo.isExportedInst(V);
963 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000964
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000965 // Otherwise, constants can always be exported.
966 return true;
967}
968
969static bool InBlock(const Value *V, const BasicBlock *BB) {
970 if (const Instruction *I = dyn_cast<Instruction>(V))
971 return I->getParent() == BB;
972 return true;
973}
974
Dan Gohman8c1a6ca2008-10-17 18:18:45 +0000975/// getFCmpCondCode - Return the ISD condition code corresponding to
976/// the given LLVM IR floating-point condition code. This includes
977/// consideration of global floating-point math flags.
978///
979static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
980 ISD::CondCode FPC, FOC;
981 switch (Pred) {
982 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
983 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
984 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
985 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
986 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
987 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
988 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
989 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
990 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
991 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
992 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
993 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
994 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
995 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
996 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
997 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
998 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000999 llvm_unreachable("Invalid FCmp predicate opcode!");
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001000 FOC = FPC = ISD::SETFALSE;
1001 break;
1002 }
1003 if (FiniteOnlyFPMath())
1004 return FOC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001005 else
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001006 return FPC;
1007}
1008
1009/// getICmpCondCode - Return the ISD condition code corresponding to
1010/// the given LLVM IR integer condition code.
1011///
1012static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1013 switch (Pred) {
1014 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1015 case ICmpInst::ICMP_NE: return ISD::SETNE;
1016 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1017 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1018 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1019 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1020 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1021 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1022 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1023 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1024 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001025 llvm_unreachable("Invalid ICmp predicate opcode!");
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001026 return ISD::SETNE;
1027 }
1028}
1029
Dan Gohmanc2277342008-10-17 21:16:08 +00001030/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1031/// This function emits a branch and is used at the leaves of an OR or an
1032/// AND operator tree.
1033///
1034void
Dan Gohman2048b852009-11-23 18:04:58 +00001035SelectionDAGBuilder::EmitBranchForMergedCondition(Value *Cond,
1036 MachineBasicBlock *TBB,
1037 MachineBasicBlock *FBB,
1038 MachineBasicBlock *CurBB) {
Dan Gohmanc2277342008-10-17 21:16:08 +00001039 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001040
Dan Gohmanc2277342008-10-17 21:16:08 +00001041 // If the leaf of the tree is a comparison, merge the condition into
1042 // the caseblock.
1043 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1044 // The operands of the cmp have to be in this block. We don't know
1045 // how to export them from some other block. If this is the first block
1046 // of the sequence, no exporting is needed.
1047 if (CurBB == CurMBB ||
1048 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1049 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001050 ISD::CondCode Condition;
1051 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001052 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001053 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001054 Condition = getFCmpCondCode(FC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001055 } else {
1056 Condition = ISD::SETEQ; // silence warning.
Torok Edwinc23197a2009-07-14 16:55:14 +00001057 llvm_unreachable("Unknown compare instruction");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001058 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001059
1060 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001061 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1062 SwitchCases.push_back(CB);
1063 return;
1064 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001065 }
1066
1067 // Create a CaseBlock record representing this branch.
Owen Anderson5defacc2009-07-31 17:39:07 +00001068 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
Dan Gohmanc2277342008-10-17 21:16:08 +00001069 NULL, TBB, FBB, CurBB);
1070 SwitchCases.push_back(CB);
1071}
1072
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001073/// FindMergedConditions - If Cond is an expression like
Dan Gohman2048b852009-11-23 18:04:58 +00001074void SelectionDAGBuilder::FindMergedConditions(Value *Cond,
1075 MachineBasicBlock *TBB,
1076 MachineBasicBlock *FBB,
1077 MachineBasicBlock *CurBB,
1078 unsigned Opc) {
Dan Gohmanc2277342008-10-17 21:16:08 +00001079 // If this node is not part of the or/and tree, emit it as a branch.
1080 Instruction *BOp = dyn_cast<Instruction>(Cond);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001081 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohmanc2277342008-10-17 21:16:08 +00001082 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1083 BOp->getParent() != CurBB->getBasicBlock() ||
1084 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1085 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1086 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001087 return;
1088 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001089
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001090 // Create TmpBB after CurBB.
1091 MachineFunction::iterator BBI = CurBB;
1092 MachineFunction &MF = DAG.getMachineFunction();
1093 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1094 CurBB->getParent()->insert(++BBI, TmpBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001095
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001096 if (Opc == Instruction::Or) {
1097 // Codegen X | Y as:
1098 // jmp_if_X TBB
1099 // jmp TmpBB
1100 // TmpBB:
1101 // jmp_if_Y TBB
1102 // jmp FBB
1103 //
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001104
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001105 // Emit the LHS condition.
1106 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001107
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001108 // Emit the RHS condition into TmpBB.
1109 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1110 } else {
1111 assert(Opc == Instruction::And && "Unknown merge op!");
1112 // Codegen X & Y as:
1113 // jmp_if_X TmpBB
1114 // jmp FBB
1115 // TmpBB:
1116 // jmp_if_Y TBB
1117 // jmp FBB
1118 //
1119 // This requires creation of TmpBB after CurBB.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001120
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001121 // Emit the LHS condition.
1122 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001123
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001124 // Emit the RHS condition into TmpBB.
1125 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1126 }
1127}
1128
1129/// If the set of cases should be emitted as a series of branches, return true.
1130/// If we should emit this as a bunch of and/or'd together conditions, return
1131/// false.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001132bool
Dan Gohman2048b852009-11-23 18:04:58 +00001133SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001134 if (Cases.size() != 2) return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001135
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001136 // If this is two comparisons of the same values or'd or and'd together, they
1137 // will get folded into a single comparison, so don't emit two blocks.
1138 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1139 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1140 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1141 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1142 return false;
1143 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001144
Chris Lattner133ce872010-01-02 00:00:03 +00001145 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1146 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1147 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1148 Cases[0].CC == Cases[1].CC &&
1149 isa<Constant>(Cases[0].CmpRHS) &&
1150 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1151 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1152 return false;
1153 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1154 return false;
1155 }
1156
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001157 return true;
1158}
1159
Dan Gohman2048b852009-11-23 18:04:58 +00001160void SelectionDAGBuilder::visitBr(BranchInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001161 // Update machine-CFG edges.
1162 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1163
1164 // Figure out which block is immediately after the current one.
1165 MachineBasicBlock *NextBlock = 0;
1166 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001167 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001168 NextBlock = BBI;
1169
1170 if (I.isUnconditional()) {
1171 // Update machine-CFG edges.
1172 CurMBB->addSuccessor(Succ0MBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001173
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001174 // If this is not a fall-through branch, emit the branch.
Bill Wendling4533cac2010-01-28 21:51:40 +00001175 if (Succ0MBB != NextBlock)
1176 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001177 MVT::Other, getControlRoot(),
Bill Wendling4533cac2010-01-28 21:51:40 +00001178 DAG.getBasicBlock(Succ0MBB)));
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001179
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001180 return;
1181 }
1182
1183 // If this condition is one of the special cases we handle, do special stuff
1184 // now.
1185 Value *CondVal = I.getCondition();
1186 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1187
1188 // If this is a series of conditions that are or'd or and'd together, emit
1189 // this as a sequence of branches instead of setcc's with and/or operations.
1190 // For example, instead of something like:
1191 // cmp A, B
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001192 // C = seteq
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001193 // cmp D, E
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001194 // F = setle
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001195 // or C, F
1196 // jnz foo
1197 // Emit:
1198 // cmp A, B
1199 // je foo
1200 // cmp D, E
1201 // jle foo
1202 //
1203 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001204 if (BOp->hasOneUse() &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001205 (BOp->getOpcode() == Instruction::And ||
1206 BOp->getOpcode() == Instruction::Or)) {
1207 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1208 // If the compares in later blocks need to use values not currently
1209 // exported from this block, export them now. This block should always
1210 // be the first entry.
1211 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001212
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001213 // Allow some cases to be rejected.
1214 if (ShouldEmitAsBranches(SwitchCases)) {
1215 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1216 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1217 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1218 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001219
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001220 // Emit the branch for this block.
1221 visitSwitchCase(SwitchCases[0]);
1222 SwitchCases.erase(SwitchCases.begin());
1223 return;
1224 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001225
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001226 // Okay, we decided not to do this, remove any inserted MBB's and clear
1227 // SwitchCases.
1228 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001229 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001230
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001231 SwitchCases.clear();
1232 }
1233 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001234
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001235 // Create a CaseBlock record representing this branch.
Owen Anderson5defacc2009-07-31 17:39:07 +00001236 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001237 NULL, Succ0MBB, Succ1MBB, CurMBB);
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001238
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001239 // Use visitSwitchCase to actually insert the fast branch sequence for this
1240 // cond branch.
1241 visitSwitchCase(CB);
1242}
1243
1244/// visitSwitchCase - Emits the necessary code to represent a single node in
1245/// the binary search tree resulting from lowering a switch instruction.
Dan Gohman2048b852009-11-23 18:04:58 +00001246void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001247 SDValue Cond;
1248 SDValue CondLHS = getValue(CB.CmpLHS);
Dale Johannesenf5d97892009-02-04 01:48:28 +00001249 DebugLoc dl = getCurDebugLoc();
Anton Korobeynikov23218582008-12-23 22:25:27 +00001250
1251 // Build the setcc now.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001252 if (CB.CmpMHS == NULL) {
1253 // Fold "(X == true)" to X and "(X == false)" to !X to
1254 // handle common cases produced by branch lowering.
Owen Anderson5defacc2009-07-31 17:39:07 +00001255 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
Owen Andersonf53c3712009-07-21 02:47:59 +00001256 CB.CC == ISD::SETEQ)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001257 Cond = CondLHS;
Owen Anderson5defacc2009-07-31 17:39:07 +00001258 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
Owen Andersonf53c3712009-07-21 02:47:59 +00001259 CB.CC == ISD::SETEQ) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001260 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001261 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001262 } else
Owen Anderson825b72b2009-08-11 20:47:22 +00001263 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001264 } else {
1265 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1266
Anton Korobeynikov23218582008-12-23 22:25:27 +00001267 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1268 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001269
1270 SDValue CmpOp = getValue(CB.CmpMHS);
Owen Andersone50ed302009-08-10 22:56:29 +00001271 EVT VT = CmpOp.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001272
1273 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001274 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
Dale Johannesenf5d97892009-02-04 01:48:28 +00001275 ISD::SETLE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001276 } else {
Dale Johannesenf5d97892009-02-04 01:48:28 +00001277 SDValue SUB = DAG.getNode(ISD::SUB, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001278 VT, CmpOp, DAG.getConstant(Low, VT));
Owen Anderson825b72b2009-08-11 20:47:22 +00001279 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001280 DAG.getConstant(High-Low, VT), ISD::SETULE);
1281 }
1282 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001283
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001284 // Update successor info
1285 CurMBB->addSuccessor(CB.TrueBB);
1286 CurMBB->addSuccessor(CB.FalseBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001287
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001288 // Set NextBlock to be the MBB immediately after the current one, if any.
1289 // This is used to avoid emitting unnecessary branches to the next block.
1290 MachineBasicBlock *NextBlock = 0;
1291 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001292 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001293 NextBlock = BBI;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001294
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001295 // If the lhs block is the next block, invert the condition so that we can
1296 // fall through to the lhs instead of the rhs block.
1297 if (CB.TrueBB == NextBlock) {
1298 std::swap(CB.TrueBB, CB.FalseBB);
1299 SDValue True = DAG.getConstant(1, Cond.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001300 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001301 }
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001302
Dale Johannesenf5d97892009-02-04 01:48:28 +00001303 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00001304 MVT::Other, getControlRoot(), Cond,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001305 DAG.getBasicBlock(CB.TrueBB));
Bill Wendling87710f02009-12-21 23:47:40 +00001306
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001307 // If the branch was constant folded, fix up the CFG.
1308 if (BrCond.getOpcode() == ISD::BR) {
1309 CurMBB->removeSuccessor(CB.FalseBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001310 } else {
1311 // Otherwise, go ahead and insert the false branch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001312 if (BrCond == getControlRoot())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001313 CurMBB->removeSuccessor(CB.TrueBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001314
Bill Wendling4533cac2010-01-28 21:51:40 +00001315 if (CB.FalseBB != NextBlock)
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001316 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1317 DAG.getBasicBlock(CB.FalseBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001318 }
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001319
1320 DAG.setRoot(BrCond);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001321}
1322
1323/// visitJumpTable - Emit JumpTable node in the current MBB
Dan Gohman2048b852009-11-23 18:04:58 +00001324void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001325 // Emit the code for the jump table
1326 assert(JT.Reg != -1U && "Should lower JT Header first!");
Owen Andersone50ed302009-08-10 22:56:29 +00001327 EVT PTy = TLI.getPointerTy();
Dale Johannesena04b7572009-02-03 23:04:43 +00001328 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1329 JT.Reg, PTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001330 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001331 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1332 MVT::Other, Index.getValue(1),
1333 Table, Index);
1334 DAG.setRoot(BrJumpTable);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001335}
1336
1337/// visitJumpTableHeader - This function emits necessary code to produce index
1338/// in the JumpTable from switch case.
Dan Gohman2048b852009-11-23 18:04:58 +00001339void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1340 JumpTableHeader &JTH) {
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001341 // Subtract the lowest switch case value from the value being switched on and
1342 // conditional branch to default mbb if the result is greater than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001343 // difference between smallest and largest cases.
1344 SDValue SwitchOp = getValue(JTH.SValue);
Owen Andersone50ed302009-08-10 22:56:29 +00001345 EVT VT = SwitchOp.getValueType();
Bill Wendling87710f02009-12-21 23:47:40 +00001346 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001347 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001348
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001349 // The SDNode we just created, which holds the value being switched on minus
Dan Gohmanf451cb82010-02-10 16:03:48 +00001350 // the smallest case value, needs to be copied to a virtual register so it
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001351 // can be used as an index into the jump table in a subsequent basic block.
1352 // This value may be smaller or larger than the target's pointer type, and
1353 // therefore require extension or truncating.
Bill Wendling87710f02009-12-21 23:47:40 +00001354 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001355
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001356 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001357 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1358 JumpTableReg, SwitchOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001359 JT.Reg = JumpTableReg;
1360
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001361 // Emit the range check for the jump table, and branch to the default block
1362 // for the switch statement if the value being switched on exceeds the largest
1363 // case in the switch.
Dale Johannesenf5d97892009-02-04 01:48:28 +00001364 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00001365 TLI.getSetCCResultType(Sub.getValueType()), Sub,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001366 DAG.getConstant(JTH.Last-JTH.First,VT),
1367 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001368
1369 // Set NextBlock to be the MBB immediately after the current one, if any.
1370 // This is used to avoid emitting unnecessary branches to the next block.
1371 MachineBasicBlock *NextBlock = 0;
1372 MachineFunction::iterator BBI = CurMBB;
Bill Wendling87710f02009-12-21 23:47:40 +00001373
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001374 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001375 NextBlock = BBI;
1376
Dale Johannesen66978ee2009-01-31 02:22:37 +00001377 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001378 MVT::Other, CopyTo, CMP,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001379 DAG.getBasicBlock(JT.Default));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001380
Bill Wendling4533cac2010-01-28 21:51:40 +00001381 if (JT.MBB != NextBlock)
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001382 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1383 DAG.getBasicBlock(JT.MBB));
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001384
Bill Wendling87710f02009-12-21 23:47:40 +00001385 DAG.setRoot(BrCond);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001386}
1387
1388/// visitBitTestHeader - This function emits necessary code to produce value
1389/// suitable for "bit tests"
Dan Gohman2048b852009-11-23 18:04:58 +00001390void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001391 // Subtract the minimum value
1392 SDValue SwitchOp = getValue(B.SValue);
Owen Andersone50ed302009-08-10 22:56:29 +00001393 EVT VT = SwitchOp.getValueType();
Bill Wendling87710f02009-12-21 23:47:40 +00001394 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001395 DAG.getConstant(B.First, VT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001396
1397 // Check range
Dale Johannesenf5d97892009-02-04 01:48:28 +00001398 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00001399 TLI.getSetCCResultType(Sub.getValueType()),
1400 Sub, DAG.getConstant(B.Range, VT),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001401 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001402
Bill Wendling87710f02009-12-21 23:47:40 +00001403 SDValue ShiftOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(),
1404 TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001405
Duncan Sands92abc622009-01-31 15:50:11 +00001406 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001407 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1408 B.Reg, ShiftOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001409
1410 // Set NextBlock to be the MBB immediately after the current one, if any.
1411 // This is used to avoid emitting unnecessary branches to the next block.
1412 MachineBasicBlock *NextBlock = 0;
1413 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001414 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001415 NextBlock = BBI;
1416
1417 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1418
1419 CurMBB->addSuccessor(B.Default);
1420 CurMBB->addSuccessor(MBB);
1421
Dale Johannesen66978ee2009-01-31 02:22:37 +00001422 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001423 MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001424 DAG.getBasicBlock(B.Default));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001425
Bill Wendling4533cac2010-01-28 21:51:40 +00001426 if (MBB != NextBlock)
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001427 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1428 DAG.getBasicBlock(MBB));
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001429
Bill Wendling87710f02009-12-21 23:47:40 +00001430 DAG.setRoot(BrRange);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001431}
1432
1433/// visitBitTestCase - this function produces one "bit test"
Dan Gohman2048b852009-11-23 18:04:58 +00001434void SelectionDAGBuilder::visitBitTestCase(MachineBasicBlock* NextMBB,
1435 unsigned Reg,
1436 BitTestCase &B) {
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001437 // Make desired shift
Dale Johannesena04b7572009-02-03 23:04:43 +00001438 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
Duncan Sands92abc622009-01-31 15:50:11 +00001439 TLI.getPointerTy());
Scott Michelfdc40a02009-02-17 22:15:04 +00001440 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001441 TLI.getPointerTy(),
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001442 DAG.getConstant(1, TLI.getPointerTy()),
1443 ShiftOp);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001444
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001445 // Emit bit tests and jumps
Scott Michelfdc40a02009-02-17 22:15:04 +00001446 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001447 TLI.getPointerTy(), SwitchVal,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001448 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Dale Johannesenf5d97892009-02-04 01:48:28 +00001449 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1450 TLI.getSetCCResultType(AndOp.getValueType()),
Duncan Sands5480c042009-01-01 15:52:00 +00001451 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001452 ISD::SETNE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001453
1454 CurMBB->addSuccessor(B.TargetBB);
1455 CurMBB->addSuccessor(NextMBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001456
Dale Johannesen66978ee2009-01-31 02:22:37 +00001457 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001458 MVT::Other, getControlRoot(),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001459 AndCmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001460
1461 // Set NextBlock to be the MBB immediately after the current one, if any.
1462 // This is used to avoid emitting unnecessary branches to the next block.
1463 MachineBasicBlock *NextBlock = 0;
1464 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001465 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001466 NextBlock = BBI;
1467
Bill Wendling4533cac2010-01-28 21:51:40 +00001468 if (NextMBB != NextBlock)
Bill Wendling0777e922009-12-21 21:59:52 +00001469 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1470 DAG.getBasicBlock(NextMBB));
Bill Wendling0777e922009-12-21 21:59:52 +00001471
Bill Wendling87710f02009-12-21 23:47:40 +00001472 DAG.setRoot(BrAnd);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001473}
1474
Dan Gohman2048b852009-11-23 18:04:58 +00001475void SelectionDAGBuilder::visitInvoke(InvokeInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001476 // Retrieve successors.
1477 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1478 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1479
Gabor Greifb67e6b32009-01-15 11:10:44 +00001480 const Value *Callee(I.getCalledValue());
1481 if (isa<InlineAsm>(Callee))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001482 visitInlineAsm(&I);
1483 else
Gabor Greifb67e6b32009-01-15 11:10:44 +00001484 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001485
1486 // If the value of the invoke is used outside of its defining block, make it
1487 // available as a virtual register.
Dan Gohmanad62f532009-04-23 23:13:24 +00001488 CopyToExportRegsIfNeeded(&I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001489
1490 // Update successor info
1491 CurMBB->addSuccessor(Return);
1492 CurMBB->addSuccessor(LandingPad);
1493
1494 // Drop into normal successor.
Bill Wendling4533cac2010-01-28 21:51:40 +00001495 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1496 MVT::Other, getControlRoot(),
1497 DAG.getBasicBlock(Return)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001498}
1499
Dan Gohman2048b852009-11-23 18:04:58 +00001500void SelectionDAGBuilder::visitUnwind(UnwindInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001501}
1502
1503/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1504/// small case ranges).
Dan Gohman2048b852009-11-23 18:04:58 +00001505bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
1506 CaseRecVector& WorkList,
1507 Value* SV,
1508 MachineBasicBlock* Default) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001509 Case& BackCase = *(CR.Range.second-1);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001510
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001511 // Size is the number of Cases represented by this range.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001512 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001513 if (Size > 3)
Anton Korobeynikov23218582008-12-23 22:25:27 +00001514 return false;
1515
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001516 // Get the MachineFunction which holds the current MBB. This is used when
1517 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001518 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001519
1520 // Figure out which block is immediately after the current one.
1521 MachineBasicBlock *NextBlock = 0;
1522 MachineFunction::iterator BBI = CR.CaseBB;
1523
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001524 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001525 NextBlock = BBI;
1526
1527 // TODO: If any two of the cases has the same destination, and if one value
1528 // is the same as the other, but has one bit unset that the other has set,
1529 // use bit manipulation to do two compares at once. For example:
1530 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Anton Korobeynikov23218582008-12-23 22:25:27 +00001531
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001532 // Rearrange the case blocks so that the last one falls through if possible.
1533 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1534 // The last case block won't fall through into 'NextBlock' if we emit the
1535 // branches in this order. See if rearranging a case value would help.
1536 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1537 if (I->BB == NextBlock) {
1538 std::swap(*I, BackCase);
1539 break;
1540 }
1541 }
1542 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001543
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001544 // Create a CaseBlock record representing a conditional branch to
1545 // the Case's target mbb if the value being switched on SV is equal
1546 // to C.
1547 MachineBasicBlock *CurBlock = CR.CaseBB;
1548 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1549 MachineBasicBlock *FallThrough;
1550 if (I != E-1) {
1551 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1552 CurMF->insert(BBI, FallThrough);
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001553
1554 // Put SV in a virtual register to make it available from the new blocks.
1555 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001556 } else {
1557 // If the last case doesn't match, go to the default block.
1558 FallThrough = Default;
1559 }
1560
1561 Value *RHS, *LHS, *MHS;
1562 ISD::CondCode CC;
1563 if (I->High == I->Low) {
1564 // This is just small small case range :) containing exactly 1 case
1565 CC = ISD::SETEQ;
1566 LHS = SV; RHS = I->High; MHS = NULL;
1567 } else {
1568 CC = ISD::SETLE;
1569 LHS = I->Low; MHS = SV; RHS = I->High;
1570 }
1571 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001572
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001573 // If emitting the first comparison, just call visitSwitchCase to emit the
1574 // code into the current block. Otherwise, push the CaseBlock onto the
1575 // vector to be later processed by SDISel, and insert the node's MBB
1576 // before the next MBB.
1577 if (CurBlock == CurMBB)
1578 visitSwitchCase(CB);
1579 else
1580 SwitchCases.push_back(CB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001581
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001582 CurBlock = FallThrough;
1583 }
1584
1585 return true;
1586}
1587
1588static inline bool areJTsAllowed(const TargetLowering &TLI) {
1589 return !DisableJumpTables &&
Owen Anderson825b72b2009-08-11 20:47:22 +00001590 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1591 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001592}
Anton Korobeynikov23218582008-12-23 22:25:27 +00001593
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001594static APInt ComputeRange(const APInt &First, const APInt &Last) {
1595 APInt LastExt(Last), FirstExt(First);
1596 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1597 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1598 return (LastExt - FirstExt + 1ULL);
1599}
1600
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001601/// handleJTSwitchCase - Emit jumptable for current switch case range
Dan Gohman2048b852009-11-23 18:04:58 +00001602bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR,
1603 CaseRecVector& WorkList,
1604 Value* SV,
1605 MachineBasicBlock* Default) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001606 Case& FrontCase = *CR.Range.first;
1607 Case& BackCase = *(CR.Range.second-1);
1608
Chris Lattnere880efe2009-11-07 07:50:34 +00001609 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1610 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001611
Chris Lattnere880efe2009-11-07 07:50:34 +00001612 APInt TSize(First.getBitWidth(), 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001613 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1614 I!=E; ++I)
1615 TSize += I->size();
1616
Chris Lattnere880efe2009-11-07 07:50:34 +00001617 if (!areJTsAllowed(TLI) || TSize.ult(APInt(First.getBitWidth(), 4)))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001618 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001619
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001620 APInt Range = ComputeRange(First, Last);
Chris Lattnere880efe2009-11-07 07:50:34 +00001621 double Density = TSize.roundToDouble() / Range.roundToDouble();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001622 if (Density < 0.4)
1623 return false;
1624
David Greene4b69d992010-01-05 01:24:57 +00001625 DEBUG(dbgs() << "Lowering jump table\n"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001626 << "First entry: " << First << ". Last entry: " << Last << '\n'
1627 << "Range: " << Range
1628 << "Size: " << TSize << ". Density: " << Density << "\n\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001629
1630 // Get the MachineFunction which holds the current MBB. This is used when
1631 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001632 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001633
1634 // Figure out which block is immediately after the current one.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001635 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands51498522009-09-06 18:03:32 +00001636 ++BBI;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001637
1638 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1639
1640 // Create a new basic block to hold the code for loading the address
1641 // of the jump table, and jumping to it. Update successor information;
1642 // we will either branch to the default case for the switch, or the jump
1643 // table.
1644 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1645 CurMF->insert(BBI, JumpTableBB);
1646 CR.CaseBB->addSuccessor(Default);
1647 CR.CaseBB->addSuccessor(JumpTableBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001648
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001649 // Build a vector of destination BBs, corresponding to each target
1650 // of the jump table. If the value of the jump table slot corresponds to
1651 // a case statement, push the case's BB onto the vector, otherwise, push
1652 // the default BB.
1653 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001654 APInt TEI = First;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001655 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Chris Lattner071c62f2010-01-25 23:26:13 +00001656 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
1657 const APInt &High = cast<ConstantInt>(I->High)->getValue();
Anton Korobeynikov23218582008-12-23 22:25:27 +00001658
1659 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001660 DestBBs.push_back(I->BB);
1661 if (TEI==High)
1662 ++I;
1663 } else {
1664 DestBBs.push_back(Default);
1665 }
1666 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001667
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001668 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001669 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1670 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001671 E = DestBBs.end(); I != E; ++I) {
1672 if (!SuccsHandled[(*I)->getNumber()]) {
1673 SuccsHandled[(*I)->getNumber()] = true;
1674 JumpTableBB->addSuccessor(*I);
1675 }
1676 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001677
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001678 // Create a jump table index for this jump table, or return an existing
1679 // one.
Chris Lattner071c62f2010-01-25 23:26:13 +00001680 unsigned JTEncoding = TLI.getJumpTableEncoding();
1681 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
1682 ->getJumpTableIndex(DestBBs);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001683
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001684 // Set the jump table information so that we can codegen it as a second
1685 // MachineBasicBlock
1686 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1687 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1688 if (CR.CaseBB == CurMBB)
1689 visitJumpTableHeader(JT, JTH);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001690
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001691 JTCases.push_back(JumpTableBlock(JTH, JT));
1692
1693 return true;
1694}
1695
1696/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1697/// 2 subtrees.
Dan Gohman2048b852009-11-23 18:04:58 +00001698bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
1699 CaseRecVector& WorkList,
1700 Value* SV,
1701 MachineBasicBlock* Default) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001702 // Get the MachineFunction which holds the current MBB. This is used when
1703 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001704 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001705
1706 // Figure out which block is immediately after the current one.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001707 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands51498522009-09-06 18:03:32 +00001708 ++BBI;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001709
1710 Case& FrontCase = *CR.Range.first;
1711 Case& BackCase = *(CR.Range.second-1);
1712 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1713
1714 // Size is the number of Cases represented by this range.
1715 unsigned Size = CR.Range.second - CR.Range.first;
1716
Chris Lattnere880efe2009-11-07 07:50:34 +00001717 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1718 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001719 double FMetric = 0;
1720 CaseItr Pivot = CR.Range.first + Size/2;
1721
1722 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1723 // (heuristically) allow us to emit JumpTable's later.
Chris Lattnere880efe2009-11-07 07:50:34 +00001724 APInt TSize(First.getBitWidth(), 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001725 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1726 I!=E; ++I)
1727 TSize += I->size();
1728
Chris Lattnere880efe2009-11-07 07:50:34 +00001729 APInt LSize = FrontCase.size();
1730 APInt RSize = TSize-LSize;
David Greene4b69d992010-01-05 01:24:57 +00001731 DEBUG(dbgs() << "Selecting best pivot: \n"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001732 << "First: " << First << ", Last: " << Last <<'\n'
1733 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001734 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1735 J!=E; ++I, ++J) {
Chris Lattnere880efe2009-11-07 07:50:34 +00001736 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
1737 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001738 APInt Range = ComputeRange(LEnd, RBegin);
1739 assert((Range - 2ULL).isNonNegative() &&
1740 "Invalid case distance");
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00001741 double LDensity = (double)LSize.roundToDouble() /
Chris Lattnere880efe2009-11-07 07:50:34 +00001742 (LEnd - First + 1ULL).roundToDouble();
1743 double RDensity = (double)RSize.roundToDouble() /
1744 (Last - RBegin + 1ULL).roundToDouble();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001745 double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001746 // Should always split in some non-trivial place
David Greene4b69d992010-01-05 01:24:57 +00001747 DEBUG(dbgs() <<"=>Step\n"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001748 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1749 << "LDensity: " << LDensity
1750 << ", RDensity: " << RDensity << '\n'
1751 << "Metric: " << Metric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001752 if (FMetric < Metric) {
1753 Pivot = J;
1754 FMetric = Metric;
David Greene4b69d992010-01-05 01:24:57 +00001755 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001756 }
1757
1758 LSize += J->size();
1759 RSize -= J->size();
1760 }
1761 if (areJTsAllowed(TLI)) {
1762 // If our case is dense we *really* should handle it earlier!
1763 assert((FMetric > 0) && "Should handle dense range earlier!");
1764 } else {
1765 Pivot = CR.Range.first + Size/2;
1766 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001767
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001768 CaseRange LHSR(CR.Range.first, Pivot);
1769 CaseRange RHSR(Pivot, CR.Range.second);
1770 Constant *C = Pivot->Low;
1771 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001772
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001773 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001774 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001775 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001776 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001777 // Pivot's Value, then we can branch directly to the LHS's Target,
1778 // rather than creating a leaf node for it.
1779 if ((LHSR.second - LHSR.first) == 1 &&
1780 LHSR.first->High == CR.GE &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001781 cast<ConstantInt>(C)->getValue() ==
1782 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001783 TrueBB = LHSR.first->BB;
1784 } else {
1785 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1786 CurMF->insert(BBI, TrueBB);
1787 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001788
1789 // Put SV in a virtual register to make it available from the new blocks.
1790 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001791 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001792
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001793 // Similar to the optimization above, if the Value being switched on is
1794 // known to be less than the Constant CR.LT, and the current Case Value
1795 // is CR.LT - 1, then we can branch directly to the target block for
1796 // the current Case Value, rather than emitting a RHS leaf node for it.
1797 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001798 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1799 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001800 FalseBB = RHSR.first->BB;
1801 } else {
1802 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1803 CurMF->insert(BBI, FalseBB);
1804 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001805
1806 // Put SV in a virtual register to make it available from the new blocks.
1807 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001808 }
1809
1810 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001811 // the LHS node if the value being switched on SV is less than C.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001812 // Otherwise, branch to LHS.
1813 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1814
1815 if (CR.CaseBB == CurMBB)
1816 visitSwitchCase(CB);
1817 else
1818 SwitchCases.push_back(CB);
1819
1820 return true;
1821}
1822
1823/// handleBitTestsSwitchCase - if current case range has few destination and
1824/// range span less, than machine word bitwidth, encode case range into series
1825/// of masks and emit bit tests with these masks.
Dan Gohman2048b852009-11-23 18:04:58 +00001826bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
1827 CaseRecVector& WorkList,
1828 Value* SV,
1829 MachineBasicBlock* Default){
Owen Andersone50ed302009-08-10 22:56:29 +00001830 EVT PTy = TLI.getPointerTy();
Owen Anderson77547be2009-08-10 18:56:59 +00001831 unsigned IntPtrBits = PTy.getSizeInBits();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001832
1833 Case& FrontCase = *CR.Range.first;
1834 Case& BackCase = *(CR.Range.second-1);
1835
1836 // Get the MachineFunction which holds the current MBB. This is used when
1837 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001838 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001839
Anton Korobeynikovd34167a2009-05-08 18:51:34 +00001840 // If target does not have legal shift left, do not emit bit tests at all.
1841 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
1842 return false;
1843
Anton Korobeynikov23218582008-12-23 22:25:27 +00001844 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001845 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1846 I!=E; ++I) {
1847 // Single case counts one, case range - two.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001848 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001849 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001850
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001851 // Count unique destinations
1852 SmallSet<MachineBasicBlock*, 4> Dests;
1853 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1854 Dests.insert(I->BB);
1855 if (Dests.size() > 3)
1856 // Don't bother the code below, if there are too much unique destinations
1857 return false;
1858 }
David Greene4b69d992010-01-05 01:24:57 +00001859 DEBUG(dbgs() << "Total number of unique destinations: "
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00001860 << Dests.size() << '\n'
1861 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001862
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001863 // Compute span of values.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001864 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1865 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001866 APInt cmpRange = maxValue - minValue;
1867
David Greene4b69d992010-01-05 01:24:57 +00001868 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001869 << "Low bound: " << minValue << '\n'
1870 << "High bound: " << maxValue << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001871
1872 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001873 (!(Dests.size() == 1 && numCmps >= 3) &&
1874 !(Dests.size() == 2 && numCmps >= 5) &&
1875 !(Dests.size() >= 3 && numCmps >= 6)))
1876 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001877
David Greene4b69d992010-01-05 01:24:57 +00001878 DEBUG(dbgs() << "Emitting bit tests\n");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001879 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1880
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001881 // Optimize the case where all the case values fit in a
1882 // word without having to subtract minValue. In this case,
1883 // we can optimize away the subtraction.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001884 if (minValue.isNonNegative() &&
1885 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1886 cmpRange = maxValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001887 } else {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001888 lowBound = minValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001889 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001890
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001891 CaseBitsVector CasesBits;
1892 unsigned i, count = 0;
1893
1894 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1895 MachineBasicBlock* Dest = I->BB;
1896 for (i = 0; i < count; ++i)
1897 if (Dest == CasesBits[i].BB)
1898 break;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001899
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001900 if (i == count) {
1901 assert((count < 3) && "Too much destinations to test!");
1902 CasesBits.push_back(CaseBits(0, Dest, 0));
1903 count++;
1904 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001905
1906 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1907 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1908
1909 uint64_t lo = (lowValue - lowBound).getZExtValue();
1910 uint64_t hi = (highValue - lowBound).getZExtValue();
1911
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001912 for (uint64_t j = lo; j <= hi; j++) {
1913 CasesBits[i].Mask |= 1ULL << j;
1914 CasesBits[i].Bits++;
1915 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001916
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001917 }
1918 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001919
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001920 BitTestInfo BTC;
1921
1922 // Figure out which block is immediately after the current one.
1923 MachineFunction::iterator BBI = CR.CaseBB;
1924 ++BBI;
1925
1926 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1927
David Greene4b69d992010-01-05 01:24:57 +00001928 DEBUG(dbgs() << "Cases:\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001929 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
David Greene4b69d992010-01-05 01:24:57 +00001930 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001931 << ", Bits: " << CasesBits[i].Bits
1932 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001933
1934 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1935 CurMF->insert(BBI, CaseBB);
1936 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1937 CaseBB,
1938 CasesBits[i].BB));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001939
1940 // Put SV in a virtual register to make it available from the new blocks.
1941 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001942 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001943
1944 BitTestBlock BTB(lowBound, cmpRange, SV,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001945 -1U, (CR.CaseBB == CurMBB),
1946 CR.CaseBB, Default, BTC);
1947
1948 if (CR.CaseBB == CurMBB)
1949 visitBitTestHeader(BTB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001950
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001951 BitTestCases.push_back(BTB);
1952
1953 return true;
1954}
1955
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001956/// Clusterify - Transform simple list of Cases into list of CaseRange's
Dan Gohman2048b852009-11-23 18:04:58 +00001957size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
1958 const SwitchInst& SI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001959 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001960
1961 // Start with "simple" cases
Anton Korobeynikov23218582008-12-23 22:25:27 +00001962 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001963 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1964 Cases.push_back(Case(SI.getSuccessorValue(i),
1965 SI.getSuccessorValue(i),
1966 SMBB));
1967 }
1968 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1969
1970 // Merge case into clusters
Anton Korobeynikov23218582008-12-23 22:25:27 +00001971 if (Cases.size() >= 2)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001972 // Must recompute end() each iteration because it may be
1973 // invalidated by erase if we hold on to it
Anton Korobeynikov23218582008-12-23 22:25:27 +00001974 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
1975 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
1976 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001977 MachineBasicBlock* nextBB = J->BB;
1978 MachineBasicBlock* currentBB = I->BB;
1979
1980 // If the two neighboring cases go to the same destination, merge them
1981 // into a single case.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001982 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001983 I->High = J->High;
1984 J = Cases.erase(J);
1985 } else {
1986 I = J++;
1987 }
1988 }
1989
1990 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1991 if (I->Low != I->High)
1992 // A range counts double, since it requires two compares.
1993 ++numCmps;
1994 }
1995
1996 return numCmps;
1997}
1998
Dan Gohman2048b852009-11-23 18:04:58 +00001999void SelectionDAGBuilder::visitSwitch(SwitchInst &SI) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002000 // Figure out which block is immediately after the current one.
2001 MachineBasicBlock *NextBlock = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002002 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2003
2004 // If there is only the default destination, branch to it if it is not the
2005 // next basic block. Otherwise, just fall through.
2006 if (SI.getNumOperands() == 2) {
2007 // Update machine-CFG edges.
2008
2009 // If this is not a fall-through branch, emit the branch.
2010 CurMBB->addSuccessor(Default);
Bill Wendling4533cac2010-01-28 21:51:40 +00002011 if (Default != NextBlock)
2012 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
2013 MVT::Other, getControlRoot(),
2014 DAG.getBasicBlock(Default)));
Bill Wendling49fcff82009-12-21 22:30:11 +00002015
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002016 return;
2017 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002018
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002019 // If there are any non-default case statements, create a vector of Cases
2020 // representing each one, and sort the vector so that we can efficiently
2021 // create a binary search tree from them.
2022 CaseVector Cases;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002023 size_t numCmps = Clusterify(Cases, SI);
David Greene4b69d992010-01-05 01:24:57 +00002024 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002025 << ". Total compares: " << numCmps << '\n');
Devang Patel8a84e442009-01-05 17:31:22 +00002026 numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002027
2028 // Get the Value to be switched on and default basic blocks, which will be
2029 // inserted into CaseBlock records, representing basic blocks in the binary
2030 // search tree.
2031 Value *SV = SI.getOperand(0);
2032
2033 // Push the initial CaseRec onto the worklist
2034 CaseRecVector WorkList;
2035 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2036
2037 while (!WorkList.empty()) {
2038 // Grab a record representing a case range to process off the worklist
2039 CaseRec CR = WorkList.back();
2040 WorkList.pop_back();
2041
2042 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2043 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002044
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002045 // If the range has few cases (two or less) emit a series of specific
2046 // tests.
2047 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2048 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002049
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002050 // If the switch has more than 5 blocks, and at least 40% dense, and the
2051 // target supports indirect branches, then emit a jump table rather than
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002052 // lowering the switch to a binary tree of conditional branches.
2053 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2054 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002055
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002056 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2057 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2058 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2059 }
2060}
2061
Dan Gohman2048b852009-11-23 18:04:58 +00002062void SelectionDAGBuilder::visitIndirectBr(IndirectBrInst &I) {
Jakob Stoklund Olesen598b24c2010-02-11 00:34:18 +00002063 // Update machine-CFG edges with unique successors.
Jakob Stoklund Olesenb5b90ed2010-02-11 18:06:56 +00002064 SmallVector<BasicBlock*, 32> succs;
Jakob Stoklund Olesen598b24c2010-02-11 00:34:18 +00002065 succs.reserve(I.getNumSuccessors());
Dan Gohmaneef55dc2009-10-27 22:10:34 +00002066 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
Jakob Stoklund Olesen598b24c2010-02-11 00:34:18 +00002067 succs.push_back(I.getSuccessor(i));
Jakob Stoklund Olesenb5b90ed2010-02-11 18:06:56 +00002068 array_pod_sort(succs.begin(), succs.end());
Jakob Stoklund Olesen598b24c2010-02-11 00:34:18 +00002069 succs.erase(std::unique(succs.begin(), succs.end()), succs.end());
2070 for (unsigned i = 0, e = succs.size(); i != e; ++i)
2071 CurMBB->addSuccessor(FuncInfo.MBBMap[succs[i]]);
Dan Gohmaneef55dc2009-10-27 22:10:34 +00002072
Bill Wendling4533cac2010-01-28 21:51:40 +00002073 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2074 MVT::Other, getControlRoot(),
2075 getValue(I.getAddress())));
Bill Wendling49fcff82009-12-21 22:30:11 +00002076}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002077
Dan Gohman2048b852009-11-23 18:04:58 +00002078void SelectionDAGBuilder::visitFSub(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002079 // -0.0 - X --> fneg
2080 const Type *Ty = I.getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002081 if (Ty->isVectorTy()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002082 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2083 const VectorType *DestTy = cast<VectorType>(I.getType());
2084 const Type *ElTy = DestTy->getElementType();
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002085 unsigned VL = DestTy->getNumElements();
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002086 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00002087 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002088 if (CV == CNZ) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002089 SDValue Op2 = getValue(I.getOperand(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00002090 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2091 Op2.getValueType(), Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002092 return;
2093 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002094 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002095 }
Bill Wendling49fcff82009-12-21 22:30:11 +00002096
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002097 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002098 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002099 SDValue Op2 = getValue(I.getOperand(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00002100 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2101 Op2.getValueType(), Op2));
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002102 return;
2103 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002104
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002105 visitBinary(I, ISD::FSUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002106}
2107
Dan Gohman2048b852009-11-23 18:04:58 +00002108void SelectionDAGBuilder::visitBinary(User &I, unsigned OpCode) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002109 SDValue Op1 = getValue(I.getOperand(0));
2110 SDValue Op2 = getValue(I.getOperand(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00002111 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2112 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002113}
2114
Dan Gohman2048b852009-11-23 18:04:58 +00002115void SelectionDAGBuilder::visitShift(User &I, unsigned Opcode) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002116 SDValue Op1 = getValue(I.getOperand(0));
2117 SDValue Op2 = getValue(I.getOperand(1));
Duncan Sands1df98592010-02-16 11:11:14 +00002118 if (!I.getType()->isVectorTy() &&
Dan Gohman57fc82d2009-04-09 03:51:29 +00002119 Op2.getValueType() != TLI.getShiftAmountTy()) {
2120 // If the operand is smaller than the shift count type, promote it.
Owen Andersone50ed302009-08-10 22:56:29 +00002121 EVT PTy = TLI.getPointerTy();
2122 EVT STy = TLI.getShiftAmountTy();
Owen Anderson77547be2009-08-10 18:56:59 +00002123 if (STy.bitsGT(Op2.getValueType()))
Dan Gohman57fc82d2009-04-09 03:51:29 +00002124 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2125 TLI.getShiftAmountTy(), Op2);
2126 // If the operand is larger than the shift count type but the shift
2127 // count type has enough bits to represent any shift value, truncate
2128 // it now. This is a common case and it exposes the truncate to
2129 // optimization early.
Owen Anderson77547be2009-08-10 18:56:59 +00002130 else if (STy.getSizeInBits() >=
Dan Gohman57fc82d2009-04-09 03:51:29 +00002131 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2132 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2133 TLI.getShiftAmountTy(), Op2);
2134 // Otherwise we'll need to temporarily settle for some other
2135 // convenient type; type legalization will make adjustments as
2136 // needed.
Owen Anderson77547be2009-08-10 18:56:59 +00002137 else if (PTy.bitsLT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002138 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002139 TLI.getPointerTy(), Op2);
Owen Anderson77547be2009-08-10 18:56:59 +00002140 else if (PTy.bitsGT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002141 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002142 TLI.getPointerTy(), Op2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002143 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002144
Bill Wendling4533cac2010-01-28 21:51:40 +00002145 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2146 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002147}
2148
Dan Gohman2048b852009-11-23 18:04:58 +00002149void SelectionDAGBuilder::visitICmp(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002150 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2151 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2152 predicate = IC->getPredicate();
2153 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2154 predicate = ICmpInst::Predicate(IC->getPredicate());
2155 SDValue Op1 = getValue(I.getOperand(0));
2156 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002157 ISD::CondCode Opcode = getICmpCondCode(predicate);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002158
Owen Andersone50ed302009-08-10 22:56:29 +00002159 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002160 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002161}
2162
Dan Gohman2048b852009-11-23 18:04:58 +00002163void SelectionDAGBuilder::visitFCmp(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002164 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2165 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2166 predicate = FC->getPredicate();
2167 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2168 predicate = FCmpInst::Predicate(FC->getPredicate());
2169 SDValue Op1 = getValue(I.getOperand(0));
2170 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002171 ISD::CondCode Condition = getFCmpCondCode(predicate);
Owen Andersone50ed302009-08-10 22:56:29 +00002172 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002173 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002174}
2175
Dan Gohman2048b852009-11-23 18:04:58 +00002176void SelectionDAGBuilder::visitSelect(User &I) {
Owen Andersone50ed302009-08-10 22:56:29 +00002177 SmallVector<EVT, 4> ValueVTs;
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002178 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2179 unsigned NumValues = ValueVTs.size();
Bill Wendling49fcff82009-12-21 22:30:11 +00002180 if (NumValues == 0) return;
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002181
Bill Wendling49fcff82009-12-21 22:30:11 +00002182 SmallVector<SDValue, 4> Values(NumValues);
2183 SDValue Cond = getValue(I.getOperand(0));
2184 SDValue TrueVal = getValue(I.getOperand(1));
2185 SDValue FalseVal = getValue(I.getOperand(2));
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002186
Bill Wendling4533cac2010-01-28 21:51:40 +00002187 for (unsigned i = 0; i != NumValues; ++i)
Bill Wendling49fcff82009-12-21 22:30:11 +00002188 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2189 TrueVal.getNode()->getValueType(i), Cond,
2190 SDValue(TrueVal.getNode(),
2191 TrueVal.getResNo() + i),
2192 SDValue(FalseVal.getNode(),
2193 FalseVal.getResNo() + i));
2194
Bill Wendling4533cac2010-01-28 21:51:40 +00002195 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2196 DAG.getVTList(&ValueVTs[0], NumValues),
2197 &Values[0], NumValues));
Bill Wendling49fcff82009-12-21 22:30:11 +00002198}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002199
Dan Gohman2048b852009-11-23 18:04:58 +00002200void SelectionDAGBuilder::visitTrunc(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002201 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2202 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002203 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002204 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002205}
2206
Dan Gohman2048b852009-11-23 18:04:58 +00002207void SelectionDAGBuilder::visitZExt(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002208 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2209 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2210 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002211 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002212 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002213}
2214
Dan Gohman2048b852009-11-23 18:04:58 +00002215void SelectionDAGBuilder::visitSExt(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002216 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2217 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2218 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002219 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002220 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002221}
2222
Dan Gohman2048b852009-11-23 18:04:58 +00002223void SelectionDAGBuilder::visitFPTrunc(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002224 // FPTrunc is never a no-op cast, no need to check
2225 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002226 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002227 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2228 DestVT, N, DAG.getIntPtrConstant(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002229}
2230
Dan Gohman2048b852009-11-23 18:04:58 +00002231void SelectionDAGBuilder::visitFPExt(User &I){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002232 // FPTrunc is never a no-op cast, no need to check
2233 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002234 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002235 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002236}
2237
Dan Gohman2048b852009-11-23 18:04:58 +00002238void SelectionDAGBuilder::visitFPToUI(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002239 // FPToUI is never a no-op cast, no need to check
2240 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002241 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002242 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002243}
2244
Dan Gohman2048b852009-11-23 18:04:58 +00002245void SelectionDAGBuilder::visitFPToSI(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002246 // FPToSI is never a no-op cast, no need to check
2247 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002248 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002249 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002250}
2251
Dan Gohman2048b852009-11-23 18:04:58 +00002252void SelectionDAGBuilder::visitUIToFP(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002253 // UIToFP is never a no-op cast, no need to check
2254 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002255 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002256 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002257}
2258
Dan Gohman2048b852009-11-23 18:04:58 +00002259void SelectionDAGBuilder::visitSIToFP(User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002260 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002261 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002262 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002263 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002264}
2265
Dan Gohman2048b852009-11-23 18:04:58 +00002266void SelectionDAGBuilder::visitPtrToInt(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002267 // What to do depends on the size of the integer and the size of the pointer.
2268 // We can either truncate, zero extend, or no-op, accordingly.
2269 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002270 EVT SrcVT = N.getValueType();
2271 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002272 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002273}
2274
Dan Gohman2048b852009-11-23 18:04:58 +00002275void SelectionDAGBuilder::visitIntToPtr(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002276 // What to do depends on the size of the integer and the size of the pointer.
2277 // We can either truncate, zero extend, or no-op, accordingly.
2278 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002279 EVT SrcVT = N.getValueType();
2280 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002281 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002282}
2283
Dan Gohman2048b852009-11-23 18:04:58 +00002284void SelectionDAGBuilder::visitBitCast(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002285 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002286 EVT DestVT = TLI.getValueType(I.getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002287
Bill Wendling49fcff82009-12-21 22:30:11 +00002288 // BitCast assures us that source and destination are the same size so this is
2289 // either a BIT_CONVERT or a no-op.
Bill Wendling4533cac2010-01-28 21:51:40 +00002290 if (DestVT != N.getValueType())
2291 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
2292 DestVT, N)); // convert types.
2293 else
Bill Wendling49fcff82009-12-21 22:30:11 +00002294 setValue(&I, N); // noop cast.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002295}
2296
Dan Gohman2048b852009-11-23 18:04:58 +00002297void SelectionDAGBuilder::visitInsertElement(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002298 SDValue InVec = getValue(I.getOperand(0));
2299 SDValue InVal = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002300 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00002301 TLI.getPointerTy(),
2302 getValue(I.getOperand(2)));
Bill Wendling4533cac2010-01-28 21:51:40 +00002303 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2304 TLI.getValueType(I.getType()),
2305 InVec, InVal, InIdx));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002306}
2307
Dan Gohman2048b852009-11-23 18:04:58 +00002308void SelectionDAGBuilder::visitExtractElement(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002309 SDValue InVec = getValue(I.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00002310 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00002311 TLI.getPointerTy(),
2312 getValue(I.getOperand(1)));
Bill Wendling4533cac2010-01-28 21:51:40 +00002313 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2314 TLI.getValueType(I.getType()), InVec, InIdx));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002315}
2316
Mon P Wangaeb06d22008-11-10 04:46:22 +00002317// Utility for visitShuffleVector - Returns true if the mask is mask starting
2318// from SIndx and increasing to the element length (undefs are allowed).
Nate Begeman5a5ca152009-04-29 05:20:52 +00002319static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2320 unsigned MaskNumElts = Mask.size();
2321 for (unsigned i = 0; i != MaskNumElts; ++i)
2322 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
Nate Begeman9008ca62009-04-27 18:41:29 +00002323 return false;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002324 return true;
2325}
2326
Dan Gohman2048b852009-11-23 18:04:58 +00002327void SelectionDAGBuilder::visitShuffleVector(User &I) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002328 SmallVector<int, 8> Mask;
Mon P Wang230e4fa2008-11-21 04:25:21 +00002329 SDValue Src1 = getValue(I.getOperand(0));
2330 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002331
Nate Begeman9008ca62009-04-27 18:41:29 +00002332 // Convert the ConstantVector mask operand into an array of ints, with -1
2333 // representing undef values.
2334 SmallVector<Constant*, 8> MaskElts;
Chris Lattnerb29d5962010-02-01 20:48:08 +00002335 cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
Nate Begeman5a5ca152009-04-29 05:20:52 +00002336 unsigned MaskNumElts = MaskElts.size();
2337 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002338 if (isa<UndefValue>(MaskElts[i]))
2339 Mask.push_back(-1);
2340 else
2341 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2342 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002343
Owen Andersone50ed302009-08-10 22:56:29 +00002344 EVT VT = TLI.getValueType(I.getType());
2345 EVT SrcVT = Src1.getValueType();
Nate Begeman5a5ca152009-04-29 05:20:52 +00002346 unsigned SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002347
Mon P Wangc7849c22008-11-16 05:06:27 +00002348 if (SrcNumElts == MaskNumElts) {
Bill Wendling4533cac2010-01-28 21:51:40 +00002349 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2350 &Mask[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002351 return;
2352 }
2353
2354 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002355 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2356 // Mask is longer than the source vectors and is a multiple of the source
2357 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang230e4fa2008-11-21 04:25:21 +00002358 // lengths match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002359 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2360 // The shuffle is concatenating two vectors together.
Bill Wendling4533cac2010-01-28 21:51:40 +00002361 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2362 VT, Src1, Src2));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002363 return;
2364 }
2365
Mon P Wangc7849c22008-11-16 05:06:27 +00002366 // Pad both vectors with undefs to make them the same length as the mask.
2367 unsigned NumConcat = MaskNumElts / SrcNumElts;
Nate Begeman9008ca62009-04-27 18:41:29 +00002368 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2369 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
Dale Johannesene8d72302009-02-06 23:05:02 +00002370 SDValue UndefVal = DAG.getUNDEF(SrcVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002371
Nate Begeman9008ca62009-04-27 18:41:29 +00002372 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2373 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002374 MOps1[0] = Src1;
2375 MOps2[0] = Src2;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002376
2377 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2378 getCurDebugLoc(), VT,
Nate Begeman9008ca62009-04-27 18:41:29 +00002379 &MOps1[0], NumConcat);
2380 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002381 getCurDebugLoc(), VT,
Nate Begeman9008ca62009-04-27 18:41:29 +00002382 &MOps2[0], NumConcat);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002383
Mon P Wangaeb06d22008-11-10 04:46:22 +00002384 // Readjust mask for new input vector length.
Nate Begeman9008ca62009-04-27 18:41:29 +00002385 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002386 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002387 int Idx = Mask[i];
Nate Begeman5a5ca152009-04-29 05:20:52 +00002388 if (Idx < (int)SrcNumElts)
Nate Begeman9008ca62009-04-27 18:41:29 +00002389 MappedOps.push_back(Idx);
2390 else
2391 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002392 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002393
Bill Wendling4533cac2010-01-28 21:51:40 +00002394 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2395 &MappedOps[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002396 return;
2397 }
2398
Mon P Wangc7849c22008-11-16 05:06:27 +00002399 if (SrcNumElts > MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002400 // Analyze the access pattern of the vector to see if we can extract
2401 // two subvectors and do the shuffle. The analysis is done by calculating
2402 // the range of elements the mask access on both vectors.
2403 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2404 int MaxRange[2] = {-1, -1};
2405
Nate Begeman5a5ca152009-04-29 05:20:52 +00002406 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002407 int Idx = Mask[i];
2408 int Input = 0;
2409 if (Idx < 0)
2410 continue;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002411
Nate Begeman5a5ca152009-04-29 05:20:52 +00002412 if (Idx >= (int)SrcNumElts) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002413 Input = 1;
2414 Idx -= SrcNumElts;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002415 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002416 if (Idx > MaxRange[Input])
2417 MaxRange[Input] = Idx;
2418 if (Idx < MinRange[Input])
2419 MinRange[Input] = Idx;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002420 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002421
Mon P Wangc7849c22008-11-16 05:06:27 +00002422 // Check if the access is smaller than the vector size and can we find
2423 // a reasonable extract index.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002424 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not
2425 // Extract.
Mon P Wangc7849c22008-11-16 05:06:27 +00002426 int StartIdx[2]; // StartIdx to extract from
2427 for (int Input=0; Input < 2; ++Input) {
Nate Begeman5a5ca152009-04-29 05:20:52 +00002428 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002429 RangeUse[Input] = 0; // Unused
2430 StartIdx[Input] = 0;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002431 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002432 // Fits within range but we should see if we can find a good
Mon P Wang230e4fa2008-11-21 04:25:21 +00002433 // start index that is a multiple of the mask length.
Nate Begeman5a5ca152009-04-29 05:20:52 +00002434 if (MaxRange[Input] < (int)MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002435 RangeUse[Input] = 1; // Extract from beginning of the vector
2436 StartIdx[Input] = 0;
2437 } else {
2438 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002439 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002440 StartIdx[Input] + MaskNumElts < SrcNumElts)
Mon P Wangc7849c22008-11-16 05:06:27 +00002441 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002442 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002443 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002444 }
2445
Bill Wendling636e2582009-08-21 18:16:06 +00002446 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
Bill Wendling4533cac2010-01-28 21:51:40 +00002447 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
Mon P Wangc7849c22008-11-16 05:06:27 +00002448 return;
2449 }
2450 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2451 // Extract appropriate subvector and generate a vector shuffle
2452 for (int Input=0; Input < 2; ++Input) {
Bill Wendling87710f02009-12-21 23:47:40 +00002453 SDValue &Src = Input == 0 ? Src1 : Src2;
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002454 if (RangeUse[Input] == 0)
Dale Johannesene8d72302009-02-06 23:05:02 +00002455 Src = DAG.getUNDEF(VT);
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002456 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00002457 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002458 Src, DAG.getIntPtrConstant(StartIdx[Input]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002459 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002460
Mon P Wangc7849c22008-11-16 05:06:27 +00002461 // Calculate new mask.
Nate Begeman9008ca62009-04-27 18:41:29 +00002462 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002463 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002464 int Idx = Mask[i];
2465 if (Idx < 0)
2466 MappedOps.push_back(Idx);
Nate Begeman5a5ca152009-04-29 05:20:52 +00002467 else if (Idx < (int)SrcNumElts)
Nate Begeman9008ca62009-04-27 18:41:29 +00002468 MappedOps.push_back(Idx - StartIdx[0]);
2469 else
2470 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
Mon P Wangc7849c22008-11-16 05:06:27 +00002471 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002472
Bill Wendling4533cac2010-01-28 21:51:40 +00002473 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2474 &MappedOps[0]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002475 return;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002476 }
2477 }
2478
Mon P Wangc7849c22008-11-16 05:06:27 +00002479 // We can't use either concat vectors or extract subvectors so fall back to
2480 // replacing the shuffle with extract and build vector.
2481 // to insert and build vector.
Owen Andersone50ed302009-08-10 22:56:29 +00002482 EVT EltVT = VT.getVectorElementType();
2483 EVT PtrVT = TLI.getPointerTy();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002484 SmallVector<SDValue,8> Ops;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002485 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002486 if (Mask[i] < 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002487 Ops.push_back(DAG.getUNDEF(EltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002488 } else {
Nate Begeman9008ca62009-04-27 18:41:29 +00002489 int Idx = Mask[i];
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002490 SDValue Res;
2491
Nate Begeman5a5ca152009-04-29 05:20:52 +00002492 if (Idx < (int)SrcNumElts)
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002493 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2494 EltVT, Src1, DAG.getConstant(Idx, PtrVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002495 else
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002496 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2497 EltVT, Src2,
2498 DAG.getConstant(Idx - SrcNumElts, PtrVT));
2499
2500 Ops.push_back(Res);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002501 }
2502 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002503
Bill Wendling4533cac2010-01-28 21:51:40 +00002504 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2505 VT, &Ops[0], Ops.size()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002506}
2507
Dan Gohman2048b852009-11-23 18:04:58 +00002508void SelectionDAGBuilder::visitInsertValue(InsertValueInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002509 const Value *Op0 = I.getOperand(0);
2510 const Value *Op1 = I.getOperand(1);
2511 const Type *AggTy = I.getType();
2512 const Type *ValTy = Op1->getType();
2513 bool IntoUndef = isa<UndefValue>(Op0);
2514 bool FromUndef = isa<UndefValue>(Op1);
2515
2516 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2517 I.idx_begin(), I.idx_end());
2518
Owen Andersone50ed302009-08-10 22:56:29 +00002519 SmallVector<EVT, 4> AggValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002520 ComputeValueVTs(TLI, AggTy, AggValueVTs);
Owen Andersone50ed302009-08-10 22:56:29 +00002521 SmallVector<EVT, 4> ValValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002522 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2523
2524 unsigned NumAggValues = AggValueVTs.size();
2525 unsigned NumValValues = ValValueVTs.size();
2526 SmallVector<SDValue, 4> Values(NumAggValues);
2527
2528 SDValue Agg = getValue(Op0);
2529 SDValue Val = getValue(Op1);
2530 unsigned i = 0;
2531 // Copy the beginning value(s) from the original aggregate.
2532 for (; i != LinearIndex; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002533 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002534 SDValue(Agg.getNode(), Agg.getResNo() + i);
2535 // Copy values from the inserted value(s).
2536 for (; i != LinearIndex + NumValValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002537 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002538 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2539 // Copy remaining value(s) from the original aggregate.
2540 for (; i != NumAggValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002541 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002542 SDValue(Agg.getNode(), Agg.getResNo() + i);
2543
Bill Wendling4533cac2010-01-28 21:51:40 +00002544 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2545 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2546 &Values[0], NumAggValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002547}
2548
Dan Gohman2048b852009-11-23 18:04:58 +00002549void SelectionDAGBuilder::visitExtractValue(ExtractValueInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002550 const Value *Op0 = I.getOperand(0);
2551 const Type *AggTy = Op0->getType();
2552 const Type *ValTy = I.getType();
2553 bool OutOfUndef = isa<UndefValue>(Op0);
2554
2555 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2556 I.idx_begin(), I.idx_end());
2557
Owen Andersone50ed302009-08-10 22:56:29 +00002558 SmallVector<EVT, 4> ValValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002559 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2560
2561 unsigned NumValValues = ValValueVTs.size();
2562 SmallVector<SDValue, 4> Values(NumValValues);
2563
2564 SDValue Agg = getValue(Op0);
2565 // Copy out the selected value(s).
2566 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2567 Values[i - LinearIndex] =
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002568 OutOfUndef ?
Dale Johannesene8d72302009-02-06 23:05:02 +00002569 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002570 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002571
Bill Wendling4533cac2010-01-28 21:51:40 +00002572 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2573 DAG.getVTList(&ValValueVTs[0], NumValValues),
2574 &Values[0], NumValValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002575}
2576
Dan Gohman2048b852009-11-23 18:04:58 +00002577void SelectionDAGBuilder::visitGetElementPtr(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002578 SDValue N = getValue(I.getOperand(0));
2579 const Type *Ty = I.getOperand(0)->getType();
2580
2581 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2582 OI != E; ++OI) {
2583 Value *Idx = *OI;
2584 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2585 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2586 if (Field) {
2587 // N = N + Offset
2588 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002589 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002590 DAG.getIntPtrConstant(Offset));
2591 }
Bill Wendlinge1a90422009-12-21 23:10:19 +00002592
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002593 Ty = StTy->getElementType(Field);
2594 } else {
2595 Ty = cast<SequentialType>(Ty)->getElementType();
2596
2597 // If this is a constant subscript, handle it quickly.
2598 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2599 if (CI->getZExtValue() == 0) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002600 uint64_t Offs =
Duncan Sands777d2302009-05-09 07:06:46 +00002601 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Evan Cheng65b52df2009-02-09 21:01:06 +00002602 SDValue OffsVal;
Owen Andersone50ed302009-08-10 22:56:29 +00002603 EVT PTy = TLI.getPointerTy();
Owen Anderson77547be2009-08-10 18:56:59 +00002604 unsigned PtrBits = PTy.getSizeInBits();
Bill Wendlinge1a90422009-12-21 23:10:19 +00002605 if (PtrBits < 64)
Evan Cheng65b52df2009-02-09 21:01:06 +00002606 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2607 TLI.getPointerTy(),
Owen Anderson825b72b2009-08-11 20:47:22 +00002608 DAG.getConstant(Offs, MVT::i64));
Bill Wendlinge1a90422009-12-21 23:10:19 +00002609 else
Evan Chengb1032a82009-02-09 20:54:38 +00002610 OffsVal = DAG.getIntPtrConstant(Offs);
Bill Wendlinge1a90422009-12-21 23:10:19 +00002611
Dale Johannesen66978ee2009-01-31 02:22:37 +00002612 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Evan Chengb1032a82009-02-09 20:54:38 +00002613 OffsVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002614 continue;
2615 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002616
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002617 // N = N + Idx * ElementSize;
Dan Gohman7abbd042009-10-23 17:57:43 +00002618 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
2619 TD->getTypeAllocSize(Ty));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002620 SDValue IdxN = getValue(Idx);
2621
2622 // If the index is smaller or larger than intptr_t, truncate or extend
2623 // it.
Duncan Sands3a66a682009-10-13 21:04:12 +00002624 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002625
2626 // If this is a multiply by a power of two, turn it into a shl
2627 // immediately. This is a very common case.
2628 if (ElementSize != 1) {
Dan Gohman7abbd042009-10-23 17:57:43 +00002629 if (ElementSize.isPowerOf2()) {
2630 unsigned Amt = ElementSize.logBase2();
Scott Michelfdc40a02009-02-17 22:15:04 +00002631 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002632 N.getValueType(), IdxN,
Duncan Sands92abc622009-01-31 15:50:11 +00002633 DAG.getConstant(Amt, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002634 } else {
Dan Gohman7abbd042009-10-23 17:57:43 +00002635 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
Scott Michelfdc40a02009-02-17 22:15:04 +00002636 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002637 N.getValueType(), IdxN, Scale);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002638 }
2639 }
2640
Scott Michelfdc40a02009-02-17 22:15:04 +00002641 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002642 N.getValueType(), N, IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002643 }
2644 }
Bill Wendlinge1a90422009-12-21 23:10:19 +00002645
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002646 setValue(&I, N);
2647}
2648
Dan Gohman2048b852009-11-23 18:04:58 +00002649void SelectionDAGBuilder::visitAlloca(AllocaInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002650 // If this is a fixed sized alloca in the entry block of the function,
2651 // allocate it statically on the stack.
2652 if (FuncInfo.StaticAllocaMap.count(&I))
2653 return; // getValue will auto-populate this.
2654
2655 const Type *Ty = I.getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002656 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002657 unsigned Align =
2658 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2659 I.getAlignment());
2660
2661 SDValue AllocSize = getValue(I.getArraySize());
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002662
Chris Lattner0b18e592009-03-17 19:36:00 +00002663 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2664 AllocSize,
2665 DAG.getConstant(TySize, AllocSize.getValueType()));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002666
Owen Andersone50ed302009-08-10 22:56:29 +00002667 EVT IntPtr = TLI.getPointerTy();
Duncan Sands3a66a682009-10-13 21:04:12 +00002668 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002669
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002670 // Handle alignment. If the requested alignment is less than or equal to
2671 // the stack alignment, ignore it. If the size is greater than or equal to
2672 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2673 unsigned StackAlign =
2674 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2675 if (Align <= StackAlign)
2676 Align = 0;
2677
2678 // Round the size of the allocation up to the stack alignment size
2679 // by add SA-1 to the size.
Scott Michelfdc40a02009-02-17 22:15:04 +00002680 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002681 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002682 DAG.getIntPtrConstant(StackAlign-1));
Bill Wendling856ff412009-12-22 00:12:37 +00002683
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002684 // Mask out the low bits for alignment purposes.
Scott Michelfdc40a02009-02-17 22:15:04 +00002685 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002686 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002687 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2688
2689 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Owen Anderson825b72b2009-08-11 20:47:22 +00002690 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
Scott Michelfdc40a02009-02-17 22:15:04 +00002691 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002692 VTs, Ops, 3);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002693 setValue(&I, DSA);
2694 DAG.setRoot(DSA.getValue(1));
Bill Wendling856ff412009-12-22 00:12:37 +00002695
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002696 // Inform the Frame Information that we have just allocated a variable-sized
2697 // object.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00002698 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002699}
2700
Dan Gohman2048b852009-11-23 18:04:58 +00002701void SelectionDAGBuilder::visitLoad(LoadInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002702 const Value *SV = I.getOperand(0);
2703 SDValue Ptr = getValue(SV);
2704
2705 const Type *Ty = I.getType();
David Greene1e559442010-02-15 17:00:31 +00002706
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002707 bool isVolatile = I.isVolatile();
David Greene1e559442010-02-15 17:00:31 +00002708 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002709 unsigned Alignment = I.getAlignment();
2710
Owen Andersone50ed302009-08-10 22:56:29 +00002711 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002712 SmallVector<uint64_t, 4> Offsets;
2713 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2714 unsigned NumValues = ValueVTs.size();
2715 if (NumValues == 0)
2716 return;
2717
2718 SDValue Root;
2719 bool ConstantMemory = false;
2720 if (I.isVolatile())
2721 // Serialize volatile loads with other side effects.
2722 Root = getRoot();
2723 else if (AA->pointsToConstantMemory(SV)) {
2724 // Do not serialize (non-volatile) loads of constant memory with anything.
2725 Root = DAG.getEntryNode();
2726 ConstantMemory = true;
2727 } else {
2728 // Do not serialize non-volatile loads against each other.
2729 Root = DAG.getRoot();
2730 }
2731
2732 SmallVector<SDValue, 4> Values(NumValues);
2733 SmallVector<SDValue, 4> Chains(NumValues);
Owen Andersone50ed302009-08-10 22:56:29 +00002734 EVT PtrVT = Ptr.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002735 for (unsigned i = 0; i != NumValues; ++i) {
Bill Wendling856ff412009-12-22 00:12:37 +00002736 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2737 PtrVT, Ptr,
2738 DAG.getConstant(Offsets[i], PtrVT));
Dale Johannesen66978ee2009-01-31 02:22:37 +00002739 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
David Greene1e559442010-02-15 17:00:31 +00002740 A, SV, Offsets[i], isVolatile,
2741 isNonTemporal, Alignment);
Bill Wendling856ff412009-12-22 00:12:37 +00002742
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002743 Values[i] = L;
2744 Chains[i] = L.getValue(1);
2745 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002746
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002747 if (!ConstantMemory) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002748 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Bill Wendling856ff412009-12-22 00:12:37 +00002749 MVT::Other, &Chains[0], NumValues);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002750 if (isVolatile)
2751 DAG.setRoot(Chain);
2752 else
2753 PendingLoads.push_back(Chain);
2754 }
2755
Bill Wendling4533cac2010-01-28 21:51:40 +00002756 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2757 DAG.getVTList(&ValueVTs[0], NumValues),
2758 &Values[0], NumValues));
Bill Wendling856ff412009-12-22 00:12:37 +00002759}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002760
Dan Gohman2048b852009-11-23 18:04:58 +00002761void SelectionDAGBuilder::visitStore(StoreInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002762 Value *SrcV = I.getOperand(0);
2763 Value *PtrV = I.getOperand(1);
2764
Owen Andersone50ed302009-08-10 22:56:29 +00002765 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002766 SmallVector<uint64_t, 4> Offsets;
2767 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2768 unsigned NumValues = ValueVTs.size();
2769 if (NumValues == 0)
2770 return;
2771
2772 // Get the lowered operands. Note that we do this after
2773 // checking if NumResults is zero, because with zero results
2774 // the operands won't have values in the map.
2775 SDValue Src = getValue(SrcV);
2776 SDValue Ptr = getValue(PtrV);
2777
2778 SDValue Root = getRoot();
2779 SmallVector<SDValue, 4> Chains(NumValues);
Owen Andersone50ed302009-08-10 22:56:29 +00002780 EVT PtrVT = Ptr.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002781 bool isVolatile = I.isVolatile();
David Greene1e559442010-02-15 17:00:31 +00002782 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002783 unsigned Alignment = I.getAlignment();
Bill Wendling856ff412009-12-22 00:12:37 +00002784
2785 for (unsigned i = 0; i != NumValues; ++i) {
2786 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
2787 DAG.getConstant(Offsets[i], PtrVT));
Dale Johannesen66978ee2009-01-31 02:22:37 +00002788 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002789 SDValue(Src.getNode(), Src.getResNo() + i),
David Greene1e559442010-02-15 17:00:31 +00002790 Add, PtrV, Offsets[i], isVolatile,
2791 isNonTemporal, Alignment);
Bill Wendling856ff412009-12-22 00:12:37 +00002792 }
2793
Bill Wendling4533cac2010-01-28 21:51:40 +00002794 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2795 MVT::Other, &Chains[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002796}
2797
2798/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2799/// node.
Dan Gohman2048b852009-11-23 18:04:58 +00002800void SelectionDAGBuilder::visitTargetIntrinsic(CallInst &I,
2801 unsigned Intrinsic) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002802 bool HasChain = !I.doesNotAccessMemory();
2803 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2804
2805 // Build the operand list.
2806 SmallVector<SDValue, 8> Ops;
2807 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2808 if (OnlyLoad) {
2809 // We don't need to serialize loads against other loads.
2810 Ops.push_back(DAG.getRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002811 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002812 Ops.push_back(getRoot());
2813 }
2814 }
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002815
2816 // Info is set by getTgtMemInstrinsic
2817 TargetLowering::IntrinsicInfo Info;
2818 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2819
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002820 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002821 if (!IsTgtIntrinsic)
2822 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002823
2824 // Add all operands of the call to the operand list.
2825 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2826 SDValue Op = getValue(I.getOperand(i));
2827 assert(TLI.isTypeLegal(Op.getValueType()) &&
2828 "Intrinsic uses a non-legal type?");
2829 Ops.push_back(Op);
2830 }
2831
Owen Andersone50ed302009-08-10 22:56:29 +00002832 SmallVector<EVT, 4> ValueVTs;
Bob Wilson8d919552009-07-31 22:41:21 +00002833 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2834#ifndef NDEBUG
2835 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
2836 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
2837 "Intrinsic uses a non-legal type?");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002838 }
Bob Wilson8d919552009-07-31 22:41:21 +00002839#endif // NDEBUG
Bill Wendling856ff412009-12-22 00:12:37 +00002840
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002841 if (HasChain)
Owen Anderson825b72b2009-08-11 20:47:22 +00002842 ValueVTs.push_back(MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002843
Bob Wilson8d919552009-07-31 22:41:21 +00002844 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002845
2846 // Create the node.
2847 SDValue Result;
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002848 if (IsTgtIntrinsic) {
2849 // This is target intrinsic that touches memory
Dale Johannesen66978ee2009-01-31 02:22:37 +00002850 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002851 VTs, &Ops[0], Ops.size(),
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002852 Info.memVT, Info.ptrVal, Info.offset,
2853 Info.align, Info.vol,
2854 Info.readMem, Info.writeMem);
Bill Wendling856ff412009-12-22 00:12:37 +00002855 } else if (!HasChain) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002856 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002857 VTs, &Ops[0], Ops.size());
Benjamin Kramerf0127052010-01-05 13:12:22 +00002858 } else if (!I.getType()->isVoidTy()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002859 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002860 VTs, &Ops[0], Ops.size());
Bill Wendling856ff412009-12-22 00:12:37 +00002861 } else {
Scott Michelfdc40a02009-02-17 22:15:04 +00002862 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002863 VTs, &Ops[0], Ops.size());
Bill Wendling856ff412009-12-22 00:12:37 +00002864 }
2865
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002866 if (HasChain) {
2867 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2868 if (OnlyLoad)
2869 PendingLoads.push_back(Chain);
2870 else
2871 DAG.setRoot(Chain);
2872 }
Bill Wendling856ff412009-12-22 00:12:37 +00002873
Benjamin Kramerf0127052010-01-05 13:12:22 +00002874 if (!I.getType()->isVoidTy()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002875 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Owen Andersone50ed302009-08-10 22:56:29 +00002876 EVT VT = TLI.getValueType(PTy);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002877 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002878 }
Bill Wendling856ff412009-12-22 00:12:37 +00002879
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002880 setValue(&I, Result);
2881 }
2882}
2883
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002884/// GetSignificand - Get the significand and build it into a floating-point
2885/// number with exponent of 1:
2886///
2887/// Op = (Op & 0x007fffff) | 0x3f800000;
2888///
2889/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002890static SDValue
Bill Wendling856ff412009-12-22 00:12:37 +00002891GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl, unsigned Order) {
Owen Anderson825b72b2009-08-11 20:47:22 +00002892 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
2893 DAG.getConstant(0x007fffff, MVT::i32));
2894 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
2895 DAG.getConstant(0x3f800000, MVT::i32));
Bill Wendling4533cac2010-01-28 21:51:40 +00002896 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00002897}
2898
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002899/// GetExponent - Get the exponent:
2900///
Bill Wendlinge9a72862009-01-20 21:17:57 +00002901/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002902///
2903/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002904static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00002905GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
Bill Wendling856ff412009-12-22 00:12:37 +00002906 DebugLoc dl, unsigned Order) {
Owen Anderson825b72b2009-08-11 20:47:22 +00002907 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
2908 DAG.getConstant(0x7f800000, MVT::i32));
2909 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
Duncan Sands92abc622009-01-31 15:50:11 +00002910 DAG.getConstant(23, TLI.getPointerTy()));
Owen Anderson825b72b2009-08-11 20:47:22 +00002911 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
2912 DAG.getConstant(127, MVT::i32));
Bill Wendling4533cac2010-01-28 21:51:40 +00002913 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00002914}
2915
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002916/// getF32Constant - Get 32-bit floating point constant.
2917static SDValue
2918getF32Constant(SelectionDAG &DAG, unsigned Flt) {
Owen Anderson825b72b2009-08-11 20:47:22 +00002919 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002920}
2921
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002922/// Inlined utility function to implement binary input atomic intrinsics for
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002923/// visitIntrinsicCall: I is a call instruction
2924/// Op is the associated NodeType for I
2925const char *
Dan Gohman2048b852009-11-23 18:04:58 +00002926SelectionDAGBuilder::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002927 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00002928 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00002929 DAG.getAtomic(Op, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002930 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00002931 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002932 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00002933 getValue(I.getOperand(2)),
2934 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002935 setValue(&I, L);
2936 DAG.setRoot(L.getValue(1));
2937 return 0;
2938}
2939
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002940// implVisitAluOverflow - Lower arithmetic overflow instrinsics.
Bill Wendling74c37652008-12-09 22:08:41 +00002941const char *
Dan Gohman2048b852009-11-23 18:04:58 +00002942SelectionDAGBuilder::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002943 SDValue Op1 = getValue(I.getOperand(1));
2944 SDValue Op2 = getValue(I.getOperand(2));
Bill Wendling74c37652008-12-09 22:08:41 +00002945
Owen Anderson825b72b2009-08-11 20:47:22 +00002946 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
Bill Wendling4533cac2010-01-28 21:51:40 +00002947 setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2));
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002948 return 0;
2949}
Bill Wendling74c37652008-12-09 22:08:41 +00002950
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002951/// visitExp - Lower an exp intrinsic. Handles the special sequences for
2952/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00002953void
Dan Gohman2048b852009-11-23 18:04:58 +00002954SelectionDAGBuilder::visitExp(CallInst &I) {
Dale Johannesen59e577f2008-09-05 18:38:42 +00002955 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00002956 DebugLoc dl = getCurDebugLoc();
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002957
Owen Anderson825b72b2009-08-11 20:47:22 +00002958 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002959 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2960 SDValue Op = getValue(I.getOperand(1));
2961
2962 // Put the exponent in the right bit position for later addition to the
2963 // final result:
2964 //
2965 // #define LOG2OFe 1.4426950f
2966 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
Owen Anderson825b72b2009-08-11 20:47:22 +00002967 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002968 getF32Constant(DAG, 0x3fb8aa3b));
Owen Anderson825b72b2009-08-11 20:47:22 +00002969 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002970
2971 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00002972 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
2973 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002974
2975 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00002976 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00002977 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendling856ff412009-12-22 00:12:37 +00002978
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002979 if (LimitFloatPrecision <= 6) {
2980 // For floating-point precision of 6:
2981 //
2982 // TwoToFractionalPartOfX =
2983 // 0.997535578f +
2984 // (0.735607626f + 0.252464424f * x) * x;
2985 //
2986 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00002987 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002988 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00002989 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002990 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00002991 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
2992 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002993 getF32Constant(DAG, 0x3f7f5e7e));
Owen Anderson825b72b2009-08-11 20:47:22 +00002994 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002995
2996 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00002997 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002998 TwoToFracPartOfX, IntegerPartOfX);
2999
Owen Anderson825b72b2009-08-11 20:47:22 +00003000 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003001 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3002 // For floating-point precision of 12:
3003 //
3004 // TwoToFractionalPartOfX =
3005 // 0.999892986f +
3006 // (0.696457318f +
3007 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3008 //
3009 // 0.000107046256 error, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003010 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003011 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003012 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003013 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003014 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3015 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003016 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00003017 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3018 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003019 getF32Constant(DAG, 0x3f7ff8fd));
Owen Anderson825b72b2009-08-11 20:47:22 +00003020 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003021
3022 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00003023 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003024 TwoToFracPartOfX, IntegerPartOfX);
3025
Owen Anderson825b72b2009-08-11 20:47:22 +00003026 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003027 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3028 // For floating-point precision of 18:
3029 //
3030 // TwoToFractionalPartOfX =
3031 // 0.999999982f +
3032 // (0.693148872f +
3033 // (0.240227044f +
3034 // (0.554906021e-1f +
3035 // (0.961591928e-2f +
3036 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3037 //
3038 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003039 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003040 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003041 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003042 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003043 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3044 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003045 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003046 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3047 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003048 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003049 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3050 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003051 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003052 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3053 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003054 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003055 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3056 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003057 getF32Constant(DAG, 0x3f800000));
Scott Michelfdc40a02009-02-17 22:15:04 +00003058 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003059 MVT::i32, t13);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003060
3061 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00003062 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003063 TwoToFracPartOfX, IntegerPartOfX);
3064
Owen Anderson825b72b2009-08-11 20:47:22 +00003065 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003066 }
3067 } else {
3068 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003069 result = DAG.getNode(ISD::FEXP, dl,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003070 getValue(I.getOperand(1)).getValueType(),
3071 getValue(I.getOperand(1)));
3072 }
3073
Dale Johannesen59e577f2008-09-05 18:38:42 +00003074 setValue(&I, result);
3075}
3076
Bill Wendling39150252008-09-09 20:39:27 +00003077/// visitLog - Lower a log intrinsic. Handles the special sequences for
3078/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003079void
Dan Gohman2048b852009-11-23 18:04:58 +00003080SelectionDAGBuilder::visitLog(CallInst &I) {
Dale Johannesen59e577f2008-09-05 18:38:42 +00003081 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003082 DebugLoc dl = getCurDebugLoc();
Bill Wendling39150252008-09-09 20:39:27 +00003083
Owen Anderson825b72b2009-08-11 20:47:22 +00003084 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling39150252008-09-09 20:39:27 +00003085 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3086 SDValue Op = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003087 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling39150252008-09-09 20:39:27 +00003088
3089 // Scale the exponent by log(2) [0.69314718f].
Bill Wendling856ff412009-12-22 00:12:37 +00003090 SDValue Exp = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
Owen Anderson825b72b2009-08-11 20:47:22 +00003091 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003092 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003093
3094 // Get the significand and build it into a floating-point number with
3095 // exponent of 1.
Bill Wendling856ff412009-12-22 00:12:37 +00003096 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
Bill Wendling39150252008-09-09 20:39:27 +00003097
3098 if (LimitFloatPrecision <= 6) {
3099 // For floating-point precision of 6:
3100 //
3101 // LogofMantissa =
3102 // -1.1609546f +
3103 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003104 //
Bill Wendling39150252008-09-09 20:39:27 +00003105 // error 0.0034276066, which is better than 8 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003106 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003107 getF32Constant(DAG, 0xbe74c456));
Owen Anderson825b72b2009-08-11 20:47:22 +00003108 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003109 getF32Constant(DAG, 0x3fb3a2b1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003110 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3111 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003112 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00003113
Scott Michelfdc40a02009-02-17 22:15:04 +00003114 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003115 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003116 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3117 // For floating-point precision of 12:
3118 //
3119 // LogOfMantissa =
3120 // -1.7417939f +
3121 // (2.8212026f +
3122 // (-1.4699568f +
3123 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3124 //
3125 // error 0.000061011436, which is 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003126 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003127 getF32Constant(DAG, 0xbd67b6d6));
Owen Anderson825b72b2009-08-11 20:47:22 +00003128 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003129 getF32Constant(DAG, 0x3ee4f4b8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003130 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3131 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003132 getF32Constant(DAG, 0x3fbc278b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003133 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3134 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003135 getF32Constant(DAG, 0x40348e95));
Owen Anderson825b72b2009-08-11 20:47:22 +00003136 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3137 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003138 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00003139
Scott Michelfdc40a02009-02-17 22:15:04 +00003140 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003141 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003142 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3143 // For floating-point precision of 18:
3144 //
3145 // LogOfMantissa =
3146 // -2.1072184f +
3147 // (4.2372794f +
3148 // (-3.7029485f +
3149 // (2.2781945f +
3150 // (-0.87823314f +
3151 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3152 //
3153 // error 0.0000023660568, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003154 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003155 getF32Constant(DAG, 0xbc91e5ac));
Owen Anderson825b72b2009-08-11 20:47:22 +00003156 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003157 getF32Constant(DAG, 0x3e4350aa));
Owen Anderson825b72b2009-08-11 20:47:22 +00003158 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3159 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003160 getF32Constant(DAG, 0x3f60d3e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003161 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3162 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003163 getF32Constant(DAG, 0x4011cdf0));
Owen Anderson825b72b2009-08-11 20:47:22 +00003164 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3165 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003166 getF32Constant(DAG, 0x406cfd1c));
Owen Anderson825b72b2009-08-11 20:47:22 +00003167 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3168 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003169 getF32Constant(DAG, 0x408797cb));
Owen Anderson825b72b2009-08-11 20:47:22 +00003170 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3171 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003172 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003173
Scott Michelfdc40a02009-02-17 22:15:04 +00003174 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003175 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003176 }
3177 } else {
3178 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003179 result = DAG.getNode(ISD::FLOG, dl,
Bill Wendling39150252008-09-09 20:39:27 +00003180 getValue(I.getOperand(1)).getValueType(),
3181 getValue(I.getOperand(1)));
3182 }
3183
Dale Johannesen59e577f2008-09-05 18:38:42 +00003184 setValue(&I, result);
3185}
3186
Bill Wendling3eb59402008-09-09 00:28:24 +00003187/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3188/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003189void
Dan Gohman2048b852009-11-23 18:04:58 +00003190SelectionDAGBuilder::visitLog2(CallInst &I) {
Dale Johannesen59e577f2008-09-05 18:38:42 +00003191 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003192 DebugLoc dl = getCurDebugLoc();
Bill Wendling3eb59402008-09-09 00:28:24 +00003193
Owen Anderson825b72b2009-08-11 20:47:22 +00003194 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003195 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3196 SDValue Op = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003197 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003198
Bill Wendling39150252008-09-09 20:39:27 +00003199 // Get the exponent.
Bill Wendling856ff412009-12-22 00:12:37 +00003200 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
3201
Bill Wendling3eb59402008-09-09 00:28:24 +00003202 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003203 // exponent of 1.
Bill Wendling856ff412009-12-22 00:12:37 +00003204 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003205
Bill Wendling3eb59402008-09-09 00:28:24 +00003206 // Different possible minimax approximations of significand in
3207 // floating-point for various degrees of accuracy over [1,2].
3208 if (LimitFloatPrecision <= 6) {
3209 // For floating-point precision of 6:
3210 //
3211 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3212 //
3213 // error 0.0049451742, which is more than 7 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003214 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003215 getF32Constant(DAG, 0xbeb08fe0));
Owen Anderson825b72b2009-08-11 20:47:22 +00003216 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003217 getF32Constant(DAG, 0x40019463));
Owen Anderson825b72b2009-08-11 20:47:22 +00003218 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3219 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003220 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003221
Scott Michelfdc40a02009-02-17 22:15:04 +00003222 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003223 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003224 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3225 // For floating-point precision of 12:
3226 //
3227 // Log2ofMantissa =
3228 // -2.51285454f +
3229 // (4.07009056f +
3230 // (-2.12067489f +
3231 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003232 //
Bill Wendling3eb59402008-09-09 00:28:24 +00003233 // error 0.0000876136000, which is better than 13 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003234 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003235 getF32Constant(DAG, 0xbda7262e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003236 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003237 getF32Constant(DAG, 0x3f25280b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003238 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3239 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003240 getF32Constant(DAG, 0x4007b923));
Owen Anderson825b72b2009-08-11 20:47:22 +00003241 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3242 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003243 getF32Constant(DAG, 0x40823e2f));
Owen Anderson825b72b2009-08-11 20:47:22 +00003244 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3245 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003246 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003247
Scott Michelfdc40a02009-02-17 22:15:04 +00003248 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003249 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003250 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3251 // For floating-point precision of 18:
3252 //
3253 // Log2ofMantissa =
3254 // -3.0400495f +
3255 // (6.1129976f +
3256 // (-5.3420409f +
3257 // (3.2865683f +
3258 // (-1.2669343f +
3259 // (0.27515199f -
3260 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3261 //
3262 // error 0.0000018516, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003263 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003264 getF32Constant(DAG, 0xbcd2769e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003265 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003266 getF32Constant(DAG, 0x3e8ce0b9));
Owen Anderson825b72b2009-08-11 20:47:22 +00003267 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3268 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003269 getF32Constant(DAG, 0x3fa22ae7));
Owen Anderson825b72b2009-08-11 20:47:22 +00003270 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3271 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003272 getF32Constant(DAG, 0x40525723));
Owen Anderson825b72b2009-08-11 20:47:22 +00003273 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3274 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003275 getF32Constant(DAG, 0x40aaf200));
Owen Anderson825b72b2009-08-11 20:47:22 +00003276 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3277 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003278 getF32Constant(DAG, 0x40c39dad));
Owen Anderson825b72b2009-08-11 20:47:22 +00003279 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3280 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003281 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003282
Scott Michelfdc40a02009-02-17 22:15:04 +00003283 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003284 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003285 }
Dale Johannesen853244f2008-09-05 23:49:37 +00003286 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003287 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003288 result = DAG.getNode(ISD::FLOG2, dl,
Dale Johannesen853244f2008-09-05 23:49:37 +00003289 getValue(I.getOperand(1)).getValueType(),
3290 getValue(I.getOperand(1)));
3291 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003292
Dale Johannesen59e577f2008-09-05 18:38:42 +00003293 setValue(&I, result);
3294}
3295
Bill Wendling3eb59402008-09-09 00:28:24 +00003296/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3297/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003298void
Dan Gohman2048b852009-11-23 18:04:58 +00003299SelectionDAGBuilder::visitLog10(CallInst &I) {
Dale Johannesen59e577f2008-09-05 18:38:42 +00003300 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003301 DebugLoc dl = getCurDebugLoc();
Bill Wendling181b6272008-10-19 20:34:04 +00003302
Owen Anderson825b72b2009-08-11 20:47:22 +00003303 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003304 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3305 SDValue Op = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003306 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003307
Bill Wendling39150252008-09-09 20:39:27 +00003308 // Scale the exponent by log10(2) [0.30102999f].
Bill Wendling856ff412009-12-22 00:12:37 +00003309 SDValue Exp = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
Owen Anderson825b72b2009-08-11 20:47:22 +00003310 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003311 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003312
3313 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003314 // exponent of 1.
Bill Wendling856ff412009-12-22 00:12:37 +00003315 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
Bill Wendling3eb59402008-09-09 00:28:24 +00003316
3317 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003318 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003319 //
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003320 // Log10ofMantissa =
3321 // -0.50419619f +
3322 // (0.60948995f - 0.10380950f * x) * x;
3323 //
3324 // error 0.0014886165, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003325 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003326 getF32Constant(DAG, 0xbdd49a13));
Owen Anderson825b72b2009-08-11 20:47:22 +00003327 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003328 getF32Constant(DAG, 0x3f1c0789));
Owen Anderson825b72b2009-08-11 20:47:22 +00003329 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3330 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003331 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003332
Scott Michelfdc40a02009-02-17 22:15:04 +00003333 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003334 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003335 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3336 // For floating-point precision of 12:
3337 //
3338 // Log10ofMantissa =
3339 // -0.64831180f +
3340 // (0.91751397f +
3341 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3342 //
3343 // error 0.00019228036, which is better than 12 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003344 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003345 getF32Constant(DAG, 0x3d431f31));
Owen Anderson825b72b2009-08-11 20:47:22 +00003346 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003347 getF32Constant(DAG, 0x3ea21fb2));
Owen Anderson825b72b2009-08-11 20:47:22 +00003348 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3349 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003350 getF32Constant(DAG, 0x3f6ae232));
Owen Anderson825b72b2009-08-11 20:47:22 +00003351 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3352 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003353 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00003354
Scott Michelfdc40a02009-02-17 22:15:04 +00003355 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003356 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003357 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003358 // For floating-point precision of 18:
3359 //
3360 // Log10ofMantissa =
3361 // -0.84299375f +
3362 // (1.5327582f +
3363 // (-1.0688956f +
3364 // (0.49102474f +
3365 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3366 //
3367 // error 0.0000037995730, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003368 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003369 getF32Constant(DAG, 0x3c5d51ce));
Owen Anderson825b72b2009-08-11 20:47:22 +00003370 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003371 getF32Constant(DAG, 0x3e00685a));
Owen Anderson825b72b2009-08-11 20:47:22 +00003372 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3373 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003374 getF32Constant(DAG, 0x3efb6798));
Owen Anderson825b72b2009-08-11 20:47:22 +00003375 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3376 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003377 getF32Constant(DAG, 0x3f88d192));
Owen Anderson825b72b2009-08-11 20:47:22 +00003378 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3379 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003380 getF32Constant(DAG, 0x3fc4316c));
Owen Anderson825b72b2009-08-11 20:47:22 +00003381 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3382 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003383 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003384
Scott Michelfdc40a02009-02-17 22:15:04 +00003385 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003386 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003387 }
Dale Johannesen852680a2008-09-05 21:27:19 +00003388 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003389 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003390 result = DAG.getNode(ISD::FLOG10, dl,
Dale Johannesen852680a2008-09-05 21:27:19 +00003391 getValue(I.getOperand(1)).getValueType(),
3392 getValue(I.getOperand(1)));
3393 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003394
Dale Johannesen59e577f2008-09-05 18:38:42 +00003395 setValue(&I, result);
3396}
3397
Bill Wendlinge10c8142008-09-09 22:39:21 +00003398/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3399/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003400void
Dan Gohman2048b852009-11-23 18:04:58 +00003401SelectionDAGBuilder::visitExp2(CallInst &I) {
Dale Johannesen601d3c02008-09-05 01:48:15 +00003402 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003403 DebugLoc dl = getCurDebugLoc();
Bill Wendlinge10c8142008-09-09 22:39:21 +00003404
Owen Anderson825b72b2009-08-11 20:47:22 +00003405 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00003406 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3407 SDValue Op = getValue(I.getOperand(1));
3408
Owen Anderson825b72b2009-08-11 20:47:22 +00003409 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003410
3411 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00003412 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3413 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003414
3415 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00003416 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003417 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003418
3419 if (LimitFloatPrecision <= 6) {
3420 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003421 //
Bill Wendlinge10c8142008-09-09 22:39:21 +00003422 // TwoToFractionalPartOfX =
3423 // 0.997535578f +
3424 // (0.735607626f + 0.252464424f * x) * x;
3425 //
3426 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003427 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003428 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00003429 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003430 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003431 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3432 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003433 getF32Constant(DAG, 0x3f7f5e7e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003434 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003435 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003436 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003437
Scott Michelfdc40a02009-02-17 22:15:04 +00003438 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003439 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003440 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3441 // For floating-point precision of 12:
3442 //
3443 // TwoToFractionalPartOfX =
3444 // 0.999892986f +
3445 // (0.696457318f +
3446 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3447 //
3448 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003449 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003450 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003451 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003452 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003453 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3454 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003455 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00003456 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3457 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003458 getF32Constant(DAG, 0x3f7ff8fd));
Owen Anderson825b72b2009-08-11 20:47:22 +00003459 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003460 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003461 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003462
Scott Michelfdc40a02009-02-17 22:15:04 +00003463 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003464 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003465 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3466 // For floating-point precision of 18:
3467 //
3468 // TwoToFractionalPartOfX =
3469 // 0.999999982f +
3470 // (0.693148872f +
3471 // (0.240227044f +
3472 // (0.554906021e-1f +
3473 // (0.961591928e-2f +
3474 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3475 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003476 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003477 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003478 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003479 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003480 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3481 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003482 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003483 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3484 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003485 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003486 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3487 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003488 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003489 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3490 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003491 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003492 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3493 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003494 getF32Constant(DAG, 0x3f800000));
Owen Anderson825b72b2009-08-11 20:47:22 +00003495 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003496 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003497 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003498
Scott Michelfdc40a02009-02-17 22:15:04 +00003499 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003500 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003501 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00003502 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003503 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003504 result = DAG.getNode(ISD::FEXP2, dl,
Dale Johannesen601d3c02008-09-05 01:48:15 +00003505 getValue(I.getOperand(1)).getValueType(),
3506 getValue(I.getOperand(1)));
3507 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00003508
Dale Johannesen601d3c02008-09-05 01:48:15 +00003509 setValue(&I, result);
3510}
3511
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003512/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3513/// limited-precision mode with x == 10.0f.
3514void
Dan Gohman2048b852009-11-23 18:04:58 +00003515SelectionDAGBuilder::visitPow(CallInst &I) {
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003516 SDValue result;
3517 Value *Val = I.getOperand(1);
Dale Johannesen66978ee2009-01-31 02:22:37 +00003518 DebugLoc dl = getCurDebugLoc();
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003519 bool IsExp10 = false;
3520
Owen Anderson825b72b2009-08-11 20:47:22 +00003521 if (getValue(Val).getValueType() == MVT::f32 &&
3522 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003523 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3524 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3525 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3526 APFloat Ten(10.0f);
3527 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3528 }
3529 }
3530 }
3531
3532 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3533 SDValue Op = getValue(I.getOperand(2));
3534
3535 // Put the exponent in the right bit position for later addition to the
3536 // final result:
3537 //
3538 // #define LOG2OF10 3.3219281f
3539 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
Owen Anderson825b72b2009-08-11 20:47:22 +00003540 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003541 getF32Constant(DAG, 0x40549a78));
Owen Anderson825b72b2009-08-11 20:47:22 +00003542 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003543
3544 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00003545 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3546 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003547
3548 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00003549 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003550 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003551
3552 if (LimitFloatPrecision <= 6) {
3553 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003554 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003555 // twoToFractionalPartOfX =
3556 // 0.997535578f +
3557 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003558 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003559 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003560 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003561 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00003562 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003563 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003564 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3565 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003566 getF32Constant(DAG, 0x3f7f5e7e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003567 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003568 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003569 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003570
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003571 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003572 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003573 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3574 // For floating-point precision of 12:
3575 //
3576 // TwoToFractionalPartOfX =
3577 // 0.999892986f +
3578 // (0.696457318f +
3579 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3580 //
3581 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003582 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003583 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003584 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003585 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003586 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3587 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003588 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00003589 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3590 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003591 getF32Constant(DAG, 0x3f7ff8fd));
Owen Anderson825b72b2009-08-11 20:47:22 +00003592 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003593 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003594 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003595
Scott Michelfdc40a02009-02-17 22:15:04 +00003596 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003597 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003598 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3599 // For floating-point precision of 18:
3600 //
3601 // TwoToFractionalPartOfX =
3602 // 0.999999982f +
3603 // (0.693148872f +
3604 // (0.240227044f +
3605 // (0.554906021e-1f +
3606 // (0.961591928e-2f +
3607 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3608 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003609 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003610 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003611 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003612 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003613 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3614 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003615 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003616 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3617 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003618 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003619 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3620 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003621 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003622 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3623 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003624 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003625 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3626 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003627 getF32Constant(DAG, 0x3f800000));
Owen Anderson825b72b2009-08-11 20:47:22 +00003628 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003629 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003630 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003631
Scott Michelfdc40a02009-02-17 22:15:04 +00003632 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003633 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003634 }
3635 } else {
3636 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003637 result = DAG.getNode(ISD::FPOW, dl,
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003638 getValue(I.getOperand(1)).getValueType(),
3639 getValue(I.getOperand(1)),
3640 getValue(I.getOperand(2)));
3641 }
3642
3643 setValue(&I, result);
3644}
3645
Chris Lattnerf031e8a2010-01-01 03:32:16 +00003646
3647/// ExpandPowI - Expand a llvm.powi intrinsic.
3648static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS,
3649 SelectionDAG &DAG) {
3650 // If RHS is a constant, we can expand this out to a multiplication tree,
3651 // otherwise we end up lowering to a call to __powidf2 (for example). When
3652 // optimizing for size, we only want to do this if the expansion would produce
3653 // a small number of multiplies, otherwise we do the full expansion.
3654 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3655 // Get the exponent as a positive value.
3656 unsigned Val = RHSC->getSExtValue();
3657 if ((int)Val < 0) Val = -Val;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003658
Chris Lattnerf031e8a2010-01-01 03:32:16 +00003659 // powi(x, 0) -> 1.0
3660 if (Val == 0)
3661 return DAG.getConstantFP(1.0, LHS.getValueType());
3662
3663 Function *F = DAG.getMachineFunction().getFunction();
3664 if (!F->hasFnAttr(Attribute::OptimizeForSize) ||
3665 // If optimizing for size, don't insert too many multiplies. This
3666 // inserts up to 5 multiplies.
3667 CountPopulation_32(Val)+Log2_32(Val) < 7) {
3668 // We use the simple binary decomposition method to generate the multiply
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003669 // sequence. There are more optimal ways to do this (for example,
Chris Lattnerf031e8a2010-01-01 03:32:16 +00003670 // powi(x,15) generates one more multiply than it should), but this has
3671 // the benefit of being both really simple and much better than a libcall.
3672 SDValue Res; // Logically starts equal to 1.0
3673 SDValue CurSquare = LHS;
3674 while (Val) {
Mikhail Glushenkovbfdfea82010-01-01 04:41:36 +00003675 if (Val & 1) {
Chris Lattnerf031e8a2010-01-01 03:32:16 +00003676 if (Res.getNode())
3677 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
3678 else
3679 Res = CurSquare; // 1.0*CurSquare.
Mikhail Glushenkovbfdfea82010-01-01 04:41:36 +00003680 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003681
Chris Lattnerf031e8a2010-01-01 03:32:16 +00003682 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
3683 CurSquare, CurSquare);
3684 Val >>= 1;
3685 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003686
Chris Lattnerf031e8a2010-01-01 03:32:16 +00003687 // If the original was negative, invert the result, producing 1/(x*x*x).
3688 if (RHSC->getSExtValue() < 0)
3689 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
3690 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
3691 return Res;
3692 }
3693 }
3694
3695 // Otherwise, expand to a libcall.
3696 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
3697}
3698
3699
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003700/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3701/// we want to emit this as a call to a named external function, return the name
3702/// otherwise lower it and return null.
3703const char *
Dan Gohman2048b852009-11-23 18:04:58 +00003704SelectionDAGBuilder::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00003705 DebugLoc dl = getCurDebugLoc();
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003706 SDValue Res;
3707
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003708 switch (Intrinsic) {
3709 default:
3710 // By default, turn this into a target intrinsic node.
3711 visitTargetIntrinsic(I, Intrinsic);
3712 return 0;
3713 case Intrinsic::vastart: visitVAStart(I); return 0;
3714 case Intrinsic::vaend: visitVAEnd(I); return 0;
3715 case Intrinsic::vacopy: visitVACopy(I); return 0;
3716 case Intrinsic::returnaddress:
Bill Wendling4533cac2010-01-28 21:51:40 +00003717 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
3718 getValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003719 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00003720 case Intrinsic::frameaddress:
Bill Wendling4533cac2010-01-28 21:51:40 +00003721 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
3722 getValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003723 return 0;
3724 case Intrinsic::setjmp:
3725 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003726 case Intrinsic::longjmp:
3727 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattner824b9582008-11-21 16:42:48 +00003728 case Intrinsic::memcpy: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003729 SDValue Op1 = getValue(I.getOperand(1));
3730 SDValue Op2 = getValue(I.getOperand(2));
3731 SDValue Op3 = getValue(I.getOperand(3));
3732 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Bill Wendling4533cac2010-01-28 21:51:40 +00003733 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
3734 I.getOperand(1), 0, I.getOperand(2), 0));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003735 return 0;
3736 }
Chris Lattner824b9582008-11-21 16:42:48 +00003737 case Intrinsic::memset: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003738 SDValue Op1 = getValue(I.getOperand(1));
3739 SDValue Op2 = getValue(I.getOperand(2));
3740 SDValue Op3 = getValue(I.getOperand(3));
3741 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Bill Wendling4533cac2010-01-28 21:51:40 +00003742 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
3743 I.getOperand(1), 0));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003744 return 0;
3745 }
Chris Lattner824b9582008-11-21 16:42:48 +00003746 case Intrinsic::memmove: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003747 SDValue Op1 = getValue(I.getOperand(1));
3748 SDValue Op2 = getValue(I.getOperand(2));
3749 SDValue Op3 = getValue(I.getOperand(3));
3750 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3751
3752 // If the source and destination are known to not be aliases, we can
3753 // lower memmove as memcpy.
3754 uint64_t Size = -1ULL;
3755 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003756 Size = C->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003757 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3758 AliasAnalysis::NoAlias) {
Bill Wendling4533cac2010-01-28 21:51:40 +00003759 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
3760 I.getOperand(1), 0, I.getOperand(2), 0));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003761 return 0;
3762 }
3763
Bill Wendling4533cac2010-01-28 21:51:40 +00003764 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
3765 I.getOperand(1), 0, I.getOperand(2), 0));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003766 return 0;
3767 }
Bill Wendling92c1e122009-02-13 02:16:35 +00003768 case Intrinsic::dbg_declare: {
Dale Johannesen904c2fa2010-02-01 19:54:53 +00003769 // FIXME: currently, we get here only if OptLevel != CodeGenOpt::None.
3770 // The real handling of this intrinsic is in FastISel.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003771 if (OptLevel != CodeGenOpt::None)
Devang Patel7e1e31f2009-07-02 22:43:26 +00003772 // FIXME: Variable debug info is not supported here.
3773 return 0;
Devang Patel24f20e02009-08-22 17:12:53 +00003774 DwarfWriter *DW = DAG.getDwarfWriter();
3775 if (!DW)
3776 return 0;
Devang Patel7e1e31f2009-07-02 22:43:26 +00003777 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Chris Lattnerbf0ca2b2009-12-29 09:32:19 +00003778 if (!DIDescriptor::ValidDebugInfo(DI.getVariable(), CodeGenOpt::None))
Devang Patel7e1e31f2009-07-02 22:43:26 +00003779 return 0;
3780
Devang Patelac1ceb32009-10-09 22:42:28 +00003781 MDNode *Variable = DI.getVariable();
Devang Patel24f20e02009-08-22 17:12:53 +00003782 Value *Address = DI.getAddress();
Dale Johannesen8ac38f22010-02-08 21:53:27 +00003783 if (!Address)
3784 return 0;
Devang Patel24f20e02009-08-22 17:12:53 +00003785 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
3786 Address = BCI->getOperand(0);
3787 AllocaInst *AI = dyn_cast<AllocaInst>(Address);
3788 // Don't handle byval struct arguments or VLAs, for example.
3789 if (!AI)
3790 return 0;
Devang Patelbd1d6a82009-09-05 00:34:14 +00003791 DenseMap<const AllocaInst*, int>::iterator SI =
3792 FuncInfo.StaticAllocaMap.find(AI);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003793 if (SI == FuncInfo.StaticAllocaMap.end())
Devang Patelbd1d6a82009-09-05 00:34:14 +00003794 return 0; // VLAs.
3795 int FI = SI->second;
Devang Patel70d75ca2009-11-12 19:02:56 +00003796
Chris Lattner3990b122009-12-28 23:41:32 +00003797 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo())
3798 if (MDNode *Dbg = DI.getMetadata("dbg"))
Chris Lattner0eb41982009-12-28 20:45:51 +00003799 MMI->setVariableDbgInfo(Variable, FI, Dbg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003800 return 0;
Bill Wendling92c1e122009-02-13 02:16:35 +00003801 }
Dale Johannesen904c2fa2010-02-01 19:54:53 +00003802 case Intrinsic::dbg_value: {
3803 // FIXME: currently, we get here only if OptLevel != CodeGenOpt::None.
3804 // The real handling of this intrinsic is in FastISel.
3805 if (OptLevel != CodeGenOpt::None)
3806 // FIXME: Variable debug info is not supported here.
3807 return 0;
3808 DwarfWriter *DW = DAG.getDwarfWriter();
3809 if (!DW)
3810 return 0;
3811 DbgValueInst &DI = cast<DbgValueInst>(I);
3812 if (!DIDescriptor::ValidDebugInfo(DI.getVariable(), CodeGenOpt::None))
3813 return 0;
3814
3815 MDNode *Variable = DI.getVariable();
3816 Value *V = DI.getValue();
3817 if (!V)
3818 return 0;
3819 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
3820 V = BCI->getOperand(0);
3821 AllocaInst *AI = dyn_cast<AllocaInst>(V);
3822 // Don't handle byval struct arguments or VLAs, for example.
3823 if (!AI)
3824 return 0;
3825 DenseMap<const AllocaInst*, int>::iterator SI =
3826 FuncInfo.StaticAllocaMap.find(AI);
3827 if (SI == FuncInfo.StaticAllocaMap.end())
3828 return 0; // VLAs.
3829 int FI = SI->second;
3830 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo())
3831 if (MDNode *Dbg = DI.getMetadata("dbg"))
3832 MMI->setVariableDbgInfo(Variable, FI, Dbg);
3833 return 0;
3834 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003835 case Intrinsic::eh_exception: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003836 // Insert the EXCEPTIONADDR instruction.
Duncan Sandsb0f1e172009-05-22 20:36:31 +00003837 assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!");
Owen Anderson825b72b2009-08-11 20:47:22 +00003838 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003839 SDValue Ops[1];
3840 Ops[0] = DAG.getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003841 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003842 setValue(&I, Op);
3843 DAG.setRoot(Op.getValue(1));
3844 return 0;
3845 }
3846
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00003847 case Intrinsic::eh_selector: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003848 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003849
Chris Lattner3a5815f2009-09-17 23:54:54 +00003850 if (CurMBB->isLandingPad())
3851 AddCatchInfo(I, MMI, CurMBB);
3852 else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003853#ifndef NDEBUG
Chris Lattner3a5815f2009-09-17 23:54:54 +00003854 FuncInfo.CatchInfoLost.insert(&I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003855#endif
Chris Lattner3a5815f2009-09-17 23:54:54 +00003856 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3857 unsigned Reg = TLI.getExceptionSelectorRegister();
3858 if (Reg) CurMBB->addLiveIn(Reg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003859 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003860
Chris Lattner3a5815f2009-09-17 23:54:54 +00003861 // Insert the EHSELECTION instruction.
3862 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3863 SDValue Ops[2];
3864 Ops[0] = getValue(I.getOperand(1));
3865 Ops[1] = getRoot();
3866 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
Chris Lattner3a5815f2009-09-17 23:54:54 +00003867 DAG.setRoot(Op.getValue(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00003868 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003869 return 0;
3870 }
3871
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00003872 case Intrinsic::eh_typeid_for: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003873 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003874
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003875 if (MMI) {
3876 // Find the type id for the given typeinfo.
3877 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003878 unsigned TypeID = MMI->getTypeIDFor(GV);
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003879 Res = DAG.getConstant(TypeID, MVT::i32);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003880 } else {
3881 // Return something different to eh_selector.
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003882 Res = DAG.getConstant(1, MVT::i32);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003883 }
3884
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003885 setValue(&I, Res);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003886 return 0;
3887 }
3888
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003889 case Intrinsic::eh_return_i32:
3890 case Intrinsic::eh_return_i64:
3891 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003892 MMI->setCallsEHReturn(true);
Bill Wendling4533cac2010-01-28 21:51:40 +00003893 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
3894 MVT::Other,
3895 getControlRoot(),
3896 getValue(I.getOperand(1)),
3897 getValue(I.getOperand(2))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003898 } else {
3899 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3900 }
3901
3902 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003903 case Intrinsic::eh_unwind_init:
3904 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3905 MMI->setCallsUnwindInit(true);
3906 }
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003907 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003908 case Intrinsic::eh_dwarf_cfa: {
Owen Andersone50ed302009-08-10 22:56:29 +00003909 EVT VT = getValue(I.getOperand(1)).getValueType();
Duncan Sands3a66a682009-10-13 21:04:12 +00003910 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), dl,
3911 TLI.getPointerTy());
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003912 SDValue Offset = DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003913 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003914 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003915 TLI.getPointerTy()),
3916 CfaArg);
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003917 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003918 TLI.getPointerTy(),
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003919 DAG.getConstant(0, TLI.getPointerTy()));
Bill Wendling4533cac2010-01-28 21:51:40 +00003920 setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
3921 FA, Offset));
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003922 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003923 }
Jim Grosbachca752c92010-01-28 01:45:32 +00003924 case Intrinsic::eh_sjlj_callsite: {
3925 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3926 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
3927 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
3928 assert(MMI->getCurrentCallSite() == 0 && "Overlapping call sites!");
3929
3930 MMI->setCurrentCallSite(CI->getZExtValue());
3931 return 0;
3932 }
3933
Mon P Wang77cdf302008-11-10 20:54:11 +00003934 case Intrinsic::convertff:
3935 case Intrinsic::convertfsi:
3936 case Intrinsic::convertfui:
3937 case Intrinsic::convertsif:
3938 case Intrinsic::convertuif:
3939 case Intrinsic::convertss:
3940 case Intrinsic::convertsu:
3941 case Intrinsic::convertus:
3942 case Intrinsic::convertuu: {
3943 ISD::CvtCode Code = ISD::CVT_INVALID;
3944 switch (Intrinsic) {
3945 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
3946 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
3947 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
3948 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
3949 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
3950 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
3951 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
3952 case Intrinsic::convertus: Code = ISD::CVT_US; break;
3953 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
3954 }
Owen Andersone50ed302009-08-10 22:56:29 +00003955 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003956 Value *Op1 = I.getOperand(1);
3957 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
3958 DAG.getValueType(DestVT),
3959 DAG.getValueType(getValue(Op1).getValueType()),
3960 getValue(I.getOperand(2)),
3961 getValue(I.getOperand(3)),
3962 Code);
3963 setValue(&I, Res);
Mon P Wang77cdf302008-11-10 20:54:11 +00003964 return 0;
3965 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003966 case Intrinsic::sqrt:
Bill Wendling4533cac2010-01-28 21:51:40 +00003967 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
3968 getValue(I.getOperand(1)).getValueType(),
3969 getValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003970 return 0;
3971 case Intrinsic::powi:
Bill Wendling4533cac2010-01-28 21:51:40 +00003972 setValue(&I, ExpandPowI(dl, getValue(I.getOperand(1)),
3973 getValue(I.getOperand(2)), DAG));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003974 return 0;
3975 case Intrinsic::sin:
Bill Wendling4533cac2010-01-28 21:51:40 +00003976 setValue(&I, DAG.getNode(ISD::FSIN, dl,
3977 getValue(I.getOperand(1)).getValueType(),
3978 getValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003979 return 0;
3980 case Intrinsic::cos:
Bill Wendling4533cac2010-01-28 21:51:40 +00003981 setValue(&I, DAG.getNode(ISD::FCOS, dl,
3982 getValue(I.getOperand(1)).getValueType(),
3983 getValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003984 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003985 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003986 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003987 return 0;
3988 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003989 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003990 return 0;
3991 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003992 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003993 return 0;
3994 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003995 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003996 return 0;
3997 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00003998 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003999 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004000 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004001 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004002 return 0;
4003 case Intrinsic::pcmarker: {
4004 SDValue Tmp = getValue(I.getOperand(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00004005 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004006 return 0;
4007 }
4008 case Intrinsic::readcyclecounter: {
4009 SDValue Op = getRoot();
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004010 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4011 DAG.getVTList(MVT::i64, MVT::Other),
4012 &Op, 1);
4013 setValue(&I, Res);
4014 DAG.setRoot(Res.getValue(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004015 return 0;
4016 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004017 case Intrinsic::bswap:
Bill Wendling4533cac2010-01-28 21:51:40 +00004018 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
4019 getValue(I.getOperand(1)).getValueType(),
4020 getValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004021 return 0;
4022 case Intrinsic::cttz: {
4023 SDValue Arg = getValue(I.getOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00004024 EVT Ty = Arg.getValueType();
Bill Wendling4533cac2010-01-28 21:51:40 +00004025 setValue(&I, DAG.getNode(ISD::CTTZ, dl, Ty, Arg));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004026 return 0;
4027 }
4028 case Intrinsic::ctlz: {
4029 SDValue Arg = getValue(I.getOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00004030 EVT Ty = Arg.getValueType();
Bill Wendling4533cac2010-01-28 21:51:40 +00004031 setValue(&I, DAG.getNode(ISD::CTLZ, dl, Ty, Arg));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004032 return 0;
4033 }
4034 case Intrinsic::ctpop: {
4035 SDValue Arg = getValue(I.getOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00004036 EVT Ty = Arg.getValueType();
Bill Wendling4533cac2010-01-28 21:51:40 +00004037 setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004038 return 0;
4039 }
4040 case Intrinsic::stacksave: {
4041 SDValue Op = getRoot();
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004042 Res = DAG.getNode(ISD::STACKSAVE, dl,
4043 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4044 setValue(&I, Res);
4045 DAG.setRoot(Res.getValue(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004046 return 0;
4047 }
4048 case Intrinsic::stackrestore: {
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004049 Res = getValue(I.getOperand(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00004050 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004051 return 0;
4052 }
Bill Wendling57344502008-11-18 11:01:33 +00004053 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00004054 // Emit code into the DAG to store the stack guard onto the stack.
4055 MachineFunction &MF = DAG.getMachineFunction();
4056 MachineFrameInfo *MFI = MF.getFrameInfo();
Owen Andersone50ed302009-08-10 22:56:29 +00004057 EVT PtrTy = TLI.getPointerTy();
Bill Wendlingb2a42982008-11-06 02:29:10 +00004058
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004059 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4060 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
Bill Wendlingb2a42982008-11-06 02:29:10 +00004061
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004062 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00004063 MFI->setStackProtectorIndex(FI);
4064
4065 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4066
4067 // Store the stack protector onto the stack.
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004068 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4069 PseudoSourceValue::getFixedStack(FI),
David Greene1e559442010-02-15 17:00:31 +00004070 0, true, false, 0);
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004071 setValue(&I, Res);
4072 DAG.setRoot(Res);
Bill Wendlingb2a42982008-11-06 02:29:10 +00004073 return 0;
4074 }
Eric Christopher7b5e6172009-10-27 00:52:25 +00004075 case Intrinsic::objectsize: {
4076 // If we don't know by now, we're never going to know.
4077 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2));
4078
4079 assert(CI && "Non-constant type in __builtin_object_size?");
4080
Eric Christopher7e5d2ff2009-10-28 21:32:16 +00004081 SDValue Arg = getValue(I.getOperand(0));
4082 EVT Ty = Arg.getValueType();
4083
Eric Christopherd060b252009-12-23 02:51:48 +00004084 if (CI->getZExtValue() == 0)
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004085 Res = DAG.getConstant(-1ULL, Ty);
Eric Christopher7b5e6172009-10-27 00:52:25 +00004086 else
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004087 Res = DAG.getConstant(0, Ty);
4088
4089 setValue(&I, Res);
Eric Christopher7b5e6172009-10-27 00:52:25 +00004090 return 0;
4091 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004092 case Intrinsic::var_annotation:
4093 // Discard annotate attributes
4094 return 0;
4095
4096 case Intrinsic::init_trampoline: {
4097 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4098
4099 SDValue Ops[6];
4100 Ops[0] = getRoot();
4101 Ops[1] = getValue(I.getOperand(1));
4102 Ops[2] = getValue(I.getOperand(2));
4103 Ops[3] = getValue(I.getOperand(3));
4104 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4105 Ops[5] = DAG.getSrcValue(F);
4106
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004107 Res = DAG.getNode(ISD::TRAMPOLINE, dl,
4108 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4109 Ops, 6);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004110
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004111 setValue(&I, Res);
4112 DAG.setRoot(Res.getValue(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004113 return 0;
4114 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004115 case Intrinsic::gcroot:
4116 if (GFI) {
4117 Value *Alloca = I.getOperand(1);
4118 Constant *TypeMap = cast<Constant>(I.getOperand(2));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004119
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004120 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4121 GFI->addStackRoot(FI->getIndex(), TypeMap);
4122 }
4123 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004124 case Intrinsic::gcread:
4125 case Intrinsic::gcwrite:
Torok Edwinc23197a2009-07-14 16:55:14 +00004126 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004127 return 0;
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004128 case Intrinsic::flt_rounds:
Bill Wendling4533cac2010-01-28 21:51:40 +00004129 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004130 return 0;
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004131 case Intrinsic::trap:
Bill Wendling4533cac2010-01-28 21:51:40 +00004132 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004133 return 0;
Bill Wendlingef375462008-11-21 02:38:44 +00004134 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00004135 return implVisitAluOverflow(I, ISD::UADDO);
4136 case Intrinsic::sadd_with_overflow:
4137 return implVisitAluOverflow(I, ISD::SADDO);
4138 case Intrinsic::usub_with_overflow:
4139 return implVisitAluOverflow(I, ISD::USUBO);
4140 case Intrinsic::ssub_with_overflow:
4141 return implVisitAluOverflow(I, ISD::SSUBO);
4142 case Intrinsic::umul_with_overflow:
4143 return implVisitAluOverflow(I, ISD::UMULO);
4144 case Intrinsic::smul_with_overflow:
4145 return implVisitAluOverflow(I, ISD::SMULO);
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004146
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004147 case Intrinsic::prefetch: {
4148 SDValue Ops[4];
4149 Ops[0] = getRoot();
4150 Ops[1] = getValue(I.getOperand(1));
4151 Ops[2] = getValue(I.getOperand(2));
4152 Ops[3] = getValue(I.getOperand(3));
Bill Wendling4533cac2010-01-28 21:51:40 +00004153 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004154 return 0;
4155 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004156
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004157 case Intrinsic::memory_barrier: {
4158 SDValue Ops[6];
4159 Ops[0] = getRoot();
4160 for (int x = 1; x < 6; ++x)
4161 Ops[x] = getValue(I.getOperand(x));
4162
Bill Wendling4533cac2010-01-28 21:51:40 +00004163 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004164 return 0;
4165 }
4166 case Intrinsic::atomic_cmp_swap: {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004167 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004168 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00004169 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004170 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4171 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004172 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004173 getValue(I.getOperand(2)),
4174 getValue(I.getOperand(3)),
4175 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004176 setValue(&I, L);
4177 DAG.setRoot(L.getValue(1));
4178 return 0;
4179 }
4180 case Intrinsic::atomic_load_add:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004181 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004182 case Intrinsic::atomic_load_sub:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004183 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004184 case Intrinsic::atomic_load_or:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004185 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004186 case Intrinsic::atomic_load_xor:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004187 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004188 case Intrinsic::atomic_load_and:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004189 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004190 case Intrinsic::atomic_load_nand:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004191 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004192 case Intrinsic::atomic_load_max:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004193 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004194 case Intrinsic::atomic_load_min:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004195 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004196 case Intrinsic::atomic_load_umin:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004197 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004198 case Intrinsic::atomic_load_umax:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004199 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004200 case Intrinsic::atomic_swap:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004201 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Duncan Sandsf07c9492009-11-10 09:08:09 +00004202
4203 case Intrinsic::invariant_start:
4204 case Intrinsic::lifetime_start:
4205 // Discard region information.
Bill Wendling4533cac2010-01-28 21:51:40 +00004206 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
Duncan Sandsf07c9492009-11-10 09:08:09 +00004207 return 0;
4208 case Intrinsic::invariant_end:
4209 case Intrinsic::lifetime_end:
4210 // Discard region information.
4211 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004212 }
4213}
4214
Dan Gohman98ca4f22009-08-05 01:29:28 +00004215/// Test if the given instruction is in a position to be optimized
4216/// with a tail-call. This roughly means that it's in a block with
4217/// a return and there's nothing that needs to be scheduled
4218/// between it and the return.
4219///
4220/// This function only tests target-independent requirements.
Dan Gohman98ca4f22009-08-05 01:29:28 +00004221static bool
Evan Cheng86809cc2010-02-03 03:28:02 +00004222isInTailCallPosition(CallSite CS, Attributes CalleeRetAttr,
Dan Gohman98ca4f22009-08-05 01:29:28 +00004223 const TargetLowering &TLI) {
Evan Cheng86809cc2010-02-03 03:28:02 +00004224 const Instruction *I = CS.getInstruction();
Dan Gohman98ca4f22009-08-05 01:29:28 +00004225 const BasicBlock *ExitBB = I->getParent();
4226 const TerminatorInst *Term = ExitBB->getTerminator();
4227 const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
4228 const Function *F = ExitBB->getParent();
4229
Dan Gohmanc2e93b22010-02-08 20:34:14 +00004230 // The block must end in a return statement or unreachable.
4231 //
4232 // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
4233 // an unreachable, for now. The way tailcall optimization is currently
4234 // implemented means it will add an epilogue followed by a jump. That is
4235 // not profitable. Also, if the callee is a special function (e.g.
4236 // longjmp on x86), it can end up causing miscompilation that has not
4237 // been fully understood.
4238 if (!Ret &&
4239 (!GuaranteedTailCallOpt || !isa<UnreachableInst>(Term))) return false;
Dan Gohman98ca4f22009-08-05 01:29:28 +00004240
4241 // If I will have a chain, make sure no other instruction that will have a
4242 // chain interposes between I and the return.
4243 if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
4244 !I->isSafeToSpeculativelyExecute())
4245 for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
4246 --BBI) {
4247 if (&*BBI == I)
4248 break;
4249 if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
4250 !BBI->isSafeToSpeculativelyExecute())
4251 return false;
4252 }
4253
4254 // If the block ends with a void return or unreachable, it doesn't matter
4255 // what the call's return type is.
4256 if (!Ret || Ret->getNumOperands() == 0) return true;
4257
Dan Gohmaned9bab32009-11-14 02:06:30 +00004258 // If the return value is undef, it doesn't matter what the call's
4259 // return type is.
4260 if (isa<UndefValue>(Ret->getOperand(0))) return true;
4261
Dan Gohman98ca4f22009-08-05 01:29:28 +00004262 // Conservatively require the attributes of the call to match those of
Dan Gohman01205a82009-11-13 18:49:38 +00004263 // the return. Ignore noalias because it doesn't affect the call sequence.
4264 unsigned CallerRetAttr = F->getAttributes().getRetAttributes();
4265 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
Dan Gohman98ca4f22009-08-05 01:29:28 +00004266 return false;
4267
Evan Cheng6fdce652010-02-04 19:07:06 +00004268 // It's not safe to eliminate the sign / zero extension of the return value.
Evan Cheng446bc102010-02-04 02:45:02 +00004269 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
4270 return false;
4271
Dan Gohman98ca4f22009-08-05 01:29:28 +00004272 // Otherwise, make sure the unmodified return value of I is the return value.
4273 for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ;
4274 U = dyn_cast<Instruction>(U->getOperand(0))) {
4275 if (!U)
4276 return false;
4277 if (!U->hasOneUse())
4278 return false;
4279 if (U == I)
4280 break;
4281 // Check for a truly no-op truncate.
4282 if (isa<TruncInst>(U) &&
4283 TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType()))
4284 continue;
4285 // Check for a truly no-op bitcast.
4286 if (isa<BitCastInst>(U) &&
4287 (U->getOperand(0)->getType() == U->getType() ||
Duncan Sands1df98592010-02-16 11:11:14 +00004288 (U->getOperand(0)->getType()->isPointerTy() &&
4289 U->getType()->isPointerTy())))
Dan Gohman98ca4f22009-08-05 01:29:28 +00004290 continue;
4291 // Otherwise it's not a true no-op.
4292 return false;
4293 }
4294
4295 return true;
4296}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004297
Dan Gohman2048b852009-11-23 18:04:58 +00004298void SelectionDAGBuilder::LowerCallTo(CallSite CS, SDValue Callee,
4299 bool isTailCall,
4300 MachineBasicBlock *LandingPad) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004301 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4302 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004303 const Type *RetTy = FTy->getReturnType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004304 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4305 unsigned BeginLabel = 0, EndLabel = 0;
4306
4307 TargetLowering::ArgListTy Args;
4308 TargetLowering::ArgListEntry Entry;
4309 Args.reserve(CS.arg_size());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004310
4311 // Check whether the function can return without sret-demotion.
4312 SmallVector<EVT, 4> OutVTs;
4313 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
4314 SmallVector<uint64_t, 4> Offsets;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004315 getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
Bill Wendlinge80ae832009-12-22 00:50:32 +00004316 OutVTs, OutsFlags, TLI, &Offsets);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004317
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004318 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004319 FTy->isVarArg(), OutVTs, OutsFlags, DAG);
4320
4321 SDValue DemoteStackSlot;
4322
4323 if (!CanLowerReturn) {
4324 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
4325 FTy->getReturnType());
4326 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
4327 FTy->getReturnType());
4328 MachineFunction &MF = DAG.getMachineFunction();
David Greene3f2bf852009-11-12 20:49:22 +00004329 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004330 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
4331
4332 DemoteStackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4333 Entry.Node = DemoteStackSlot;
4334 Entry.Ty = StackSlotPtrType;
4335 Entry.isSExt = false;
4336 Entry.isZExt = false;
4337 Entry.isInReg = false;
4338 Entry.isSRet = true;
4339 Entry.isNest = false;
4340 Entry.isByVal = false;
4341 Entry.Alignment = Align;
4342 Args.push_back(Entry);
4343 RetTy = Type::getVoidTy(FTy->getContext());
4344 }
4345
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004346 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004347 i != e; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004348 SDValue ArgNode = getValue(*i);
4349 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4350
4351 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00004352 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4353 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4354 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4355 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4356 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4357 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004358 Entry.Alignment = CS.getParamAlignment(attrInd);
4359 Args.push_back(Entry);
4360 }
4361
4362 if (LandingPad && MMI) {
4363 // Insert a label before the invoke call to mark the try range. This can be
4364 // used to detect deletion of the invoke via the MachineModuleInfo.
4365 BeginLabel = MMI->NextLabelID();
Jim Grosbach1b747ad2009-08-11 00:09:57 +00004366
Jim Grosbachca752c92010-01-28 01:45:32 +00004367 // For SjLj, keep track of which landing pads go with which invokes
4368 // so as to maintain the ordering of pads in the LSDA.
4369 unsigned CallSiteIndex = MMI->getCurrentCallSite();
4370 if (CallSiteIndex) {
4371 MMI->setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
4372 // Now that the call site is handled, stop tracking it.
4373 MMI->setCurrentCallSite(0);
4374 }
4375
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004376 // Both PendingLoads and PendingExports must be flushed here;
4377 // this call might not return.
4378 (void)getRoot();
Bill Wendling0d580132009-12-23 01:28:19 +00004379 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4380 getControlRoot(), BeginLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004381 }
4382
Dan Gohman98ca4f22009-08-05 01:29:28 +00004383 // Check if target-independent constraints permit a tail call here.
4384 // Target-dependent constraints are checked within TLI.LowerCallTo.
4385 if (isTailCall &&
Evan Cheng86809cc2010-02-03 03:28:02 +00004386 !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI))
Dan Gohman98ca4f22009-08-05 01:29:28 +00004387 isTailCall = false;
4388
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004389 std::pair<SDValue,SDValue> Result =
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004390 TLI.LowerCallTo(getRoot(), RetTy,
Devang Patel05988662008-09-25 21:00:45 +00004391 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004392 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
Tilmann Scheller6b61cd12009-07-03 06:44:53 +00004393 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004394 CS.getCallingConv(),
Dan Gohman98ca4f22009-08-05 01:29:28 +00004395 isTailCall,
4396 !CS.getInstruction()->use_empty(),
Bill Wendling3ea3c242009-12-22 02:10:19 +00004397 Callee, Args, DAG, getCurDebugLoc(), SDNodeOrder);
Dan Gohman98ca4f22009-08-05 01:29:28 +00004398 assert((isTailCall || Result.second.getNode()) &&
4399 "Non-null chain expected with non-tail call!");
4400 assert((Result.second.getNode() || !Result.first.getNode()) &&
4401 "Null value expected with tail call!");
Bill Wendlinge80ae832009-12-22 00:50:32 +00004402 if (Result.first.getNode()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004403 setValue(CS.getInstruction(), Result.first);
Bill Wendlinge80ae832009-12-22 00:50:32 +00004404 } else if (!CanLowerReturn && Result.second.getNode()) {
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004405 // The instruction result is the result of loading from the
4406 // hidden sret parameter.
4407 SmallVector<EVT, 1> PVTs;
4408 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
4409
4410 ComputeValueVTs(TLI, PtrRetTy, PVTs);
4411 assert(PVTs.size() == 1 && "Pointers should fit in one register");
4412 EVT PtrVT = PVTs[0];
4413 unsigned NumValues = OutVTs.size();
4414 SmallVector<SDValue, 4> Values(NumValues);
4415 SmallVector<SDValue, 4> Chains(NumValues);
4416
4417 for (unsigned i = 0; i < NumValues; ++i) {
Bill Wendlinge80ae832009-12-22 00:50:32 +00004418 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
4419 DemoteStackSlot,
4420 DAG.getConstant(Offsets[i], PtrVT));
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004421 SDValue L = DAG.getLoad(OutVTs[i], getCurDebugLoc(), Result.second,
David Greene1e559442010-02-15 17:00:31 +00004422 Add, NULL, Offsets[i], false, false, 1);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004423 Values[i] = L;
4424 Chains[i] = L.getValue(1);
4425 }
Bill Wendlinge80ae832009-12-22 00:50:32 +00004426
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004427 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
4428 MVT::Other, &Chains[0], NumValues);
4429 PendingLoads.push_back(Chain);
Kenneth Uildriks93ae4072010-01-16 23:37:33 +00004430
4431 // Collect the legal value parts into potentially illegal values
4432 // that correspond to the original function's return values.
4433 SmallVector<EVT, 4> RetTys;
4434 RetTy = FTy->getReturnType();
4435 ComputeValueVTs(TLI, RetTy, RetTys);
4436 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4437 SmallVector<SDValue, 4> ReturnValues;
4438 unsigned CurReg = 0;
4439 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4440 EVT VT = RetTys[I];
4441 EVT RegisterVT = TLI.getRegisterType(RetTy->getContext(), VT);
4442 unsigned NumRegs = TLI.getNumRegisters(RetTy->getContext(), VT);
4443
4444 SDValue ReturnValue =
4445 getCopyFromParts(DAG, getCurDebugLoc(), SDNodeOrder, &Values[CurReg], NumRegs,
4446 RegisterVT, VT, AssertOp);
4447 ReturnValues.push_back(ReturnValue);
Kenneth Uildriks93ae4072010-01-16 23:37:33 +00004448 CurReg += NumRegs;
4449 }
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004450
Bill Wendling4533cac2010-01-28 21:51:40 +00004451 setValue(CS.getInstruction(),
4452 DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
4453 DAG.getVTList(&RetTys[0], RetTys.size()),
4454 &ReturnValues[0], ReturnValues.size()));
Bill Wendlinge80ae832009-12-22 00:50:32 +00004455
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004456 }
Bill Wendlinge80ae832009-12-22 00:50:32 +00004457
4458 // As a special case, a null chain means that a tail call has been emitted and
4459 // the DAG root is already updated.
Bill Wendling4533cac2010-01-28 21:51:40 +00004460 if (Result.second.getNode())
Dan Gohman98ca4f22009-08-05 01:29:28 +00004461 DAG.setRoot(Result.second);
Bill Wendling4533cac2010-01-28 21:51:40 +00004462 else
Dan Gohman98ca4f22009-08-05 01:29:28 +00004463 HasTailCall = true;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004464
4465 if (LandingPad && MMI) {
4466 // Insert a label at the end of the invoke call to mark the try range. This
4467 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4468 EndLabel = MMI->NextLabelID();
Bill Wendling0d580132009-12-23 01:28:19 +00004469 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4470 getRoot(), EndLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004471
4472 // Inform MachineModuleInfo of range.
4473 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4474 }
4475}
4476
Chris Lattner8047d9a2009-12-24 00:37:38 +00004477/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
4478/// value is equal or not-equal to zero.
4479static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
4480 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
4481 UI != E; ++UI) {
4482 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
4483 if (IC->isEquality())
4484 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
4485 if (C->isNullValue())
4486 continue;
4487 // Unknown instruction.
4488 return false;
4489 }
4490 return true;
4491}
4492
Chris Lattner04b091a2009-12-24 01:07:17 +00004493static SDValue getMemCmpLoad(Value *PtrVal, MVT LoadVT, const Type *LoadTy,
Chris Lattner8047d9a2009-12-24 00:37:38 +00004494 SelectionDAGBuilder &Builder) {
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004495
Chris Lattner8047d9a2009-12-24 00:37:38 +00004496 // Check to see if this load can be trivially constant folded, e.g. if the
4497 // input is from a string literal.
4498 if (Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
4499 // Cast pointer to the type we really want to load.
4500 LoadInput = ConstantExpr::getBitCast(LoadInput,
4501 PointerType::getUnqual(LoadTy));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004502
Chris Lattner8047d9a2009-12-24 00:37:38 +00004503 if (Constant *LoadCst = ConstantFoldLoadFromConstPtr(LoadInput, Builder.TD))
4504 return Builder.getValue(LoadCst);
4505 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004506
Chris Lattner8047d9a2009-12-24 00:37:38 +00004507 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
4508 // still constant memory, the input chain can be the entry node.
4509 SDValue Root;
4510 bool ConstantMemory = false;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004511
Chris Lattner8047d9a2009-12-24 00:37:38 +00004512 // Do not serialize (non-volatile) loads of constant memory with anything.
4513 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
4514 Root = Builder.DAG.getEntryNode();
4515 ConstantMemory = true;
4516 } else {
4517 // Do not serialize non-volatile loads against each other.
4518 Root = Builder.DAG.getRoot();
4519 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004520
Chris Lattner8047d9a2009-12-24 00:37:38 +00004521 SDValue Ptr = Builder.getValue(PtrVal);
4522 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root,
4523 Ptr, PtrVal /*SrcValue*/, 0/*SVOffset*/,
David Greene1e559442010-02-15 17:00:31 +00004524 false /*volatile*/,
4525 false /*nontemporal*/, 1 /* align=1 */);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004526
Chris Lattner8047d9a2009-12-24 00:37:38 +00004527 if (!ConstantMemory)
4528 Builder.PendingLoads.push_back(LoadVal.getValue(1));
4529 return LoadVal;
4530}
4531
4532
4533/// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
4534/// If so, return true and lower it, otherwise return false and it will be
4535/// lowered like a normal call.
4536bool SelectionDAGBuilder::visitMemCmpCall(CallInst &I) {
4537 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
4538 if (I.getNumOperands() != 4)
4539 return false;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004540
Chris Lattner8047d9a2009-12-24 00:37:38 +00004541 Value *LHS = I.getOperand(1), *RHS = I.getOperand(2);
Duncan Sands1df98592010-02-16 11:11:14 +00004542 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
4543 !I.getOperand(3)->getType()->isIntegerTy() ||
4544 !I.getType()->isIntegerTy())
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004545 return false;
4546
Chris Lattner8047d9a2009-12-24 00:37:38 +00004547 ConstantInt *Size = dyn_cast<ConstantInt>(I.getOperand(3));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004548
Chris Lattner8047d9a2009-12-24 00:37:38 +00004549 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
4550 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
Chris Lattner04b091a2009-12-24 01:07:17 +00004551 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) {
4552 bool ActuallyDoIt = true;
4553 MVT LoadVT;
4554 const Type *LoadTy;
4555 switch (Size->getZExtValue()) {
4556 default:
4557 LoadVT = MVT::Other;
4558 LoadTy = 0;
4559 ActuallyDoIt = false;
4560 break;
4561 case 2:
4562 LoadVT = MVT::i16;
4563 LoadTy = Type::getInt16Ty(Size->getContext());
4564 break;
4565 case 4:
4566 LoadVT = MVT::i32;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004567 LoadTy = Type::getInt32Ty(Size->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00004568 break;
4569 case 8:
4570 LoadVT = MVT::i64;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004571 LoadTy = Type::getInt64Ty(Size->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00004572 break;
4573 /*
4574 case 16:
4575 LoadVT = MVT::v4i32;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004576 LoadTy = Type::getInt32Ty(Size->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00004577 LoadTy = VectorType::get(LoadTy, 4);
4578 break;
4579 */
4580 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004581
Chris Lattner04b091a2009-12-24 01:07:17 +00004582 // This turns into unaligned loads. We only do this if the target natively
4583 // supports the MVT we'll be loading or if it is small enough (<= 4) that
4584 // we'll only produce a small number of byte loads.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004585
Chris Lattner04b091a2009-12-24 01:07:17 +00004586 // Require that we can find a legal MVT, and only do this if the target
4587 // supports unaligned loads of that type. Expanding into byte loads would
4588 // bloat the code.
4589 if (ActuallyDoIt && Size->getZExtValue() > 4) {
4590 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
4591 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
4592 if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT))
4593 ActuallyDoIt = false;
4594 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004595
Chris Lattner04b091a2009-12-24 01:07:17 +00004596 if (ActuallyDoIt) {
4597 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
4598 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004599
Chris Lattner04b091a2009-12-24 01:07:17 +00004600 SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal,
4601 ISD::SETNE);
4602 EVT CallVT = TLI.getValueType(I.getType(), true);
4603 setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT));
4604 return true;
4605 }
Chris Lattner8047d9a2009-12-24 00:37:38 +00004606 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004607
4608
Chris Lattner8047d9a2009-12-24 00:37:38 +00004609 return false;
4610}
4611
4612
Dan Gohman2048b852009-11-23 18:04:58 +00004613void SelectionDAGBuilder::visitCall(CallInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004614 const char *RenameFn = 0;
4615 if (Function *F = I.getCalledFunction()) {
4616 if (F->isDeclaration()) {
Dale Johannesen49de9822009-02-05 01:49:45 +00004617 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4618 if (II) {
4619 if (unsigned IID = II->getIntrinsicID(F)) {
4620 RenameFn = visitIntrinsicCall(I, IID);
4621 if (!RenameFn)
4622 return;
4623 }
4624 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004625 if (unsigned IID = F->getIntrinsicID()) {
4626 RenameFn = visitIntrinsicCall(I, IID);
4627 if (!RenameFn)
4628 return;
4629 }
4630 }
4631
4632 // Check for well-known libc/libm calls. If the function is internal, it
4633 // can't be a library call.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004634 if (!F->hasLocalLinkage() && F->hasName()) {
4635 StringRef Name = F->getName();
4636 if (Name == "copysign" || Name == "copysignf") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004637 if (I.getNumOperands() == 3 && // Basic sanity checks.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00004638 I.getOperand(1)->getType()->isFloatingPointTy() &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004639 I.getType() == I.getOperand(1)->getType() &&
4640 I.getType() == I.getOperand(2)->getType()) {
4641 SDValue LHS = getValue(I.getOperand(1));
4642 SDValue RHS = getValue(I.getOperand(2));
Bill Wendling0d580132009-12-23 01:28:19 +00004643 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
4644 LHS.getValueType(), LHS, RHS));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004645 return;
4646 }
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004647 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004648 if (I.getNumOperands() == 2 && // Basic sanity checks.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00004649 I.getOperand(1)->getType()->isFloatingPointTy() &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004650 I.getType() == I.getOperand(1)->getType()) {
4651 SDValue Tmp = getValue(I.getOperand(1));
Bill Wendling0d580132009-12-23 01:28:19 +00004652 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
4653 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004654 return;
4655 }
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004656 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004657 if (I.getNumOperands() == 2 && // Basic sanity checks.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00004658 I.getOperand(1)->getType()->isFloatingPointTy() &&
Dale Johannesena45bfd32009-09-25 18:00:35 +00004659 I.getType() == I.getOperand(1)->getType() &&
4660 I.onlyReadsMemory()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004661 SDValue Tmp = getValue(I.getOperand(1));
Bill Wendling0d580132009-12-23 01:28:19 +00004662 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
4663 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004664 return;
4665 }
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004666 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004667 if (I.getNumOperands() == 2 && // Basic sanity checks.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00004668 I.getOperand(1)->getType()->isFloatingPointTy() &&
Dale Johannesena45bfd32009-09-25 18:00:35 +00004669 I.getType() == I.getOperand(1)->getType() &&
4670 I.onlyReadsMemory()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004671 SDValue Tmp = getValue(I.getOperand(1));
Bill Wendling0d580132009-12-23 01:28:19 +00004672 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
4673 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004674 return;
4675 }
Dale Johannesen52fb79b2009-09-25 17:23:22 +00004676 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
4677 if (I.getNumOperands() == 2 && // Basic sanity checks.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00004678 I.getOperand(1)->getType()->isFloatingPointTy() &&
Dale Johannesena45bfd32009-09-25 18:00:35 +00004679 I.getType() == I.getOperand(1)->getType() &&
4680 I.onlyReadsMemory()) {
Dale Johannesen52fb79b2009-09-25 17:23:22 +00004681 SDValue Tmp = getValue(I.getOperand(1));
Bill Wendling0d580132009-12-23 01:28:19 +00004682 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
4683 Tmp.getValueType(), Tmp));
Dale Johannesen52fb79b2009-09-25 17:23:22 +00004684 return;
4685 }
Chris Lattner8047d9a2009-12-24 00:37:38 +00004686 } else if (Name == "memcmp") {
4687 if (visitMemCmpCall(I))
4688 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004689 }
4690 }
4691 } else if (isa<InlineAsm>(I.getOperand(0))) {
4692 visitInlineAsm(&I);
4693 return;
4694 }
4695
4696 SDValue Callee;
4697 if (!RenameFn)
4698 Callee = getValue(I.getOperand(0));
4699 else
Bill Wendling056292f2008-09-16 21:48:12 +00004700 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004701
Bill Wendling0d580132009-12-23 01:28:19 +00004702 // Check if we can potentially perform a tail call. More detailed checking is
4703 // be done within LowerCallTo, after more information about the call is known.
Evan Cheng11e67932010-01-26 23:13:04 +00004704 LowerCallTo(&I, Callee, I.isTailCall());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004705}
4706
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004707/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004708/// this value and returns the result as a ValueVT value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004709/// Chain/Flag as the input and updates them for the output Chain/Flag.
4710/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004711SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
Bill Wendlingec72e322009-12-22 01:11:43 +00004712 unsigned Order, SDValue &Chain,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004713 SDValue *Flag) const {
4714 // Assemble the legal parts into the final values.
4715 SmallVector<SDValue, 4> Values(ValueVTs.size());
4716 SmallVector<SDValue, 8> Parts;
4717 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4718 // Copy the legal parts from the registers.
Owen Andersone50ed302009-08-10 22:56:29 +00004719 EVT ValueVT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00004720 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
Owen Andersone50ed302009-08-10 22:56:29 +00004721 EVT RegisterVT = RegVTs[Value];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004722
4723 Parts.resize(NumRegs);
4724 for (unsigned i = 0; i != NumRegs; ++i) {
4725 SDValue P;
Bill Wendlingec72e322009-12-22 01:11:43 +00004726 if (Flag == 0) {
Dale Johannesena04b7572009-02-03 23:04:43 +00004727 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
Bill Wendlingec72e322009-12-22 01:11:43 +00004728 } else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004729 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004730 *Flag = P.getValue(2);
4731 }
Bill Wendlingec72e322009-12-22 01:11:43 +00004732
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004733 Chain = P.getValue(1);
Bill Wendlingec72e322009-12-22 01:11:43 +00004734
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004735 // If the source register was virtual and if we know something about it,
4736 // add an assert node.
4737 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4738 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4739 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4740 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4741 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4742 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004743
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004744 unsigned RegSize = RegisterVT.getSizeInBits();
4745 unsigned NumSignBits = LOI.NumSignBits;
4746 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004747
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004748 // FIXME: We capture more information than the dag can represent. For
4749 // now, just use the tightest assertzext/assertsext possible.
4750 bool isSExt = true;
Owen Anderson825b72b2009-08-11 20:47:22 +00004751 EVT FromVT(MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004752 if (NumSignBits == RegSize)
Owen Anderson825b72b2009-08-11 20:47:22 +00004753 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004754 else if (NumZeroBits >= RegSize-1)
Owen Anderson825b72b2009-08-11 20:47:22 +00004755 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004756 else if (NumSignBits > RegSize-8)
Owen Anderson825b72b2009-08-11 20:47:22 +00004757 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
Dan Gohman07c26ee2009-03-31 01:38:29 +00004758 else if (NumZeroBits >= RegSize-8)
Owen Anderson825b72b2009-08-11 20:47:22 +00004759 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004760 else if (NumSignBits > RegSize-16)
Owen Anderson825b72b2009-08-11 20:47:22 +00004761 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
Dan Gohman07c26ee2009-03-31 01:38:29 +00004762 else if (NumZeroBits >= RegSize-16)
Owen Anderson825b72b2009-08-11 20:47:22 +00004763 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004764 else if (NumSignBits > RegSize-32)
Owen Anderson825b72b2009-08-11 20:47:22 +00004765 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
Dan Gohman07c26ee2009-03-31 01:38:29 +00004766 else if (NumZeroBits >= RegSize-32)
Owen Anderson825b72b2009-08-11 20:47:22 +00004767 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004768
Bill Wendling4533cac2010-01-28 21:51:40 +00004769 if (FromVT != MVT::Other)
Dale Johannesen66978ee2009-01-31 02:22:37 +00004770 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004771 RegisterVT, P, DAG.getValueType(FromVT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004772 }
4773 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004774
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004775 Parts[i] = P;
4776 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004777
Bill Wendling3ea3c242009-12-22 02:10:19 +00004778 Values[Value] = getCopyFromParts(DAG, dl, Order, Parts.begin(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00004779 NumRegs, RegisterVT, ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004780 Part += NumRegs;
4781 Parts.clear();
4782 }
4783
Bill Wendling4533cac2010-01-28 21:51:40 +00004784 return DAG.getNode(ISD::MERGE_VALUES, dl,
4785 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4786 &Values[0], ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004787}
4788
4789/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004790/// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004791/// Chain/Flag as the input and updates them for the output Chain/Flag.
4792/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004793void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Bill Wendlingec72e322009-12-22 01:11:43 +00004794 unsigned Order, SDValue &Chain,
4795 SDValue *Flag) const {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004796 // Get the list of the values's legal parts.
4797 unsigned NumRegs = Regs.size();
4798 SmallVector<SDValue, 8> Parts(NumRegs);
4799 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00004800 EVT ValueVT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00004801 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
Owen Andersone50ed302009-08-10 22:56:29 +00004802 EVT RegisterVT = RegVTs[Value];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004803
Bill Wendling3ea3c242009-12-22 02:10:19 +00004804 getCopyToParts(DAG, dl, Order,
4805 Val.getValue(Val.getResNo() + Value),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004806 &Parts[Part], NumParts, RegisterVT);
4807 Part += NumParts;
4808 }
4809
4810 // Copy the parts into the registers.
4811 SmallVector<SDValue, 8> Chains(NumRegs);
4812 for (unsigned i = 0; i != NumRegs; ++i) {
4813 SDValue Part;
Bill Wendlingec72e322009-12-22 01:11:43 +00004814 if (Flag == 0) {
Dale Johannesena04b7572009-02-03 23:04:43 +00004815 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
Bill Wendlingec72e322009-12-22 01:11:43 +00004816 } else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004817 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004818 *Flag = Part.getValue(1);
4819 }
Bill Wendlingec72e322009-12-22 01:11:43 +00004820
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004821 Chains[i] = Part.getValue(0);
4822 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004823
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004824 if (NumRegs == 1 || Flag)
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004825 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004826 // flagged to it. That is the CopyToReg nodes and the user are considered
4827 // a single scheduling unit. If we create a TokenFactor and return it as
4828 // chain, then the TokenFactor is both a predecessor (operand) of the
4829 // user as well as a successor (the TF operands are flagged to the user).
4830 // c1, f1 = CopyToReg
4831 // c2, f2 = CopyToReg
4832 // c3 = TokenFactor c1, c2
4833 // ...
4834 // = op c3, ..., f2
4835 Chain = Chains[NumRegs-1];
4836 else
Owen Anderson825b72b2009-08-11 20:47:22 +00004837 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004838}
4839
4840/// AddInlineAsmOperands - Add this value to the specified inlineasm node
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004841/// operand list. This adds the code marker and includes the number of
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004842/// values added into it.
Evan Cheng697cbbf2009-03-20 18:03:34 +00004843void RegsForValue::AddInlineAsmOperands(unsigned Code,
4844 bool HasMatching,unsigned MatchingIdx,
Bill Wendling651ad132009-12-22 01:25:10 +00004845 SelectionDAG &DAG, unsigned Order,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004846 std::vector<SDValue> &Ops) const {
Evan Cheng697cbbf2009-03-20 18:03:34 +00004847 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
4848 unsigned Flag = Code | (Regs.size() << 3);
4849 if (HasMatching)
4850 Flag |= 0x80000000 | (MatchingIdx << 16);
Dale Johannesen99499332009-12-23 07:32:51 +00004851 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
Bill Wendling651ad132009-12-22 01:25:10 +00004852 Ops.push_back(Res);
4853
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004854 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
Owen Anderson23b9b192009-08-12 00:36:31 +00004855 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
Owen Andersone50ed302009-08-10 22:56:29 +00004856 EVT RegisterVT = RegVTs[Value];
Chris Lattner58f15c42008-10-17 16:21:11 +00004857 for (unsigned i = 0; i != NumRegs; ++i) {
4858 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Bill Wendling4533cac2010-01-28 21:51:40 +00004859 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner58f15c42008-10-17 16:21:11 +00004860 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004861 }
4862}
4863
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004864/// isAllocatableRegister - If the specified register is safe to allocate,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004865/// i.e. it isn't a stack pointer or some other special register, return the
4866/// register class for the register. Otherwise, return null.
4867static const TargetRegisterClass *
4868isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4869 const TargetLowering &TLI,
4870 const TargetRegisterInfo *TRI) {
Owen Anderson825b72b2009-08-11 20:47:22 +00004871 EVT FoundVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004872 const TargetRegisterClass *FoundRC = 0;
4873 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4874 E = TRI->regclass_end(); RCI != E; ++RCI) {
Owen Anderson825b72b2009-08-11 20:47:22 +00004875 EVT ThisVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004876
4877 const TargetRegisterClass *RC = *RCI;
Dan Gohmanf451cb82010-02-10 16:03:48 +00004878 // If none of the value types for this register class are valid, we
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004879 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4880 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4881 I != E; ++I) {
4882 if (TLI.isTypeLegal(*I)) {
4883 // If we have already found this register in a different register class,
4884 // choose the one with the largest VT specified. For example, on
4885 // PowerPC, we favor f64 register classes over f32.
Owen Anderson825b72b2009-08-11 20:47:22 +00004886 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004887 ThisVT = *I;
4888 break;
4889 }
4890 }
4891 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004892
Owen Anderson825b72b2009-08-11 20:47:22 +00004893 if (ThisVT == MVT::Other) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004894
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004895 // NOTE: This isn't ideal. In particular, this might allocate the
4896 // frame pointer in functions that need it (due to them not being taken
4897 // out of allocation, because a variable sized allocation hasn't been seen
4898 // yet). This is a slight code pessimization, but should still work.
4899 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4900 E = RC->allocation_order_end(MF); I != E; ++I)
4901 if (*I == Reg) {
4902 // We found a matching register class. Keep looking at others in case
4903 // we find one with larger registers that this physreg is also in.
4904 FoundRC = RC;
4905 FoundVT = ThisVT;
4906 break;
4907 }
4908 }
4909 return FoundRC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004910}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004911
4912
4913namespace llvm {
4914/// AsmOperandInfo - This contains information for each constraint that we are
4915/// lowering.
Cedric Venetaff9c272009-02-14 16:06:42 +00004916class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
Daniel Dunbarc0c3b9a2008-09-10 04:16:29 +00004917 public TargetLowering::AsmOperandInfo {
Cedric Venetaff9c272009-02-14 16:06:42 +00004918public:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004919 /// CallOperand - If this is the result output operand or a clobber
4920 /// this is null, otherwise it is the incoming operand to the CallInst.
4921 /// This gets modified as the asm is processed.
4922 SDValue CallOperand;
4923
4924 /// AssignedRegs - If this is a register or register class operand, this
4925 /// contains the set of register corresponding to the operand.
4926 RegsForValue AssignedRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004927
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004928 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4929 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4930 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004931
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004932 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4933 /// busy in OutputRegs/InputRegs.
4934 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004935 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004936 std::set<unsigned> &InputRegs,
4937 const TargetRegisterInfo &TRI) const {
4938 if (isOutReg) {
4939 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4940 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4941 }
4942 if (isInReg) {
4943 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4944 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4945 }
4946 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004947
Owen Andersone50ed302009-08-10 22:56:29 +00004948 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
Chris Lattner81249c92008-10-17 17:05:25 +00004949 /// corresponds to. If there is no Value* for this operand, it returns
Owen Anderson825b72b2009-08-11 20:47:22 +00004950 /// MVT::Other.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004951 EVT getCallOperandValEVT(LLVMContext &Context,
Owen Anderson1d0be152009-08-13 21:58:54 +00004952 const TargetLowering &TLI,
Chris Lattner81249c92008-10-17 17:05:25 +00004953 const TargetData *TD) const {
Owen Anderson825b72b2009-08-11 20:47:22 +00004954 if (CallOperandVal == 0) return MVT::Other;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004955
Chris Lattner81249c92008-10-17 17:05:25 +00004956 if (isa<BasicBlock>(CallOperandVal))
4957 return TLI.getPointerTy();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004958
Chris Lattner81249c92008-10-17 17:05:25 +00004959 const llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004960
Chris Lattner81249c92008-10-17 17:05:25 +00004961 // If this is an indirect operand, the operand is a pointer to the
4962 // accessed type.
Bob Wilsone261b0c2009-12-22 18:34:19 +00004963 if (isIndirect) {
4964 const llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
4965 if (!PtrTy)
4966 llvm_report_error("Indirect operand for inline asm not a pointer!");
4967 OpTy = PtrTy->getElementType();
4968 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004969
Chris Lattner81249c92008-10-17 17:05:25 +00004970 // If OpTy is not a single value, it may be a struct/union that we
4971 // can tile with integers.
4972 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4973 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4974 switch (BitSize) {
4975 default: break;
4976 case 1:
4977 case 8:
4978 case 16:
4979 case 32:
4980 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00004981 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00004982 OpTy = IntegerType::get(Context, BitSize);
Chris Lattner81249c92008-10-17 17:05:25 +00004983 break;
4984 }
4985 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004986
Chris Lattner81249c92008-10-17 17:05:25 +00004987 return TLI.getValueType(OpTy, true);
4988 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004989
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004990private:
4991 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4992 /// specified set.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004993 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004994 const TargetRegisterInfo &TRI) {
4995 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4996 Regs.insert(Reg);
4997 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4998 for (; *Aliases; ++Aliases)
4999 Regs.insert(*Aliases);
5000 }
5001};
5002} // end llvm namespace.
5003
5004
5005/// GetRegistersForValue - Assign registers (virtual or physical) for the
5006/// specified operand. We prefer to assign virtual registers, to allow the
Bob Wilson266d9452009-12-17 05:07:36 +00005007/// register allocator to handle the assignment process. However, if the asm
5008/// uses features that we can't model on machineinstrs, we have SDISel do the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005009/// allocation. This produces generally horrible, but correct, code.
5010///
5011/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005012/// Input and OutputRegs are the set of already allocated physical registers.
5013///
Dan Gohman2048b852009-11-23 18:04:58 +00005014void SelectionDAGBuilder::
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005015GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005016 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005017 std::set<unsigned> &InputRegs) {
Dan Gohman0d24bfb2009-08-15 02:06:22 +00005018 LLVMContext &Context = FuncInfo.Fn->getContext();
Owen Anderson23b9b192009-08-12 00:36:31 +00005019
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005020 // Compute whether this value requires an input register, an output register,
5021 // or both.
5022 bool isOutReg = false;
5023 bool isInReg = false;
5024 switch (OpInfo.Type) {
5025 case InlineAsm::isOutput:
5026 isOutReg = true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005027
5028 // If there is an input constraint that matches this, we need to reserve
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005029 // the input register so no other inputs allocate to it.
Chris Lattner6bdcda32008-10-17 16:47:46 +00005030 isInReg = OpInfo.hasMatchingInput();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005031 break;
5032 case InlineAsm::isInput:
5033 isInReg = true;
5034 isOutReg = false;
5035 break;
5036 case InlineAsm::isClobber:
5037 isOutReg = true;
5038 isInReg = true;
5039 break;
5040 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005041
5042
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005043 MachineFunction &MF = DAG.getMachineFunction();
5044 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005045
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005046 // If this is a constraint for a single physreg, or a constraint for a
5047 // register class, find it.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005048 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005049 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5050 OpInfo.ConstraintVT);
5051
5052 unsigned NumRegs = 1;
Owen Anderson825b72b2009-08-11 20:47:22 +00005053 if (OpInfo.ConstraintVT != MVT::Other) {
Chris Lattner01426e12008-10-21 00:45:36 +00005054 // If this is a FP input in an integer register (or visa versa) insert a bit
5055 // cast of the input value. More generally, handle any case where the input
5056 // value disagrees with the register class we plan to stick this in.
5057 if (OpInfo.Type == InlineAsm::isInput &&
5058 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
Owen Andersone50ed302009-08-10 22:56:29 +00005059 // Try to convert to the first EVT that the reg class contains. If the
Chris Lattner01426e12008-10-21 00:45:36 +00005060 // types are identical size, use a bitcast to convert (e.g. two differing
5061 // vector types).
Owen Andersone50ed302009-08-10 22:56:29 +00005062 EVT RegVT = *PhysReg.second->vt_begin();
Chris Lattner01426e12008-10-21 00:45:36 +00005063 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005064 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005065 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00005066 OpInfo.ConstraintVT = RegVT;
5067 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5068 // If the input is a FP value and we want it in FP registers, do a
5069 // bitcast to the corresponding integer type. This turns an f64 value
5070 // into i64, which can be passed with two i32 values on a 32-bit
5071 // machine.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005072 RegVT = EVT::getIntegerVT(Context,
Owen Anderson23b9b192009-08-12 00:36:31 +00005073 OpInfo.ConstraintVT.getSizeInBits());
Dale Johannesen66978ee2009-01-31 02:22:37 +00005074 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005075 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00005076 OpInfo.ConstraintVT = RegVT;
5077 }
5078 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005079
Owen Anderson23b9b192009-08-12 00:36:31 +00005080 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00005081 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005082
Owen Andersone50ed302009-08-10 22:56:29 +00005083 EVT RegVT;
5084 EVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005085
5086 // If this is a constraint for a specific physical register, like {r17},
5087 // assign it now.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005088 if (unsigned AssignedReg = PhysReg.first) {
5089 const TargetRegisterClass *RC = PhysReg.second;
Owen Anderson825b72b2009-08-11 20:47:22 +00005090 if (OpInfo.ConstraintVT == MVT::Other)
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005091 ValueVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005092
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005093 // Get the actual register value type. This is important, because the user
5094 // may have asked for (e.g.) the AX register in i32 type. We need to
5095 // remember that AX is actually i16 to get the right extension.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005096 RegVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005097
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005098 // This is a explicit reference to a physical register.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005099 Regs.push_back(AssignedReg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005100
5101 // If this is an expanded reference, add the rest of the regs to Regs.
5102 if (NumRegs != 1) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005103 TargetRegisterClass::iterator I = RC->begin();
5104 for (; *I != AssignedReg; ++I)
5105 assert(I != RC->end() && "Didn't find reg!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005106
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005107 // Already added the first reg.
5108 --NumRegs; ++I;
5109 for (; NumRegs; --NumRegs, ++I) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005110 assert(I != RC->end() && "Ran out of registers to allocate!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005111 Regs.push_back(*I);
5112 }
5113 }
Bill Wendling651ad132009-12-22 01:25:10 +00005114
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005115 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5116 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5117 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5118 return;
5119 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005120
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005121 // Otherwise, if this was a reference to an LLVM register class, create vregs
5122 // for this reference.
Chris Lattnerb3b44842009-03-24 15:25:07 +00005123 if (const TargetRegisterClass *RC = PhysReg.second) {
5124 RegVT = *RC->vt_begin();
Owen Anderson825b72b2009-08-11 20:47:22 +00005125 if (OpInfo.ConstraintVT == MVT::Other)
Evan Chengfb112882009-03-23 08:01:15 +00005126 ValueVT = RegVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005127
Evan Chengfb112882009-03-23 08:01:15 +00005128 // Create the appropriate number of virtual registers.
5129 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5130 for (; NumRegs; --NumRegs)
Chris Lattnerb3b44842009-03-24 15:25:07 +00005131 Regs.push_back(RegInfo.createVirtualRegister(RC));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005132
Evan Chengfb112882009-03-23 08:01:15 +00005133 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5134 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005135 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005136
Chris Lattnerfc9d1612009-03-24 15:22:11 +00005137 // This is a reference to a register class that doesn't directly correspond
5138 // to an LLVM register class. Allocate NumRegs consecutive, available,
5139 // registers from the class.
5140 std::vector<unsigned> RegClassRegs
5141 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5142 OpInfo.ConstraintVT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005143
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005144 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5145 unsigned NumAllocated = 0;
5146 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5147 unsigned Reg = RegClassRegs[i];
5148 // See if this register is available.
5149 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5150 (isInReg && InputRegs.count(Reg))) { // Already used.
5151 // Make sure we find consecutive registers.
5152 NumAllocated = 0;
5153 continue;
5154 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005155
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005156 // Check to see if this register is allocatable (i.e. don't give out the
5157 // stack pointer).
Chris Lattnerfc9d1612009-03-24 15:22:11 +00005158 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5159 if (!RC) { // Couldn't allocate this register.
5160 // Reset NumAllocated to make sure we return consecutive registers.
5161 NumAllocated = 0;
5162 continue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005163 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005164
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005165 // Okay, this register is good, we can use it.
5166 ++NumAllocated;
5167
5168 // If we allocated enough consecutive registers, succeed.
5169 if (NumAllocated == NumRegs) {
5170 unsigned RegStart = (i-NumAllocated)+1;
5171 unsigned RegEnd = i+1;
5172 // Mark all of the allocated registers used.
5173 for (unsigned i = RegStart; i != RegEnd; ++i)
5174 Regs.push_back(RegClassRegs[i]);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005175
5176 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005177 OpInfo.ConstraintVT);
5178 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5179 return;
5180 }
5181 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005182
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005183 // Otherwise, we couldn't allocate enough registers for this.
5184}
5185
Evan Chengda43bcf2008-09-24 00:05:32 +00005186/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5187/// processed uses a memory 'm' constraint.
5188static bool
5189hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
Dan Gohmane9530ec2009-01-15 16:58:17 +00005190 const TargetLowering &TLI) {
Evan Chengda43bcf2008-09-24 00:05:32 +00005191 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5192 InlineAsm::ConstraintInfo &CI = CInfos[i];
5193 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5194 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5195 if (CType == TargetLowering::C_Memory)
5196 return true;
5197 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005198
Chris Lattner6c147292009-04-30 00:48:50 +00005199 // Indirect operand accesses access memory.
5200 if (CI.isIndirect)
5201 return true;
Evan Chengda43bcf2008-09-24 00:05:32 +00005202 }
5203
5204 return false;
5205}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005206
5207/// visitInlineAsm - Handle a call to an InlineAsm object.
5208///
Dan Gohman2048b852009-11-23 18:04:58 +00005209void SelectionDAGBuilder::visitInlineAsm(CallSite CS) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005210 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5211
5212 /// ConstraintOperands - Information about all of the constraints.
5213 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005214
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005215 std::set<unsigned> OutputRegs, InputRegs;
5216
5217 // Do a prepass over the constraints, canonicalizing them, and building up the
5218 // ConstraintOperands list.
5219 std::vector<InlineAsm::ConstraintInfo>
5220 ConstraintInfos = IA->ParseConstraints();
5221
Evan Chengda43bcf2008-09-24 00:05:32 +00005222 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005223
Chris Lattner6c147292009-04-30 00:48:50 +00005224 SDValue Chain, Flag;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005225
Chris Lattner6c147292009-04-30 00:48:50 +00005226 // We won't need to flush pending loads if this asm doesn't touch
5227 // memory and is nonvolatile.
5228 if (hasMemory || IA->hasSideEffects())
Dale Johannesen97d14fc2009-04-18 00:09:40 +00005229 Chain = getRoot();
Chris Lattner6c147292009-04-30 00:48:50 +00005230 else
5231 Chain = DAG.getRoot();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005232
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005233 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5234 unsigned ResNo = 0; // ResNo - The result number of the next output.
5235 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5236 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5237 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005238
Owen Anderson825b72b2009-08-11 20:47:22 +00005239 EVT OpVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005240
5241 // Compute the value type for each operand.
5242 switch (OpInfo.Type) {
5243 case InlineAsm::isOutput:
5244 // Indirect outputs just consume an argument.
5245 if (OpInfo.isIndirect) {
5246 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5247 break;
5248 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005249
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005250 // The return value of the call is this value. As such, there is no
5251 // corresponding argument.
Benjamin Kramerf0127052010-01-05 13:12:22 +00005252 assert(!CS.getType()->isVoidTy() &&
Owen Anderson1d0be152009-08-13 21:58:54 +00005253 "Bad inline asm!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005254 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5255 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5256 } else {
5257 assert(ResNo == 0 && "Asm only has one result!");
5258 OpVT = TLI.getValueType(CS.getType());
5259 }
5260 ++ResNo;
5261 break;
5262 case InlineAsm::isInput:
5263 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5264 break;
5265 case InlineAsm::isClobber:
5266 // Nothing to do.
5267 break;
5268 }
5269
5270 // If this is an input or an indirect output, process the call argument.
5271 // BasicBlocks are labels, currently appearing only in asm's.
5272 if (OpInfo.CallOperandVal) {
Dale Johannesen5339c552009-07-20 23:27:39 +00005273 // Strip bitcasts, if any. This mostly comes up for functions.
Dale Johannesen76711242009-08-06 22:45:51 +00005274 OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts();
5275
Chris Lattner81249c92008-10-17 17:05:25 +00005276 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005277 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00005278 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005279 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005280 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005281
Owen Anderson1d0be152009-08-13 21:58:54 +00005282 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005283 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005284
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005285 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005286 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005287
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005288 // Second pass over the constraints: compute which constraint option to use
5289 // and assign registers to constraints that want a specific physreg.
5290 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5291 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005292
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005293 // If this is an output operand with a matching input operand, look up the
Evan Cheng09dc9c02008-12-16 18:21:39 +00005294 // matching input. If their types mismatch, e.g. one is an integer, the
5295 // other is floating point, or their sizes are different, flag it as an
5296 // error.
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005297 if (OpInfo.hasMatchingInput()) {
5298 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5299 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Evan Cheng09dc9c02008-12-16 18:21:39 +00005300 if ((OpInfo.ConstraintVT.isInteger() !=
5301 Input.ConstraintVT.isInteger()) ||
5302 (OpInfo.ConstraintVT.getSizeInBits() !=
5303 Input.ConstraintVT.getSizeInBits())) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005304 llvm_report_error("Unsupported asm: input constraint"
Torok Edwin7d696d82009-07-11 13:10:19 +00005305 " with a matching output constraint of incompatible"
5306 " type!");
Evan Cheng09dc9c02008-12-16 18:21:39 +00005307 }
5308 Input.ConstraintVT = OpInfo.ConstraintVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005309 }
5310 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005311
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005312 // Compute the constraint code and ConstraintType to use.
Evan Chengda43bcf2008-09-24 00:05:32 +00005313 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005314
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005315 // If this is a memory input, and if the operand is not indirect, do what we
5316 // need to to provide an address for the memory input.
5317 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5318 !OpInfo.isIndirect) {
5319 assert(OpInfo.Type == InlineAsm::isInput &&
5320 "Can only indirectify direct input operands!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005321
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005322 // Memory operands really want the address of the value. If we don't have
5323 // an indirect input, put it in the constpool if we can, otherwise spill
5324 // it to a stack slot.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005325
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005326 // If the operand is a float, integer, or vector constant, spill to a
5327 // constant pool entry to get its address.
5328 Value *OpVal = OpInfo.CallOperandVal;
5329 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5330 isa<ConstantVector>(OpVal)) {
5331 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5332 TLI.getPointerTy());
5333 } else {
5334 // Otherwise, create a stack slot and emit a store to it before the
5335 // asm.
5336 const Type *Ty = OpVal->getType();
Duncan Sands777d2302009-05-09 07:06:46 +00005337 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005338 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5339 MachineFunction &MF = DAG.getMachineFunction();
David Greene3f2bf852009-11-12 20:49:22 +00005340 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005341 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Dale Johannesen66978ee2009-01-31 02:22:37 +00005342 Chain = DAG.getStore(Chain, getCurDebugLoc(),
David Greene1e559442010-02-15 17:00:31 +00005343 OpInfo.CallOperand, StackSlot, NULL, 0,
5344 false, false, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005345 OpInfo.CallOperand = StackSlot;
5346 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005347
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005348 // There is no longer a Value* corresponding to this operand.
5349 OpInfo.CallOperandVal = 0;
Bill Wendling651ad132009-12-22 01:25:10 +00005350
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005351 // It is now an indirect operand.
5352 OpInfo.isIndirect = true;
5353 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005354
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005355 // If this constraint is for a specific register, allocate it before
5356 // anything else.
5357 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005358 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005359 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005360
Bill Wendling651ad132009-12-22 01:25:10 +00005361 ConstraintInfos.clear();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005362
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005363 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00005364 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005365 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5366 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005367
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005368 // C_Register operands have already been allocated, Other/Memory don't need
5369 // to be.
5370 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005371 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005372 }
5373
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005374 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5375 std::vector<SDValue> AsmNodeOperands;
5376 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5377 AsmNodeOperands.push_back(
Dan Gohmanf2d7fb32010-01-04 21:00:54 +00005378 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
5379 TLI.getPointerTy()));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005380
5381
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005382 // Loop over all of the inputs, copying the operand values into the
5383 // appropriate registers and processing the output regs.
5384 RegsForValue RetValRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005385
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005386 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5387 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005388
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005389 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5390 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5391
5392 switch (OpInfo.Type) {
5393 case InlineAsm::isOutput: {
5394 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5395 OpInfo.ConstraintType != TargetLowering::C_Register) {
5396 // Memory output, or 'other' output (e.g. 'X' constraint).
5397 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5398
5399 // Add information to the INLINEASM node to know about this output.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005400 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5401 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005402 TLI.getPointerTy()));
5403 AsmNodeOperands.push_back(OpInfo.CallOperand);
5404 break;
5405 }
5406
5407 // Otherwise, this is a register or register class output.
5408
5409 // Copy the output from the appropriate register. Find a register that
5410 // we can use.
5411 if (OpInfo.AssignedRegs.Regs.empty()) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005412 llvm_report_error("Couldn't allocate output reg for"
Torok Edwin7d696d82009-07-11 13:10:19 +00005413 " constraint '" + OpInfo.ConstraintCode + "'!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005414 }
5415
5416 // If this is an indirect operand, store through the pointer after the
5417 // asm.
5418 if (OpInfo.isIndirect) {
5419 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5420 OpInfo.CallOperandVal));
5421 } else {
5422 // This is the result value of the call.
Benjamin Kramerf0127052010-01-05 13:12:22 +00005423 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005424 // Concatenate this output onto the outputs list.
5425 RetValRegs.append(OpInfo.AssignedRegs);
5426 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005427
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005428 // Add information to the INLINEASM node to know that this register is
5429 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00005430 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5431 6 /* EARLYCLOBBER REGDEF */ :
5432 2 /* REGDEF */ ,
Evan Chengfb112882009-03-23 08:01:15 +00005433 false,
5434 0,
Bill Wendling651ad132009-12-22 01:25:10 +00005435 DAG, SDNodeOrder,
5436 AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005437 break;
5438 }
5439 case InlineAsm::isInput: {
5440 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005441
Chris Lattner6bdcda32008-10-17 16:47:46 +00005442 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005443 // If this is required to match an output register we have already set,
5444 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00005445 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005446
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005447 // Scan until we find the definition we already emitted of this operand.
5448 // When we find it, create a RegsForValue operand.
5449 unsigned CurOp = 2; // The first operand.
5450 for (; OperandNo; --OperandNo) {
5451 // Advance to the next operand.
Evan Cheng697cbbf2009-03-20 18:03:34 +00005452 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005453 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005454 assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5455 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5456 (OpFlag & 7) == 4 /*MEM*/) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005457 "Skipped past definitions?");
Evan Cheng697cbbf2009-03-20 18:03:34 +00005458 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005459 }
5460
Evan Cheng697cbbf2009-03-20 18:03:34 +00005461 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005462 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005463 if ((OpFlag & 7) == 2 /*REGDEF*/
5464 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5465 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
Dan Gohman15480bd2009-06-15 22:32:41 +00005466 if (OpInfo.isIndirect) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005467 llvm_report_error("Don't know how to handle tied indirect "
Torok Edwin7d696d82009-07-11 13:10:19 +00005468 "register inputs yet!");
Dan Gohman15480bd2009-06-15 22:32:41 +00005469 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005470 RegsForValue MatchedRegs;
5471 MatchedRegs.TLI = &TLI;
5472 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
Owen Andersone50ed302009-08-10 22:56:29 +00005473 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
Evan Chengfb112882009-03-23 08:01:15 +00005474 MatchedRegs.RegVTs.push_back(RegVT);
5475 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005476 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
Evan Chengfb112882009-03-23 08:01:15 +00005477 i != e; ++i)
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005478 MatchedRegs.Regs.push_back
5479 (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005480
5481 // Use the produced MatchedRegs object to
Dale Johannesen66978ee2009-01-31 02:22:37 +00005482 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
Bill Wendlingec72e322009-12-22 01:11:43 +00005483 SDNodeOrder, Chain, &Flag);
Evan Chengfb112882009-03-23 08:01:15 +00005484 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5485 true, OpInfo.getMatchedOperand(),
Bill Wendling651ad132009-12-22 01:25:10 +00005486 DAG, SDNodeOrder, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005487 break;
5488 } else {
Evan Cheng697cbbf2009-03-20 18:03:34 +00005489 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5490 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5491 "Unexpected number of operands");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005492 // Add information to the INLINEASM node to know about this input.
Evan Chengfb112882009-03-23 08:01:15 +00005493 // See InlineAsm.h isUseOperandTiedToDef.
5494 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
Evan Cheng697cbbf2009-03-20 18:03:34 +00005495 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005496 TLI.getPointerTy()));
5497 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5498 break;
5499 }
5500 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005501
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005502 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005503 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005504 "Don't know how to handle indirect other inputs yet!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005505
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005506 std::vector<SDValue> Ops;
5507 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Chengda43bcf2008-09-24 00:05:32 +00005508 hasMemory, Ops, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005509 if (Ops.empty()) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005510 llvm_report_error("Invalid operand for inline asm"
Torok Edwin7d696d82009-07-11 13:10:19 +00005511 " constraint '" + OpInfo.ConstraintCode + "'!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005512 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005513
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005514 // Add information to the INLINEASM node to know about this input.
5515 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005516 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005517 TLI.getPointerTy()));
5518 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5519 break;
5520 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5521 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5522 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5523 "Memory operands expect pointer values");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005524
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005525 // Add information to the INLINEASM node to know about this input.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005526 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5527 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005528 TLI.getPointerTy()));
5529 AsmNodeOperands.push_back(InOperandVal);
5530 break;
5531 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005532
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005533 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5534 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5535 "Unknown constraint type!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005536 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005537 "Don't know how to handle indirect register inputs yet!");
5538
5539 // Copy the input into the appropriate registers.
Evan Cheng8112b532010-02-10 01:21:02 +00005540 if (OpInfo.AssignedRegs.Regs.empty() ||
5541 !OpInfo.AssignedRegs.areValueTypesLegal()) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005542 llvm_report_error("Couldn't allocate input reg for"
Torok Edwin7d696d82009-07-11 13:10:19 +00005543 " constraint '"+ OpInfo.ConstraintCode +"'!");
Evan Chengaa765b82008-09-25 00:14:04 +00005544 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005545
Dale Johannesen66978ee2009-01-31 02:22:37 +00005546 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
Bill Wendlingec72e322009-12-22 01:11:43 +00005547 SDNodeOrder, Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005548
Evan Cheng697cbbf2009-03-20 18:03:34 +00005549 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
Bill Wendling651ad132009-12-22 01:25:10 +00005550 DAG, SDNodeOrder,
5551 AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005552 break;
5553 }
5554 case InlineAsm::isClobber: {
5555 // Add the clobbered value to the operand list, so that the register
5556 // allocator is aware that the physreg got clobbered.
5557 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesen91aac102008-09-17 21:13:11 +00005558 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
Bill Wendling651ad132009-12-22 01:25:10 +00005559 false, 0, DAG, SDNodeOrder,
5560 AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005561 break;
5562 }
5563 }
5564 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005565
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005566 // Finish up input operands.
5567 AsmNodeOperands[0] = Chain;
5568 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005569
Dale Johannesen66978ee2009-01-31 02:22:37 +00005570 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00005571 DAG.getVTList(MVT::Other, MVT::Flag),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005572 &AsmNodeOperands[0], AsmNodeOperands.size());
5573 Flag = Chain.getValue(1);
5574
5575 // If this asm returns a register value, copy the result from that register
5576 // and set it as the value of the call.
5577 if (!RetValRegs.Regs.empty()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00005578 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
Bill Wendlingec72e322009-12-22 01:11:43 +00005579 SDNodeOrder, Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005580
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005581 // FIXME: Why don't we do this for inline asms with MRVs?
5582 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
Owen Andersone50ed302009-08-10 22:56:29 +00005583 EVT ResultType = TLI.getValueType(CS.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005584
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005585 // If any of the results of the inline asm is a vector, it may have the
5586 // wrong width/num elts. This can happen for register classes that can
5587 // contain multiple different value types. The preg or vreg allocated may
5588 // not have the same VT as was expected. Convert it to the right type
5589 // with bit_convert.
5590 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005591 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005592 ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005593
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005594 } else if (ResultType != Val.getValueType() &&
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005595 ResultType.isInteger() && Val.getValueType().isInteger()) {
5596 // If a result value was tied to an input value, the computed result may
5597 // have a wider width than the expected result. Extract the relevant
5598 // portion.
Dale Johannesen66978ee2009-01-31 02:22:37 +00005599 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005600 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005601
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005602 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00005603 }
Dan Gohman95915732008-10-18 01:03:45 +00005604
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005605 setValue(CS.getInstruction(), Val);
Dale Johannesenec65a7d2009-04-14 00:56:56 +00005606 // Don't need to use this as a chain in this case.
5607 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5608 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005609 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005610
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005611 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005612
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005613 // Process indirect outputs, first output all of the flagged copies out of
5614 // physregs.
5615 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5616 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5617 Value *Ptr = IndirectStoresToEmit[i].second;
Dale Johannesen66978ee2009-01-31 02:22:37 +00005618 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
Bill Wendlingec72e322009-12-22 01:11:43 +00005619 SDNodeOrder, Chain, &Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005620 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6c147292009-04-30 00:48:50 +00005621
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005622 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005623
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005624 // Emit the non-flagged stores from the physregs.
5625 SmallVector<SDValue, 8> OutChains;
Bill Wendling651ad132009-12-22 01:25:10 +00005626 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
5627 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
5628 StoresToEmit[i].first,
5629 getValue(StoresToEmit[i].second),
David Greene1e559442010-02-15 17:00:31 +00005630 StoresToEmit[i].second, 0,
5631 false, false, 0);
Bill Wendling651ad132009-12-22 01:25:10 +00005632 OutChains.push_back(Val);
Bill Wendling651ad132009-12-22 01:25:10 +00005633 }
5634
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005635 if (!OutChains.empty())
Owen Anderson825b72b2009-08-11 20:47:22 +00005636 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005637 &OutChains[0], OutChains.size());
Bill Wendling651ad132009-12-22 01:25:10 +00005638
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005639 DAG.setRoot(Chain);
5640}
5641
Dan Gohman2048b852009-11-23 18:04:58 +00005642void SelectionDAGBuilder::visitVAStart(CallInst &I) {
Bill Wendlingc1d3c942009-12-23 00:44:51 +00005643 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
5644 MVT::Other, getRoot(),
5645 getValue(I.getOperand(1)),
5646 DAG.getSrcValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005647}
5648
Dan Gohman2048b852009-11-23 18:04:58 +00005649void SelectionDAGBuilder::visitVAArg(VAArgInst &I) {
Dale Johannesena04b7572009-02-03 23:04:43 +00005650 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5651 getRoot(), getValue(I.getOperand(0)),
5652 DAG.getSrcValue(I.getOperand(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005653 setValue(&I, V);
5654 DAG.setRoot(V.getValue(1));
5655}
5656
Dan Gohman2048b852009-11-23 18:04:58 +00005657void SelectionDAGBuilder::visitVAEnd(CallInst &I) {
Bill Wendlingc1d3c942009-12-23 00:44:51 +00005658 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
5659 MVT::Other, getRoot(),
5660 getValue(I.getOperand(1)),
5661 DAG.getSrcValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005662}
5663
Dan Gohman2048b852009-11-23 18:04:58 +00005664void SelectionDAGBuilder::visitVACopy(CallInst &I) {
Bill Wendlingc1d3c942009-12-23 00:44:51 +00005665 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
5666 MVT::Other, getRoot(),
5667 getValue(I.getOperand(1)),
5668 getValue(I.getOperand(2)),
5669 DAG.getSrcValue(I.getOperand(1)),
5670 DAG.getSrcValue(I.getOperand(2))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005671}
5672
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005673/// TargetLowering::LowerCallTo - This is the default LowerCallTo
Dan Gohman98ca4f22009-08-05 01:29:28 +00005674/// implementation, which just calls LowerCall.
5675/// FIXME: When all targets are
5676/// migrated to using LowerCall, this hook should be integrated into SDISel.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005677std::pair<SDValue, SDValue>
5678TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5679 bool RetSExt, bool RetZExt, bool isVarArg,
Tilmann Scheller6b61cd12009-07-03 06:44:53 +00005680 bool isInreg, unsigned NumFixedArgs,
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00005681 CallingConv::ID CallConv, bool isTailCall,
Dan Gohman98ca4f22009-08-05 01:29:28 +00005682 bool isReturnValueUsed,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005683 SDValue Callee,
Bill Wendling3ea3c242009-12-22 02:10:19 +00005684 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl,
5685 unsigned Order) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005686 // Handle all of the outgoing arguments.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005687 SmallVector<ISD::OutputArg, 32> Outs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005688 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Owen Andersone50ed302009-08-10 22:56:29 +00005689 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005690 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5691 for (unsigned Value = 0, NumValues = ValueVTs.size();
5692 Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00005693 EVT VT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00005694 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005695 SDValue Op = SDValue(Args[i].Node.getNode(),
5696 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005697 ISD::ArgFlagsTy Flags;
5698 unsigned OriginalAlignment =
5699 getTargetData()->getABITypeAlignment(ArgTy);
5700
5701 if (Args[i].isZExt)
5702 Flags.setZExt();
5703 if (Args[i].isSExt)
5704 Flags.setSExt();
5705 if (Args[i].isInReg)
5706 Flags.setInReg();
5707 if (Args[i].isSRet)
5708 Flags.setSRet();
5709 if (Args[i].isByVal) {
5710 Flags.setByVal();
5711 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5712 const Type *ElementTy = Ty->getElementType();
5713 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sands777d2302009-05-09 07:06:46 +00005714 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005715 // For ByVal, alignment should come from FE. BE will guess if this
5716 // info is not there but there are cases it cannot get right.
5717 if (Args[i].Alignment)
5718 FrameAlign = Args[i].Alignment;
5719 Flags.setByValAlign(FrameAlign);
5720 Flags.setByValSize(FrameSize);
5721 }
5722 if (Args[i].isNest)
5723 Flags.setNest();
5724 Flags.setOrigAlign(OriginalAlignment);
5725
Owen Anderson23b9b192009-08-12 00:36:31 +00005726 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
5727 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005728 SmallVector<SDValue, 4> Parts(NumParts);
5729 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5730
5731 if (Args[i].isSExt)
5732 ExtendKind = ISD::SIGN_EXTEND;
5733 else if (Args[i].isZExt)
5734 ExtendKind = ISD::ZERO_EXTEND;
5735
Bill Wendling3ea3c242009-12-22 02:10:19 +00005736 getCopyToParts(DAG, dl, Order, Op, &Parts[0], NumParts,
5737 PartVT, ExtendKind);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005738
Dan Gohman98ca4f22009-08-05 01:29:28 +00005739 for (unsigned j = 0; j != NumParts; ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005740 // if it isn't first piece, alignment must be 1
Dan Gohman98ca4f22009-08-05 01:29:28 +00005741 ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs);
5742 if (NumParts > 1 && j == 0)
5743 MyFlags.Flags.setSplit();
5744 else if (j != 0)
5745 MyFlags.Flags.setOrigAlign(1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005746
Dan Gohman98ca4f22009-08-05 01:29:28 +00005747 Outs.push_back(MyFlags);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005748 }
5749 }
5750 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005751
Dan Gohman98ca4f22009-08-05 01:29:28 +00005752 // Handle the incoming return values from the call.
5753 SmallVector<ISD::InputArg, 32> Ins;
Owen Andersone50ed302009-08-10 22:56:29 +00005754 SmallVector<EVT, 4> RetTys;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005755 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005756 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Owen Andersone50ed302009-08-10 22:56:29 +00005757 EVT VT = RetTys[I];
Owen Anderson23b9b192009-08-12 00:36:31 +00005758 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5759 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005760 for (unsigned i = 0; i != NumRegs; ++i) {
5761 ISD::InputArg MyFlags;
5762 MyFlags.VT = RegisterVT;
5763 MyFlags.Used = isReturnValueUsed;
5764 if (RetSExt)
5765 MyFlags.Flags.setSExt();
5766 if (RetZExt)
5767 MyFlags.Flags.setZExt();
5768 if (isInreg)
5769 MyFlags.Flags.setInReg();
5770 Ins.push_back(MyFlags);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005771 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005772 }
5773
Dan Gohman98ca4f22009-08-05 01:29:28 +00005774 SmallVector<SDValue, 4> InVals;
Evan Cheng022d9e12010-02-02 23:55:14 +00005775 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
Dan Gohman98ca4f22009-08-05 01:29:28 +00005776 Outs, Ins, dl, DAG, InVals);
Dan Gohman5e866062009-08-06 15:37:27 +00005777
5778 // Verify that the target's LowerCall behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +00005779 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00005780 "LowerCall didn't return a valid chain!");
5781 assert((!isTailCall || InVals.empty()) &&
5782 "LowerCall emitted a return value for a tail call!");
5783 assert((isTailCall || InVals.size() == Ins.size()) &&
5784 "LowerCall didn't emit the correct number of values!");
5785 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5786 assert(InVals[i].getNode() &&
5787 "LowerCall emitted a null value!");
5788 assert(Ins[i].VT == InVals[i].getValueType() &&
5789 "LowerCall emitted a value with the wrong type!");
5790 });
Dan Gohman98ca4f22009-08-05 01:29:28 +00005791
5792 // For a tail call, the return value is merely live-out and there aren't
5793 // any nodes in the DAG representing it. Return a special value to
5794 // indicate that a tail call has been emitted and no more Instructions
5795 // should be processed in the current block.
5796 if (isTailCall) {
5797 DAG.setRoot(Chain);
5798 return std::make_pair(SDValue(), SDValue());
5799 }
5800
5801 // Collect the legal value parts into potentially illegal values
5802 // that correspond to the original function's return values.
5803 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5804 if (RetSExt)
5805 AssertOp = ISD::AssertSext;
5806 else if (RetZExt)
5807 AssertOp = ISD::AssertZext;
5808 SmallVector<SDValue, 4> ReturnValues;
5809 unsigned CurReg = 0;
5810 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Owen Andersone50ed302009-08-10 22:56:29 +00005811 EVT VT = RetTys[I];
Owen Anderson23b9b192009-08-12 00:36:31 +00005812 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5813 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005814
Bill Wendling4533cac2010-01-28 21:51:40 +00005815 ReturnValues.push_back(getCopyFromParts(DAG, dl, Order, &InVals[CurReg],
5816 NumRegs, RegisterVT, VT,
5817 AssertOp));
Dan Gohman98ca4f22009-08-05 01:29:28 +00005818 CurReg += NumRegs;
5819 }
5820
5821 // For a function returning void, there is no return value. We can't create
5822 // such a node, so we just return a null return value in that case. In
5823 // that case, nothing will actualy look at the value.
5824 if (ReturnValues.empty())
5825 return std::make_pair(SDValue(), Chain);
5826
5827 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
5828 DAG.getVTList(&RetTys[0], RetTys.size()),
5829 &ReturnValues[0], ReturnValues.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005830 return std::make_pair(Res, Chain);
5831}
5832
Duncan Sands9fbc7e22009-01-21 09:00:29 +00005833void TargetLowering::LowerOperationWrapper(SDNode *N,
5834 SmallVectorImpl<SDValue> &Results,
5835 SelectionDAG &DAG) {
5836 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptabb326bb2009-01-21 04:48:39 +00005837 if (Res.getNode())
5838 Results.push_back(Res);
5839}
5840
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005841SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005842 llvm_unreachable("LowerOperation not implemented for this target!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005843 return SDValue();
5844}
5845
Dan Gohman2048b852009-11-23 18:04:58 +00005846void SelectionDAGBuilder::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005847 SDValue Op = getValue(V);
5848 assert((Op.getOpcode() != ISD::CopyFromReg ||
5849 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5850 "Copy from a reg to the same reg!");
5851 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5852
Owen Anderson23b9b192009-08-12 00:36:31 +00005853 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005854 SDValue Chain = DAG.getEntryNode();
Bill Wendlingec72e322009-12-22 01:11:43 +00005855 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), SDNodeOrder, Chain, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005856 PendingExports.push_back(Chain);
5857}
5858
5859#include "llvm/CodeGen/SelectionDAGISel.h"
5860
Dan Gohman8c2b5252009-10-30 01:27:03 +00005861void SelectionDAGISel::LowerArguments(BasicBlock *LLVMBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005862 // If this is the entry block, emit arguments.
5863 Function &F = *LLVMBB->getParent();
Dan Gohman2048b852009-11-23 18:04:58 +00005864 SelectionDAG &DAG = SDB->DAG;
Dan Gohman98ca4f22009-08-05 01:29:28 +00005865 SDValue OldRoot = DAG.getRoot();
Dan Gohman2048b852009-11-23 18:04:58 +00005866 DebugLoc dl = SDB->getCurDebugLoc();
Dan Gohman98ca4f22009-08-05 01:29:28 +00005867 const TargetData *TD = TLI.getTargetData();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005868 SmallVector<ISD::InputArg, 16> Ins;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005869
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +00005870 // Check whether the function can return without sret-demotion.
5871 SmallVector<EVT, 4> OutVTs;
5872 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005873 getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005874 OutVTs, OutsFlags, TLI);
5875 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
5876
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005877 FLI.CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(), F.isVarArg(),
Bill Wendling3ea3c242009-12-22 02:10:19 +00005878 OutVTs, OutsFlags, DAG);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005879 if (!FLI.CanLowerReturn) {
5880 // Put in an sret pointer parameter before all the other parameters.
5881 SmallVector<EVT, 1> ValueVTs;
5882 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5883
5884 // NOTE: Assuming that a pointer will never break down to more than one VT
5885 // or one register.
5886 ISD::ArgFlagsTy Flags;
5887 Flags.setSRet();
5888 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), ValueVTs[0]);
5889 ISD::InputArg RetArg(Flags, RegisterVT, true);
5890 Ins.push_back(RetArg);
5891 }
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +00005892
Dan Gohman98ca4f22009-08-05 01:29:28 +00005893 // Set up the incoming argument description vector.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005894 unsigned Idx = 1;
5895 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5896 I != E; ++I, ++Idx) {
Owen Andersone50ed302009-08-10 22:56:29 +00005897 SmallVector<EVT, 4> ValueVTs;
Dan Gohman98ca4f22009-08-05 01:29:28 +00005898 ComputeValueVTs(TLI, I->getType(), ValueVTs);
5899 bool isArgValueUsed = !I->use_empty();
5900 for (unsigned Value = 0, NumValues = ValueVTs.size();
5901 Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00005902 EVT VT = ValueVTs[Value];
Owen Anderson1d0be152009-08-13 21:58:54 +00005903 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Dan Gohman98ca4f22009-08-05 01:29:28 +00005904 ISD::ArgFlagsTy Flags;
5905 unsigned OriginalAlignment =
5906 TD->getABITypeAlignment(ArgTy);
5907
5908 if (F.paramHasAttr(Idx, Attribute::ZExt))
5909 Flags.setZExt();
5910 if (F.paramHasAttr(Idx, Attribute::SExt))
5911 Flags.setSExt();
5912 if (F.paramHasAttr(Idx, Attribute::InReg))
5913 Flags.setInReg();
5914 if (F.paramHasAttr(Idx, Attribute::StructRet))
5915 Flags.setSRet();
5916 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
5917 Flags.setByVal();
5918 const PointerType *Ty = cast<PointerType>(I->getType());
5919 const Type *ElementTy = Ty->getElementType();
5920 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
5921 unsigned FrameSize = TD->getTypeAllocSize(ElementTy);
5922 // For ByVal, alignment should be passed from FE. BE will guess if
5923 // this info is not there but there are cases it cannot get right.
5924 if (F.getParamAlignment(Idx))
5925 FrameAlign = F.getParamAlignment(Idx);
5926 Flags.setByValAlign(FrameAlign);
5927 Flags.setByValSize(FrameSize);
5928 }
5929 if (F.paramHasAttr(Idx, Attribute::Nest))
5930 Flags.setNest();
5931 Flags.setOrigAlign(OriginalAlignment);
5932
Owen Anderson23b9b192009-08-12 00:36:31 +00005933 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5934 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005935 for (unsigned i = 0; i != NumRegs; ++i) {
5936 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
5937 if (NumRegs > 1 && i == 0)
5938 MyFlags.Flags.setSplit();
5939 // if it isn't first piece, alignment must be 1
5940 else if (i > 0)
5941 MyFlags.Flags.setOrigAlign(1);
5942 Ins.push_back(MyFlags);
5943 }
5944 }
5945 }
5946
5947 // Call the target to set up the argument values.
5948 SmallVector<SDValue, 8> InVals;
5949 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
5950 F.isVarArg(), Ins,
5951 dl, DAG, InVals);
Dan Gohman5e866062009-08-06 15:37:27 +00005952
5953 // Verify that the target's LowerFormalArguments behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +00005954 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00005955 "LowerFormalArguments didn't return a valid chain!");
5956 assert(InVals.size() == Ins.size() &&
5957 "LowerFormalArguments didn't emit the correct number of values!");
Bill Wendling3ea58b62009-12-22 21:35:02 +00005958 DEBUG({
5959 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5960 assert(InVals[i].getNode() &&
5961 "LowerFormalArguments emitted a null value!");
5962 assert(Ins[i].VT == InVals[i].getValueType() &&
5963 "LowerFormalArguments emitted a value with the wrong type!");
5964 }
5965 });
Bill Wendling3ea3c242009-12-22 02:10:19 +00005966
Dan Gohman5e866062009-08-06 15:37:27 +00005967 // Update the DAG with the new chain value resulting from argument lowering.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005968 DAG.setRoot(NewRoot);
5969
5970 // Set up the argument values.
5971 unsigned i = 0;
5972 Idx = 1;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005973 if (!FLI.CanLowerReturn) {
5974 // Create a virtual register for the sret pointer, and put in a copy
5975 // from the sret argument into it.
5976 SmallVector<EVT, 1> ValueVTs;
5977 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5978 EVT VT = ValueVTs[0];
5979 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5980 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Bill Wendling3ea58b62009-12-22 21:35:02 +00005981 SDValue ArgValue = getCopyFromParts(DAG, dl, 0, &InVals[0], 1,
Bill Wendling3ea3c242009-12-22 02:10:19 +00005982 RegVT, VT, AssertOp);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005983
Dan Gohman2048b852009-11-23 18:04:58 +00005984 MachineFunction& MF = SDB->DAG.getMachineFunction();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005985 MachineRegisterInfo& RegInfo = MF.getRegInfo();
5986 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
5987 FLI.DemoteRegister = SRetReg;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005988 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(),
5989 SRetReg, ArgValue);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005990 DAG.setRoot(NewRoot);
Bill Wendling3ea3c242009-12-22 02:10:19 +00005991
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005992 // i indexes lowered arguments. Bump it past the hidden sret argument.
5993 // Idx indexes LLVM arguments. Don't touch it.
5994 ++i;
5995 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00005996
Dan Gohman98ca4f22009-08-05 01:29:28 +00005997 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5998 ++I, ++Idx) {
5999 SmallVector<SDValue, 4> ArgValues;
Owen Andersone50ed302009-08-10 22:56:29 +00006000 SmallVector<EVT, 4> ValueVTs;
Dan Gohman98ca4f22009-08-05 01:29:28 +00006001 ComputeValueVTs(TLI, I->getType(), ValueVTs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006002 unsigned NumValues = ValueVTs.size();
Dan Gohman98ca4f22009-08-05 01:29:28 +00006003 for (unsigned Value = 0; Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00006004 EVT VT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00006005 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6006 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006007
6008 if (!I->use_empty()) {
6009 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6010 if (F.paramHasAttr(Idx, Attribute::SExt))
6011 AssertOp = ISD::AssertSext;
6012 else if (F.paramHasAttr(Idx, Attribute::ZExt))
6013 AssertOp = ISD::AssertZext;
6014
Bill Wendling3ea58b62009-12-22 21:35:02 +00006015 ArgValues.push_back(getCopyFromParts(DAG, dl, 0, &InVals[i],
Bill Wendling3ea3c242009-12-22 02:10:19 +00006016 NumParts, PartVT, VT,
6017 AssertOp));
Dan Gohman98ca4f22009-08-05 01:29:28 +00006018 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006019
Dan Gohman98ca4f22009-08-05 01:29:28 +00006020 i += NumParts;
6021 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006022
Dan Gohman98ca4f22009-08-05 01:29:28 +00006023 if (!I->use_empty()) {
Bill Wendling3ea3c242009-12-22 02:10:19 +00006024 SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues,
6025 SDB->getCurDebugLoc());
6026 SDB->setValue(I, Res);
6027
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006028 // If this argument is live outside of the entry block, insert a copy from
6029 // whereever we got it to the vreg that other BB's will reference it as.
Dan Gohman2048b852009-11-23 18:04:58 +00006030 SDB->CopyToExportRegsIfNeeded(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006031 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006032 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006033
Dan Gohman98ca4f22009-08-05 01:29:28 +00006034 assert(i == InVals.size() && "Argument register count mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006035
6036 // Finally, if the target has anything special to do, allow it to do so.
6037 // FIXME: this should insert code into the DAG!
Dan Gohman2048b852009-11-23 18:04:58 +00006038 EmitFunctionEntryCode(F, SDB->DAG.getMachineFunction());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006039}
6040
6041/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
6042/// ensure constants are generated when needed. Remember the virtual registers
6043/// that need to be added to the Machine PHI nodes as input. We cannot just
6044/// directly add them, because expansion might result in multiple MBB's for one
6045/// BB. As such, the start of the BB might correspond to a different MBB than
6046/// the end.
6047///
6048void
6049SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
6050 TerminatorInst *TI = LLVMBB->getTerminator();
6051
6052 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6053
6054 // Check successor nodes' PHI nodes that expect a constant to be available
6055 // from this block.
6056 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6057 BasicBlock *SuccBB = TI->getSuccessor(succ);
6058 if (!isa<PHINode>(SuccBB->begin())) continue;
6059 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006060
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006061 // If this terminator has multiple identical successors (common for
6062 // switches), only handle each succ once.
6063 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006064
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006065 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6066 PHINode *PN;
6067
6068 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6069 // nodes and Machine PHI nodes, but the incoming operands have not been
6070 // emitted yet.
6071 for (BasicBlock::iterator I = SuccBB->begin();
6072 (PN = dyn_cast<PHINode>(I)); ++I) {
6073 // Ignore dead phi's.
6074 if (PN->use_empty()) continue;
6075
6076 unsigned Reg;
6077 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6078
6079 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
Dan Gohman2048b852009-11-23 18:04:58 +00006080 unsigned &RegOut = SDB->ConstantsOut[C];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006081 if (RegOut == 0) {
6082 RegOut = FuncInfo->CreateRegForValue(C);
Dan Gohman2048b852009-11-23 18:04:58 +00006083 SDB->CopyValueToVirtualRegister(C, RegOut);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006084 }
6085 Reg = RegOut;
6086 } else {
6087 Reg = FuncInfo->ValueMap[PHIOp];
6088 if (Reg == 0) {
6089 assert(isa<AllocaInst>(PHIOp) &&
6090 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
6091 "Didn't codegen value into a register!??");
6092 Reg = FuncInfo->CreateRegForValue(PHIOp);
Dan Gohman2048b852009-11-23 18:04:58 +00006093 SDB->CopyValueToVirtualRegister(PHIOp, Reg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006094 }
6095 }
6096
6097 // Remember that this register needs to added to the machine PHI node as
6098 // the input for this MBB.
Owen Andersone50ed302009-08-10 22:56:29 +00006099 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006100 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6101 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
Owen Andersone50ed302009-08-10 22:56:29 +00006102 EVT VT = ValueVTs[vti];
Owen Anderson23b9b192009-08-12 00:36:31 +00006103 unsigned NumRegisters = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006104 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Dan Gohman2048b852009-11-23 18:04:58 +00006105 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006106 Reg += NumRegisters;
6107 }
6108 }
6109 }
Dan Gohman2048b852009-11-23 18:04:58 +00006110 SDB->ConstantsOut.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006111}
6112
Dan Gohman3df24e62008-09-03 23:12:08 +00006113/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
6114/// supports legal types, and it emits MachineInstrs directly instead of
6115/// creating SelectionDAG nodes.
6116///
6117bool
6118SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
6119 FastISel *F) {
6120 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006121
Dan Gohman3df24e62008-09-03 23:12:08 +00006122 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
Dan Gohman2048b852009-11-23 18:04:58 +00006123 unsigned OrigNumPHINodesToUpdate = SDB->PHINodesToUpdate.size();
Dan Gohman3df24e62008-09-03 23:12:08 +00006124
6125 // Check successor nodes' PHI nodes that expect a constant to be available
6126 // from this block.
6127 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6128 BasicBlock *SuccBB = TI->getSuccessor(succ);
6129 if (!isa<PHINode>(SuccBB->begin())) continue;
6130 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006131
Dan Gohman3df24e62008-09-03 23:12:08 +00006132 // If this terminator has multiple identical successors (common for
6133 // switches), only handle each succ once.
6134 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006135
Dan Gohman3df24e62008-09-03 23:12:08 +00006136 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6137 PHINode *PN;
6138
6139 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6140 // nodes and Machine PHI nodes, but the incoming operands have not been
6141 // emitted yet.
6142 for (BasicBlock::iterator I = SuccBB->begin();
6143 (PN = dyn_cast<PHINode>(I)); ++I) {
6144 // Ignore dead phi's.
6145 if (PN->use_empty()) continue;
6146
6147 // Only handle legal types. Two interesting things to note here. First,
6148 // by bailing out early, we may leave behind some dead instructions,
6149 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
6150 // own moves. Second, this check is necessary becuase FastISel doesn't
6151 // use CreateRegForValue to create registers, so it always creates
6152 // exactly one register for each non-void instruction.
Owen Andersone50ed302009-08-10 22:56:29 +00006153 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
Owen Anderson825b72b2009-08-11 20:47:22 +00006154 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
6155 // Promote MVT::i1.
6156 if (VT == MVT::i1)
Owen Anderson23b9b192009-08-12 00:36:31 +00006157 VT = TLI.getTypeToTransformTo(*CurDAG->getContext(), VT);
Dan Gohman74321ab2008-09-10 21:01:31 +00006158 else {
Dan Gohman2048b852009-11-23 18:04:58 +00006159 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
Dan Gohman74321ab2008-09-10 21:01:31 +00006160 return false;
6161 }
Dan Gohman3df24e62008-09-03 23:12:08 +00006162 }
6163
6164 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6165
6166 unsigned Reg = F->getRegForValue(PHIOp);
6167 if (Reg == 0) {
Dan Gohman2048b852009-11-23 18:04:58 +00006168 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
Dan Gohman3df24e62008-09-03 23:12:08 +00006169 return false;
6170 }
Dan Gohman2048b852009-11-23 18:04:58 +00006171 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
Dan Gohman3df24e62008-09-03 23:12:08 +00006172 }
6173 }
6174
6175 return true;
6176}