blob: de17f904d90c8da3be61cbb1a46ce8957388d138 [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
683 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
684 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),
847 Add, NULL, Offsets[i], 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);
Bill Wendling87710f02009-12-21 23:47:40 +0000852 } else {
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000853 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
854 SmallVector<EVT, 4> ValueVTs;
855 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
856 unsigned NumValues = ValueVTs.size();
857 if (NumValues == 0) continue;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000858
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000859 SDValue RetOp = getValue(I.getOperand(i));
860 for (unsigned j = 0, f = NumValues; j != f; ++j) {
861 EVT VT = ValueVTs[j];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000862
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000863 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000864
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000865 const Function *F = I.getParent()->getParent();
866 if (F->paramHasAttr(0, Attribute::SExt))
867 ExtendKind = ISD::SIGN_EXTEND;
868 else if (F->paramHasAttr(0, Attribute::ZExt))
869 ExtendKind = ISD::ZERO_EXTEND;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000870
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000871 // FIXME: C calling convention requires the return type to be promoted
872 // to at least 32-bit. But this is not necessary for non-C calling
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000873 // conventions. The frontend should mark functions whose return values
874 // require promoting with signext or zeroext attributes.
875 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
876 EVT MinVT = TLI.getRegisterType(*DAG.getContext(), MVT::i32);
877 if (VT.bitsLT(MinVT))
878 VT = MinVT;
879 }
880
881 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
882 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
883 SmallVector<SDValue, 4> Parts(NumParts);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000884 getCopyToParts(DAG, getCurDebugLoc(), SDNodeOrder,
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000885 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
886 &Parts[0], NumParts, PartVT, ExtendKind);
887
888 // 'inreg' on function refers to return value
889 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
890 if (F->paramHasAttr(0, Attribute::InReg))
891 Flags.setInReg();
892
893 // Propagate extension type if any
894 if (F->paramHasAttr(0, Attribute::SExt))
895 Flags.setSExt();
896 else if (F->paramHasAttr(0, Attribute::ZExt))
897 Flags.setZExt();
898
899 for (unsigned i = 0; i < NumParts; ++i)
900 Outs.push_back(ISD::OutputArg(Flags, Parts[i], /*isfixed=*/true));
Evan Cheng3927f432009-03-25 20:20:11 +0000901 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000902 }
903 }
Dan Gohman98ca4f22009-08-05 01:29:28 +0000904
905 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +0000906 CallingConv::ID CallConv =
907 DAG.getMachineFunction().getFunction()->getCallingConv();
Dan Gohman98ca4f22009-08-05 01:29:28 +0000908 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
909 Outs, getCurDebugLoc(), DAG);
Dan Gohman5e866062009-08-06 15:37:27 +0000910
911 // Verify that the target's LowerReturn behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +0000912 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +0000913 "LowerReturn didn't return a valid chain!");
914
915 // Update the DAG with the new chain value resulting from return lowering.
Dan Gohman98ca4f22009-08-05 01:29:28 +0000916 DAG.setRoot(Chain);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000917}
918
Dan Gohmanad62f532009-04-23 23:13:24 +0000919/// CopyToExportRegsIfNeeded - If the given value has virtual registers
920/// created for it, emit nodes to copy the value into the virtual
921/// registers.
Dan Gohman2048b852009-11-23 18:04:58 +0000922void SelectionDAGBuilder::CopyToExportRegsIfNeeded(Value *V) {
Dan Gohmanad62f532009-04-23 23:13:24 +0000923 if (!V->use_empty()) {
924 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
925 if (VMI != FuncInfo.ValueMap.end())
926 CopyValueToVirtualRegister(V, VMI->second);
927 }
928}
929
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000930/// ExportFromCurrentBlock - If this condition isn't known to be exported from
931/// the current basic block, add it to ValueMap now so that we'll get a
932/// CopyTo/FromReg.
Dan Gohman2048b852009-11-23 18:04:58 +0000933void SelectionDAGBuilder::ExportFromCurrentBlock(Value *V) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000934 // No need to export constants.
935 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000936
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000937 // Already exported?
938 if (FuncInfo.isExportedInst(V)) return;
939
940 unsigned Reg = FuncInfo.InitializeRegForValue(V);
941 CopyValueToVirtualRegister(V, Reg);
942}
943
Dan Gohman2048b852009-11-23 18:04:58 +0000944bool SelectionDAGBuilder::isExportableFromCurrentBlock(Value *V,
945 const BasicBlock *FromBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000946 // The operands of the setcc have to be in this block. We don't know
947 // how to export them from some other block.
948 if (Instruction *VI = dyn_cast<Instruction>(V)) {
949 // Can export from current BB.
950 if (VI->getParent() == FromBB)
951 return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000952
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000953 // Is already exported, noop.
954 return FuncInfo.isExportedInst(V);
955 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000956
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000957 // If this is an argument, we can export it if the BB is the entry block or
958 // if it is already exported.
959 if (isa<Argument>(V)) {
960 if (FromBB == &FromBB->getParent()->getEntryBlock())
961 return true;
962
963 // Otherwise, can only export this if it is already exported.
964 return FuncInfo.isExportedInst(V);
965 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000966
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000967 // Otherwise, constants can always be exported.
968 return true;
969}
970
971static bool InBlock(const Value *V, const BasicBlock *BB) {
972 if (const Instruction *I = dyn_cast<Instruction>(V))
973 return I->getParent() == BB;
974 return true;
975}
976
Dan Gohman8c1a6ca2008-10-17 18:18:45 +0000977/// getFCmpCondCode - Return the ISD condition code corresponding to
978/// the given LLVM IR floating-point condition code. This includes
979/// consideration of global floating-point math flags.
980///
981static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
982 ISD::CondCode FPC, FOC;
983 switch (Pred) {
984 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
985 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
986 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
987 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
988 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
989 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
990 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
991 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
992 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
993 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
994 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
995 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
996 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
997 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
998 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
999 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1000 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001001 llvm_unreachable("Invalid FCmp predicate opcode!");
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001002 FOC = FPC = ISD::SETFALSE;
1003 break;
1004 }
1005 if (FiniteOnlyFPMath())
1006 return FOC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001007 else
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001008 return FPC;
1009}
1010
1011/// getICmpCondCode - Return the ISD condition code corresponding to
1012/// the given LLVM IR integer condition code.
1013///
1014static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1015 switch (Pred) {
1016 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1017 case ICmpInst::ICMP_NE: return ISD::SETNE;
1018 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1019 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1020 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1021 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1022 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1023 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1024 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1025 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1026 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001027 llvm_unreachable("Invalid ICmp predicate opcode!");
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001028 return ISD::SETNE;
1029 }
1030}
1031
Dan Gohmanc2277342008-10-17 21:16:08 +00001032/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1033/// This function emits a branch and is used at the leaves of an OR or an
1034/// AND operator tree.
1035///
1036void
Dan Gohman2048b852009-11-23 18:04:58 +00001037SelectionDAGBuilder::EmitBranchForMergedCondition(Value *Cond,
1038 MachineBasicBlock *TBB,
1039 MachineBasicBlock *FBB,
1040 MachineBasicBlock *CurBB) {
Dan Gohmanc2277342008-10-17 21:16:08 +00001041 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001042
Dan Gohmanc2277342008-10-17 21:16:08 +00001043 // If the leaf of the tree is a comparison, merge the condition into
1044 // the caseblock.
1045 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1046 // The operands of the cmp have to be in this block. We don't know
1047 // how to export them from some other block. If this is the first block
1048 // of the sequence, no exporting is needed.
1049 if (CurBB == CurMBB ||
1050 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1051 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001052 ISD::CondCode Condition;
1053 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001054 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001055 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001056 Condition = getFCmpCondCode(FC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001057 } else {
1058 Condition = ISD::SETEQ; // silence warning.
Torok Edwinc23197a2009-07-14 16:55:14 +00001059 llvm_unreachable("Unknown compare instruction");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001060 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001061
1062 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001063 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1064 SwitchCases.push_back(CB);
1065 return;
1066 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001067 }
1068
1069 // Create a CaseBlock record representing this branch.
Owen Anderson5defacc2009-07-31 17:39:07 +00001070 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
Dan Gohmanc2277342008-10-17 21:16:08 +00001071 NULL, TBB, FBB, CurBB);
1072 SwitchCases.push_back(CB);
1073}
1074
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001075/// FindMergedConditions - If Cond is an expression like
Dan Gohman2048b852009-11-23 18:04:58 +00001076void SelectionDAGBuilder::FindMergedConditions(Value *Cond,
1077 MachineBasicBlock *TBB,
1078 MachineBasicBlock *FBB,
1079 MachineBasicBlock *CurBB,
1080 unsigned Opc) {
Dan Gohmanc2277342008-10-17 21:16:08 +00001081 // If this node is not part of the or/and tree, emit it as a branch.
1082 Instruction *BOp = dyn_cast<Instruction>(Cond);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001083 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohmanc2277342008-10-17 21:16:08 +00001084 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1085 BOp->getParent() != CurBB->getBasicBlock() ||
1086 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1087 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1088 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001089 return;
1090 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001091
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001092 // Create TmpBB after CurBB.
1093 MachineFunction::iterator BBI = CurBB;
1094 MachineFunction &MF = DAG.getMachineFunction();
1095 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1096 CurBB->getParent()->insert(++BBI, TmpBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001097
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001098 if (Opc == Instruction::Or) {
1099 // Codegen X | Y as:
1100 // jmp_if_X TBB
1101 // jmp TmpBB
1102 // TmpBB:
1103 // jmp_if_Y TBB
1104 // jmp FBB
1105 //
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001106
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001107 // Emit the LHS condition.
1108 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001109
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001110 // Emit the RHS condition into TmpBB.
1111 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1112 } else {
1113 assert(Opc == Instruction::And && "Unknown merge op!");
1114 // Codegen X & Y as:
1115 // jmp_if_X TmpBB
1116 // jmp FBB
1117 // TmpBB:
1118 // jmp_if_Y TBB
1119 // jmp FBB
1120 //
1121 // This requires creation of TmpBB after CurBB.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001122
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001123 // Emit the LHS condition.
1124 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001125
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001126 // Emit the RHS condition into TmpBB.
1127 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1128 }
1129}
1130
1131/// If the set of cases should be emitted as a series of branches, return true.
1132/// If we should emit this as a bunch of and/or'd together conditions, return
1133/// false.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001134bool
Dan Gohman2048b852009-11-23 18:04:58 +00001135SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001136 if (Cases.size() != 2) return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001137
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001138 // If this is two comparisons of the same values or'd or and'd together, they
1139 // will get folded into a single comparison, so don't emit two blocks.
1140 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1141 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1142 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1143 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1144 return false;
1145 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001146
Chris Lattner133ce872010-01-02 00:00:03 +00001147 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1148 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1149 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1150 Cases[0].CC == Cases[1].CC &&
1151 isa<Constant>(Cases[0].CmpRHS) &&
1152 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1153 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1154 return false;
1155 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1156 return false;
1157 }
1158
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001159 return true;
1160}
1161
Dan Gohman2048b852009-11-23 18:04:58 +00001162void SelectionDAGBuilder::visitBr(BranchInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001163 // Update machine-CFG edges.
1164 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1165
1166 // Figure out which block is immediately after the current one.
1167 MachineBasicBlock *NextBlock = 0;
1168 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001169 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001170 NextBlock = BBI;
1171
1172 if (I.isUnconditional()) {
1173 // Update machine-CFG edges.
1174 CurMBB->addSuccessor(Succ0MBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001175
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001176 // If this is not a fall-through branch, emit the branch.
Bill Wendling4533cac2010-01-28 21:51:40 +00001177 if (Succ0MBB != NextBlock)
1178 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001179 MVT::Other, getControlRoot(),
Bill Wendling4533cac2010-01-28 21:51:40 +00001180 DAG.getBasicBlock(Succ0MBB)));
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001181
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001182 return;
1183 }
1184
1185 // If this condition is one of the special cases we handle, do special stuff
1186 // now.
1187 Value *CondVal = I.getCondition();
1188 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1189
1190 // If this is a series of conditions that are or'd or and'd together, emit
1191 // this as a sequence of branches instead of setcc's with and/or operations.
1192 // For example, instead of something like:
1193 // cmp A, B
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001194 // C = seteq
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001195 // cmp D, E
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001196 // F = setle
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001197 // or C, F
1198 // jnz foo
1199 // Emit:
1200 // cmp A, B
1201 // je foo
1202 // cmp D, E
1203 // jle foo
1204 //
1205 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001206 if (BOp->hasOneUse() &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001207 (BOp->getOpcode() == Instruction::And ||
1208 BOp->getOpcode() == Instruction::Or)) {
1209 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1210 // If the compares in later blocks need to use values not currently
1211 // exported from this block, export them now. This block should always
1212 // be the first entry.
1213 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001214
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001215 // Allow some cases to be rejected.
1216 if (ShouldEmitAsBranches(SwitchCases)) {
1217 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1218 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1219 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1220 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001221
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001222 // Emit the branch for this block.
1223 visitSwitchCase(SwitchCases[0]);
1224 SwitchCases.erase(SwitchCases.begin());
1225 return;
1226 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001227
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001228 // Okay, we decided not to do this, remove any inserted MBB's and clear
1229 // SwitchCases.
1230 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001231 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001232
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001233 SwitchCases.clear();
1234 }
1235 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001236
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001237 // Create a CaseBlock record representing this branch.
Owen Anderson5defacc2009-07-31 17:39:07 +00001238 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001239 NULL, Succ0MBB, Succ1MBB, CurMBB);
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001240
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001241 // Use visitSwitchCase to actually insert the fast branch sequence for this
1242 // cond branch.
1243 visitSwitchCase(CB);
1244}
1245
1246/// visitSwitchCase - Emits the necessary code to represent a single node in
1247/// the binary search tree resulting from lowering a switch instruction.
Dan Gohman2048b852009-11-23 18:04:58 +00001248void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001249 SDValue Cond;
1250 SDValue CondLHS = getValue(CB.CmpLHS);
Dale Johannesenf5d97892009-02-04 01:48:28 +00001251 DebugLoc dl = getCurDebugLoc();
Anton Korobeynikov23218582008-12-23 22:25:27 +00001252
1253 // Build the setcc now.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001254 if (CB.CmpMHS == NULL) {
1255 // Fold "(X == true)" to X and "(X == false)" to !X to
1256 // handle common cases produced by branch lowering.
Owen Anderson5defacc2009-07-31 17:39:07 +00001257 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
Owen Andersonf53c3712009-07-21 02:47:59 +00001258 CB.CC == ISD::SETEQ)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001259 Cond = CondLHS;
Owen Anderson5defacc2009-07-31 17:39:07 +00001260 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
Owen Andersonf53c3712009-07-21 02:47:59 +00001261 CB.CC == ISD::SETEQ) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001262 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001263 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001264 } else
Owen Anderson825b72b2009-08-11 20:47:22 +00001265 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001266 } else {
1267 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1268
Anton Korobeynikov23218582008-12-23 22:25:27 +00001269 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1270 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001271
1272 SDValue CmpOp = getValue(CB.CmpMHS);
Owen Andersone50ed302009-08-10 22:56:29 +00001273 EVT VT = CmpOp.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001274
1275 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001276 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
Dale Johannesenf5d97892009-02-04 01:48:28 +00001277 ISD::SETLE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001278 } else {
Dale Johannesenf5d97892009-02-04 01:48:28 +00001279 SDValue SUB = DAG.getNode(ISD::SUB, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001280 VT, CmpOp, DAG.getConstant(Low, VT));
Owen Anderson825b72b2009-08-11 20:47:22 +00001281 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001282 DAG.getConstant(High-Low, VT), ISD::SETULE);
1283 }
1284 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001285
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001286 // Update successor info
1287 CurMBB->addSuccessor(CB.TrueBB);
1288 CurMBB->addSuccessor(CB.FalseBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001289
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001290 // Set NextBlock to be the MBB immediately after the current one, if any.
1291 // This is used to avoid emitting unnecessary branches to the next block.
1292 MachineBasicBlock *NextBlock = 0;
1293 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001294 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001295 NextBlock = BBI;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001296
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001297 // If the lhs block is the next block, invert the condition so that we can
1298 // fall through to the lhs instead of the rhs block.
1299 if (CB.TrueBB == NextBlock) {
1300 std::swap(CB.TrueBB, CB.FalseBB);
1301 SDValue True = DAG.getConstant(1, Cond.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001302 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001303 }
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001304
Dale Johannesenf5d97892009-02-04 01:48:28 +00001305 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00001306 MVT::Other, getControlRoot(), Cond,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001307 DAG.getBasicBlock(CB.TrueBB));
Bill Wendling87710f02009-12-21 23:47:40 +00001308
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001309 // If the branch was constant folded, fix up the CFG.
1310 if (BrCond.getOpcode() == ISD::BR) {
1311 CurMBB->removeSuccessor(CB.FalseBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001312 } else {
1313 // Otherwise, go ahead and insert the false branch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001314 if (BrCond == getControlRoot())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001315 CurMBB->removeSuccessor(CB.TrueBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001316
Bill Wendling4533cac2010-01-28 21:51:40 +00001317 if (CB.FalseBB != NextBlock)
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001318 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1319 DAG.getBasicBlock(CB.FalseBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001320 }
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001321
1322 DAG.setRoot(BrCond);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001323}
1324
1325/// visitJumpTable - Emit JumpTable node in the current MBB
Dan Gohman2048b852009-11-23 18:04:58 +00001326void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001327 // Emit the code for the jump table
1328 assert(JT.Reg != -1U && "Should lower JT Header first!");
Owen Andersone50ed302009-08-10 22:56:29 +00001329 EVT PTy = TLI.getPointerTy();
Dale Johannesena04b7572009-02-03 23:04:43 +00001330 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1331 JT.Reg, PTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001332 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001333 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1334 MVT::Other, Index.getValue(1),
1335 Table, Index);
1336 DAG.setRoot(BrJumpTable);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001337}
1338
1339/// visitJumpTableHeader - This function emits necessary code to produce index
1340/// in the JumpTable from switch case.
Dan Gohman2048b852009-11-23 18:04:58 +00001341void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1342 JumpTableHeader &JTH) {
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001343 // Subtract the lowest switch case value from the value being switched on and
1344 // conditional branch to default mbb if the result is greater than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001345 // difference between smallest and largest cases.
1346 SDValue SwitchOp = getValue(JTH.SValue);
Owen Andersone50ed302009-08-10 22:56:29 +00001347 EVT VT = SwitchOp.getValueType();
Bill Wendling87710f02009-12-21 23:47:40 +00001348 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001349 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001350
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001351 // The SDNode we just created, which holds the value being switched on minus
Dan Gohmanf451cb82010-02-10 16:03:48 +00001352 // the smallest case value, needs to be copied to a virtual register so it
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001353 // can be used as an index into the jump table in a subsequent basic block.
1354 // This value may be smaller or larger than the target's pointer type, and
1355 // therefore require extension or truncating.
Bill Wendling87710f02009-12-21 23:47:40 +00001356 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001357
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001358 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001359 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1360 JumpTableReg, SwitchOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001361 JT.Reg = JumpTableReg;
1362
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001363 // Emit the range check for the jump table, and branch to the default block
1364 // for the switch statement if the value being switched on exceeds the largest
1365 // case in the switch.
Dale Johannesenf5d97892009-02-04 01:48:28 +00001366 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00001367 TLI.getSetCCResultType(Sub.getValueType()), Sub,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001368 DAG.getConstant(JTH.Last-JTH.First,VT),
1369 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001370
1371 // Set NextBlock to be the MBB immediately after the current one, if any.
1372 // This is used to avoid emitting unnecessary branches to the next block.
1373 MachineBasicBlock *NextBlock = 0;
1374 MachineFunction::iterator BBI = CurMBB;
Bill Wendling87710f02009-12-21 23:47:40 +00001375
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001376 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001377 NextBlock = BBI;
1378
Dale Johannesen66978ee2009-01-31 02:22:37 +00001379 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001380 MVT::Other, CopyTo, CMP,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001381 DAG.getBasicBlock(JT.Default));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001382
Bill Wendling4533cac2010-01-28 21:51:40 +00001383 if (JT.MBB != NextBlock)
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001384 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1385 DAG.getBasicBlock(JT.MBB));
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001386
Bill Wendling87710f02009-12-21 23:47:40 +00001387 DAG.setRoot(BrCond);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001388}
1389
1390/// visitBitTestHeader - This function emits necessary code to produce value
1391/// suitable for "bit tests"
Dan Gohman2048b852009-11-23 18:04:58 +00001392void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001393 // Subtract the minimum value
1394 SDValue SwitchOp = getValue(B.SValue);
Owen Andersone50ed302009-08-10 22:56:29 +00001395 EVT VT = SwitchOp.getValueType();
Bill Wendling87710f02009-12-21 23:47:40 +00001396 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001397 DAG.getConstant(B.First, VT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001398
1399 // Check range
Dale Johannesenf5d97892009-02-04 01:48:28 +00001400 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00001401 TLI.getSetCCResultType(Sub.getValueType()),
1402 Sub, DAG.getConstant(B.Range, VT),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001403 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001404
Bill Wendling87710f02009-12-21 23:47:40 +00001405 SDValue ShiftOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(),
1406 TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001407
Duncan Sands92abc622009-01-31 15:50:11 +00001408 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001409 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1410 B.Reg, ShiftOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001411
1412 // Set NextBlock to be the MBB immediately after the current one, if any.
1413 // This is used to avoid emitting unnecessary branches to the next block.
1414 MachineBasicBlock *NextBlock = 0;
1415 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001416 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001417 NextBlock = BBI;
1418
1419 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1420
1421 CurMBB->addSuccessor(B.Default);
1422 CurMBB->addSuccessor(MBB);
1423
Dale Johannesen66978ee2009-01-31 02:22:37 +00001424 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001425 MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001426 DAG.getBasicBlock(B.Default));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001427
Bill Wendling4533cac2010-01-28 21:51:40 +00001428 if (MBB != NextBlock)
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001429 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1430 DAG.getBasicBlock(MBB));
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001431
Bill Wendling87710f02009-12-21 23:47:40 +00001432 DAG.setRoot(BrRange);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001433}
1434
1435/// visitBitTestCase - this function produces one "bit test"
Dan Gohman2048b852009-11-23 18:04:58 +00001436void SelectionDAGBuilder::visitBitTestCase(MachineBasicBlock* NextMBB,
1437 unsigned Reg,
1438 BitTestCase &B) {
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001439 // Make desired shift
Dale Johannesena04b7572009-02-03 23:04:43 +00001440 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
Duncan Sands92abc622009-01-31 15:50:11 +00001441 TLI.getPointerTy());
Scott Michelfdc40a02009-02-17 22:15:04 +00001442 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001443 TLI.getPointerTy(),
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001444 DAG.getConstant(1, TLI.getPointerTy()),
1445 ShiftOp);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001446
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001447 // Emit bit tests and jumps
Scott Michelfdc40a02009-02-17 22:15:04 +00001448 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001449 TLI.getPointerTy(), SwitchVal,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001450 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Dale Johannesenf5d97892009-02-04 01:48:28 +00001451 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1452 TLI.getSetCCResultType(AndOp.getValueType()),
Duncan Sands5480c042009-01-01 15:52:00 +00001453 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001454 ISD::SETNE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001455
1456 CurMBB->addSuccessor(B.TargetBB);
1457 CurMBB->addSuccessor(NextMBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001458
Dale Johannesen66978ee2009-01-31 02:22:37 +00001459 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001460 MVT::Other, getControlRoot(),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001461 AndCmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001462
1463 // Set NextBlock to be the MBB immediately after the current one, if any.
1464 // This is used to avoid emitting unnecessary branches to the next block.
1465 MachineBasicBlock *NextBlock = 0;
1466 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001467 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001468 NextBlock = BBI;
1469
Bill Wendling4533cac2010-01-28 21:51:40 +00001470 if (NextMBB != NextBlock)
Bill Wendling0777e922009-12-21 21:59:52 +00001471 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1472 DAG.getBasicBlock(NextMBB));
Bill Wendling0777e922009-12-21 21:59:52 +00001473
Bill Wendling87710f02009-12-21 23:47:40 +00001474 DAG.setRoot(BrAnd);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001475}
1476
Dan Gohman2048b852009-11-23 18:04:58 +00001477void SelectionDAGBuilder::visitInvoke(InvokeInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001478 // Retrieve successors.
1479 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1480 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1481
Gabor Greifb67e6b32009-01-15 11:10:44 +00001482 const Value *Callee(I.getCalledValue());
1483 if (isa<InlineAsm>(Callee))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001484 visitInlineAsm(&I);
1485 else
Gabor Greifb67e6b32009-01-15 11:10:44 +00001486 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001487
1488 // If the value of the invoke is used outside of its defining block, make it
1489 // available as a virtual register.
Dan Gohmanad62f532009-04-23 23:13:24 +00001490 CopyToExportRegsIfNeeded(&I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001491
1492 // Update successor info
1493 CurMBB->addSuccessor(Return);
1494 CurMBB->addSuccessor(LandingPad);
1495
1496 // Drop into normal successor.
Bill Wendling4533cac2010-01-28 21:51:40 +00001497 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1498 MVT::Other, getControlRoot(),
1499 DAG.getBasicBlock(Return)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001500}
1501
Dan Gohman2048b852009-11-23 18:04:58 +00001502void SelectionDAGBuilder::visitUnwind(UnwindInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001503}
1504
1505/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1506/// small case ranges).
Dan Gohman2048b852009-11-23 18:04:58 +00001507bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
1508 CaseRecVector& WorkList,
1509 Value* SV,
1510 MachineBasicBlock* Default) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001511 Case& BackCase = *(CR.Range.second-1);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001512
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001513 // Size is the number of Cases represented by this range.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001514 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001515 if (Size > 3)
Anton Korobeynikov23218582008-12-23 22:25:27 +00001516 return false;
1517
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001518 // Get the MachineFunction which holds the current MBB. This is used when
1519 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001520 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001521
1522 // Figure out which block is immediately after the current one.
1523 MachineBasicBlock *NextBlock = 0;
1524 MachineFunction::iterator BBI = CR.CaseBB;
1525
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001526 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001527 NextBlock = BBI;
1528
1529 // TODO: If any two of the cases has the same destination, and if one value
1530 // is the same as the other, but has one bit unset that the other has set,
1531 // use bit manipulation to do two compares at once. For example:
1532 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Anton Korobeynikov23218582008-12-23 22:25:27 +00001533
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001534 // Rearrange the case blocks so that the last one falls through if possible.
1535 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1536 // The last case block won't fall through into 'NextBlock' if we emit the
1537 // branches in this order. See if rearranging a case value would help.
1538 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1539 if (I->BB == NextBlock) {
1540 std::swap(*I, BackCase);
1541 break;
1542 }
1543 }
1544 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001545
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001546 // Create a CaseBlock record representing a conditional branch to
1547 // the Case's target mbb if the value being switched on SV is equal
1548 // to C.
1549 MachineBasicBlock *CurBlock = CR.CaseBB;
1550 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1551 MachineBasicBlock *FallThrough;
1552 if (I != E-1) {
1553 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1554 CurMF->insert(BBI, FallThrough);
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001555
1556 // Put SV in a virtual register to make it available from the new blocks.
1557 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001558 } else {
1559 // If the last case doesn't match, go to the default block.
1560 FallThrough = Default;
1561 }
1562
1563 Value *RHS, *LHS, *MHS;
1564 ISD::CondCode CC;
1565 if (I->High == I->Low) {
1566 // This is just small small case range :) containing exactly 1 case
1567 CC = ISD::SETEQ;
1568 LHS = SV; RHS = I->High; MHS = NULL;
1569 } else {
1570 CC = ISD::SETLE;
1571 LHS = I->Low; MHS = SV; RHS = I->High;
1572 }
1573 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001574
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001575 // If emitting the first comparison, just call visitSwitchCase to emit the
1576 // code into the current block. Otherwise, push the CaseBlock onto the
1577 // vector to be later processed by SDISel, and insert the node's MBB
1578 // before the next MBB.
1579 if (CurBlock == CurMBB)
1580 visitSwitchCase(CB);
1581 else
1582 SwitchCases.push_back(CB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001583
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001584 CurBlock = FallThrough;
1585 }
1586
1587 return true;
1588}
1589
1590static inline bool areJTsAllowed(const TargetLowering &TLI) {
1591 return !DisableJumpTables &&
Owen Anderson825b72b2009-08-11 20:47:22 +00001592 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1593 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001594}
Anton Korobeynikov23218582008-12-23 22:25:27 +00001595
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001596static APInt ComputeRange(const APInt &First, const APInt &Last) {
1597 APInt LastExt(Last), FirstExt(First);
1598 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1599 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1600 return (LastExt - FirstExt + 1ULL);
1601}
1602
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001603/// handleJTSwitchCase - Emit jumptable for current switch case range
Dan Gohman2048b852009-11-23 18:04:58 +00001604bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR,
1605 CaseRecVector& WorkList,
1606 Value* SV,
1607 MachineBasicBlock* Default) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001608 Case& FrontCase = *CR.Range.first;
1609 Case& BackCase = *(CR.Range.second-1);
1610
Chris Lattnere880efe2009-11-07 07:50:34 +00001611 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1612 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001613
Chris Lattnere880efe2009-11-07 07:50:34 +00001614 APInt TSize(First.getBitWidth(), 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001615 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1616 I!=E; ++I)
1617 TSize += I->size();
1618
Chris Lattnere880efe2009-11-07 07:50:34 +00001619 if (!areJTsAllowed(TLI) || TSize.ult(APInt(First.getBitWidth(), 4)))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001620 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001621
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001622 APInt Range = ComputeRange(First, Last);
Chris Lattnere880efe2009-11-07 07:50:34 +00001623 double Density = TSize.roundToDouble() / Range.roundToDouble();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001624 if (Density < 0.4)
1625 return false;
1626
David Greene4b69d992010-01-05 01:24:57 +00001627 DEBUG(dbgs() << "Lowering jump table\n"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001628 << "First entry: " << First << ". Last entry: " << Last << '\n'
1629 << "Range: " << Range
1630 << "Size: " << TSize << ". Density: " << Density << "\n\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001631
1632 // Get the MachineFunction which holds the current MBB. This is used when
1633 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001634 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001635
1636 // Figure out which block is immediately after the current one.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001637 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands51498522009-09-06 18:03:32 +00001638 ++BBI;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001639
1640 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1641
1642 // Create a new basic block to hold the code for loading the address
1643 // of the jump table, and jumping to it. Update successor information;
1644 // we will either branch to the default case for the switch, or the jump
1645 // table.
1646 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1647 CurMF->insert(BBI, JumpTableBB);
1648 CR.CaseBB->addSuccessor(Default);
1649 CR.CaseBB->addSuccessor(JumpTableBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001650
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001651 // Build a vector of destination BBs, corresponding to each target
1652 // of the jump table. If the value of the jump table slot corresponds to
1653 // a case statement, push the case's BB onto the vector, otherwise, push
1654 // the default BB.
1655 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001656 APInt TEI = First;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001657 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Chris Lattner071c62f2010-01-25 23:26:13 +00001658 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
1659 const APInt &High = cast<ConstantInt>(I->High)->getValue();
Anton Korobeynikov23218582008-12-23 22:25:27 +00001660
1661 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001662 DestBBs.push_back(I->BB);
1663 if (TEI==High)
1664 ++I;
1665 } else {
1666 DestBBs.push_back(Default);
1667 }
1668 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001669
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001670 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001671 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1672 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001673 E = DestBBs.end(); I != E; ++I) {
1674 if (!SuccsHandled[(*I)->getNumber()]) {
1675 SuccsHandled[(*I)->getNumber()] = true;
1676 JumpTableBB->addSuccessor(*I);
1677 }
1678 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001679
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001680 // Create a jump table index for this jump table, or return an existing
1681 // one.
Chris Lattner071c62f2010-01-25 23:26:13 +00001682 unsigned JTEncoding = TLI.getJumpTableEncoding();
1683 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
1684 ->getJumpTableIndex(DestBBs);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001685
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001686 // Set the jump table information so that we can codegen it as a second
1687 // MachineBasicBlock
1688 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1689 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1690 if (CR.CaseBB == CurMBB)
1691 visitJumpTableHeader(JT, JTH);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001692
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001693 JTCases.push_back(JumpTableBlock(JTH, JT));
1694
1695 return true;
1696}
1697
1698/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1699/// 2 subtrees.
Dan Gohman2048b852009-11-23 18:04:58 +00001700bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
1701 CaseRecVector& WorkList,
1702 Value* SV,
1703 MachineBasicBlock* Default) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001704 // Get the MachineFunction which holds the current MBB. This is used when
1705 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001706 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001707
1708 // Figure out which block is immediately after the current one.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001709 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands51498522009-09-06 18:03:32 +00001710 ++BBI;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001711
1712 Case& FrontCase = *CR.Range.first;
1713 Case& BackCase = *(CR.Range.second-1);
1714 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1715
1716 // Size is the number of Cases represented by this range.
1717 unsigned Size = CR.Range.second - CR.Range.first;
1718
Chris Lattnere880efe2009-11-07 07:50:34 +00001719 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1720 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001721 double FMetric = 0;
1722 CaseItr Pivot = CR.Range.first + Size/2;
1723
1724 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1725 // (heuristically) allow us to emit JumpTable's later.
Chris Lattnere880efe2009-11-07 07:50:34 +00001726 APInt TSize(First.getBitWidth(), 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001727 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1728 I!=E; ++I)
1729 TSize += I->size();
1730
Chris Lattnere880efe2009-11-07 07:50:34 +00001731 APInt LSize = FrontCase.size();
1732 APInt RSize = TSize-LSize;
David Greene4b69d992010-01-05 01:24:57 +00001733 DEBUG(dbgs() << "Selecting best pivot: \n"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001734 << "First: " << First << ", Last: " << Last <<'\n'
1735 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001736 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1737 J!=E; ++I, ++J) {
Chris Lattnere880efe2009-11-07 07:50:34 +00001738 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
1739 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001740 APInt Range = ComputeRange(LEnd, RBegin);
1741 assert((Range - 2ULL).isNonNegative() &&
1742 "Invalid case distance");
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00001743 double LDensity = (double)LSize.roundToDouble() /
Chris Lattnere880efe2009-11-07 07:50:34 +00001744 (LEnd - First + 1ULL).roundToDouble();
1745 double RDensity = (double)RSize.roundToDouble() /
1746 (Last - RBegin + 1ULL).roundToDouble();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001747 double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001748 // Should always split in some non-trivial place
David Greene4b69d992010-01-05 01:24:57 +00001749 DEBUG(dbgs() <<"=>Step\n"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001750 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1751 << "LDensity: " << LDensity
1752 << ", RDensity: " << RDensity << '\n'
1753 << "Metric: " << Metric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001754 if (FMetric < Metric) {
1755 Pivot = J;
1756 FMetric = Metric;
David Greene4b69d992010-01-05 01:24:57 +00001757 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001758 }
1759
1760 LSize += J->size();
1761 RSize -= J->size();
1762 }
1763 if (areJTsAllowed(TLI)) {
1764 // If our case is dense we *really* should handle it earlier!
1765 assert((FMetric > 0) && "Should handle dense range earlier!");
1766 } else {
1767 Pivot = CR.Range.first + Size/2;
1768 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001769
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001770 CaseRange LHSR(CR.Range.first, Pivot);
1771 CaseRange RHSR(Pivot, CR.Range.second);
1772 Constant *C = Pivot->Low;
1773 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001774
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001775 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001776 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001777 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001778 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001779 // Pivot's Value, then we can branch directly to the LHS's Target,
1780 // rather than creating a leaf node for it.
1781 if ((LHSR.second - LHSR.first) == 1 &&
1782 LHSR.first->High == CR.GE &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001783 cast<ConstantInt>(C)->getValue() ==
1784 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001785 TrueBB = LHSR.first->BB;
1786 } else {
1787 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1788 CurMF->insert(BBI, TrueBB);
1789 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001790
1791 // Put SV in a virtual register to make it available from the new blocks.
1792 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001793 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001794
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001795 // Similar to the optimization above, if the Value being switched on is
1796 // known to be less than the Constant CR.LT, and the current Case Value
1797 // is CR.LT - 1, then we can branch directly to the target block for
1798 // the current Case Value, rather than emitting a RHS leaf node for it.
1799 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001800 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1801 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001802 FalseBB = RHSR.first->BB;
1803 } else {
1804 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1805 CurMF->insert(BBI, FalseBB);
1806 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001807
1808 // Put SV in a virtual register to make it available from the new blocks.
1809 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001810 }
1811
1812 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001813 // the LHS node if the value being switched on SV is less than C.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001814 // Otherwise, branch to LHS.
1815 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1816
1817 if (CR.CaseBB == CurMBB)
1818 visitSwitchCase(CB);
1819 else
1820 SwitchCases.push_back(CB);
1821
1822 return true;
1823}
1824
1825/// handleBitTestsSwitchCase - if current case range has few destination and
1826/// range span less, than machine word bitwidth, encode case range into series
1827/// of masks and emit bit tests with these masks.
Dan Gohman2048b852009-11-23 18:04:58 +00001828bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
1829 CaseRecVector& WorkList,
1830 Value* SV,
1831 MachineBasicBlock* Default){
Owen Andersone50ed302009-08-10 22:56:29 +00001832 EVT PTy = TLI.getPointerTy();
Owen Anderson77547be2009-08-10 18:56:59 +00001833 unsigned IntPtrBits = PTy.getSizeInBits();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001834
1835 Case& FrontCase = *CR.Range.first;
1836 Case& BackCase = *(CR.Range.second-1);
1837
1838 // Get the MachineFunction which holds the current MBB. This is used when
1839 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001840 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001841
Anton Korobeynikovd34167a2009-05-08 18:51:34 +00001842 // If target does not have legal shift left, do not emit bit tests at all.
1843 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
1844 return false;
1845
Anton Korobeynikov23218582008-12-23 22:25:27 +00001846 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001847 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1848 I!=E; ++I) {
1849 // Single case counts one, case range - two.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001850 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001851 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001852
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001853 // Count unique destinations
1854 SmallSet<MachineBasicBlock*, 4> Dests;
1855 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1856 Dests.insert(I->BB);
1857 if (Dests.size() > 3)
1858 // Don't bother the code below, if there are too much unique destinations
1859 return false;
1860 }
David Greene4b69d992010-01-05 01:24:57 +00001861 DEBUG(dbgs() << "Total number of unique destinations: "
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00001862 << Dests.size() << '\n'
1863 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001864
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001865 // Compute span of values.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001866 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1867 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001868 APInt cmpRange = maxValue - minValue;
1869
David Greene4b69d992010-01-05 01:24:57 +00001870 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001871 << "Low bound: " << minValue << '\n'
1872 << "High bound: " << maxValue << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001873
1874 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001875 (!(Dests.size() == 1 && numCmps >= 3) &&
1876 !(Dests.size() == 2 && numCmps >= 5) &&
1877 !(Dests.size() >= 3 && numCmps >= 6)))
1878 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001879
David Greene4b69d992010-01-05 01:24:57 +00001880 DEBUG(dbgs() << "Emitting bit tests\n");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001881 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1882
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001883 // Optimize the case where all the case values fit in a
1884 // word without having to subtract minValue. In this case,
1885 // we can optimize away the subtraction.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001886 if (minValue.isNonNegative() &&
1887 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1888 cmpRange = maxValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001889 } else {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001890 lowBound = minValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001891 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001892
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001893 CaseBitsVector CasesBits;
1894 unsigned i, count = 0;
1895
1896 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1897 MachineBasicBlock* Dest = I->BB;
1898 for (i = 0; i < count; ++i)
1899 if (Dest == CasesBits[i].BB)
1900 break;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001901
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001902 if (i == count) {
1903 assert((count < 3) && "Too much destinations to test!");
1904 CasesBits.push_back(CaseBits(0, Dest, 0));
1905 count++;
1906 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001907
1908 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1909 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1910
1911 uint64_t lo = (lowValue - lowBound).getZExtValue();
1912 uint64_t hi = (highValue - lowBound).getZExtValue();
1913
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001914 for (uint64_t j = lo; j <= hi; j++) {
1915 CasesBits[i].Mask |= 1ULL << j;
1916 CasesBits[i].Bits++;
1917 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001918
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001919 }
1920 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001921
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001922 BitTestInfo BTC;
1923
1924 // Figure out which block is immediately after the current one.
1925 MachineFunction::iterator BBI = CR.CaseBB;
1926 ++BBI;
1927
1928 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1929
David Greene4b69d992010-01-05 01:24:57 +00001930 DEBUG(dbgs() << "Cases:\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001931 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
David Greene4b69d992010-01-05 01:24:57 +00001932 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001933 << ", Bits: " << CasesBits[i].Bits
1934 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001935
1936 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1937 CurMF->insert(BBI, CaseBB);
1938 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1939 CaseBB,
1940 CasesBits[i].BB));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001941
1942 // Put SV in a virtual register to make it available from the new blocks.
1943 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001944 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001945
1946 BitTestBlock BTB(lowBound, cmpRange, SV,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001947 -1U, (CR.CaseBB == CurMBB),
1948 CR.CaseBB, Default, BTC);
1949
1950 if (CR.CaseBB == CurMBB)
1951 visitBitTestHeader(BTB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001952
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001953 BitTestCases.push_back(BTB);
1954
1955 return true;
1956}
1957
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001958/// Clusterify - Transform simple list of Cases into list of CaseRange's
Dan Gohman2048b852009-11-23 18:04:58 +00001959size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
1960 const SwitchInst& SI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001961 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001962
1963 // Start with "simple" cases
Anton Korobeynikov23218582008-12-23 22:25:27 +00001964 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001965 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1966 Cases.push_back(Case(SI.getSuccessorValue(i),
1967 SI.getSuccessorValue(i),
1968 SMBB));
1969 }
1970 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1971
1972 // Merge case into clusters
Anton Korobeynikov23218582008-12-23 22:25:27 +00001973 if (Cases.size() >= 2)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001974 // Must recompute end() each iteration because it may be
1975 // invalidated by erase if we hold on to it
Anton Korobeynikov23218582008-12-23 22:25:27 +00001976 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
1977 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
1978 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001979 MachineBasicBlock* nextBB = J->BB;
1980 MachineBasicBlock* currentBB = I->BB;
1981
1982 // If the two neighboring cases go to the same destination, merge them
1983 // into a single case.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001984 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001985 I->High = J->High;
1986 J = Cases.erase(J);
1987 } else {
1988 I = J++;
1989 }
1990 }
1991
1992 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1993 if (I->Low != I->High)
1994 // A range counts double, since it requires two compares.
1995 ++numCmps;
1996 }
1997
1998 return numCmps;
1999}
2000
Dan Gohman2048b852009-11-23 18:04:58 +00002001void SelectionDAGBuilder::visitSwitch(SwitchInst &SI) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002002 // Figure out which block is immediately after the current one.
2003 MachineBasicBlock *NextBlock = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002004 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2005
2006 // If there is only the default destination, branch to it if it is not the
2007 // next basic block. Otherwise, just fall through.
2008 if (SI.getNumOperands() == 2) {
2009 // Update machine-CFG edges.
2010
2011 // If this is not a fall-through branch, emit the branch.
2012 CurMBB->addSuccessor(Default);
Bill Wendling4533cac2010-01-28 21:51:40 +00002013 if (Default != NextBlock)
2014 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
2015 MVT::Other, getControlRoot(),
2016 DAG.getBasicBlock(Default)));
Bill Wendling49fcff82009-12-21 22:30:11 +00002017
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002018 return;
2019 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002020
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002021 // If there are any non-default case statements, create a vector of Cases
2022 // representing each one, and sort the vector so that we can efficiently
2023 // create a binary search tree from them.
2024 CaseVector Cases;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002025 size_t numCmps = Clusterify(Cases, SI);
David Greene4b69d992010-01-05 01:24:57 +00002026 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002027 << ". Total compares: " << numCmps << '\n');
Devang Patel8a84e442009-01-05 17:31:22 +00002028 numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002029
2030 // Get the Value to be switched on and default basic blocks, which will be
2031 // inserted into CaseBlock records, representing basic blocks in the binary
2032 // search tree.
2033 Value *SV = SI.getOperand(0);
2034
2035 // Push the initial CaseRec onto the worklist
2036 CaseRecVector WorkList;
2037 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2038
2039 while (!WorkList.empty()) {
2040 // Grab a record representing a case range to process off the worklist
2041 CaseRec CR = WorkList.back();
2042 WorkList.pop_back();
2043
2044 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2045 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002046
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002047 // If the range has few cases (two or less) emit a series of specific
2048 // tests.
2049 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2050 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002051
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002052 // If the switch has more than 5 blocks, and at least 40% dense, and the
2053 // target supports indirect branches, then emit a jump table rather than
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002054 // lowering the switch to a binary tree of conditional branches.
2055 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2056 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002057
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002058 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2059 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2060 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2061 }
2062}
2063
Dan Gohman2048b852009-11-23 18:04:58 +00002064void SelectionDAGBuilder::visitIndirectBr(IndirectBrInst &I) {
Dan Gohmaneef55dc2009-10-27 22:10:34 +00002065 // Update machine-CFG edges.
2066 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
2067 CurMBB->addSuccessor(FuncInfo.MBBMap[I.getSuccessor(i)]);
2068
Bill Wendling4533cac2010-01-28 21:51:40 +00002069 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2070 MVT::Other, getControlRoot(),
2071 getValue(I.getAddress())));
Bill Wendling49fcff82009-12-21 22:30:11 +00002072}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002073
Dan Gohman2048b852009-11-23 18:04:58 +00002074void SelectionDAGBuilder::visitFSub(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002075 // -0.0 - X --> fneg
2076 const Type *Ty = I.getType();
2077 if (isa<VectorType>(Ty)) {
2078 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2079 const VectorType *DestTy = cast<VectorType>(I.getType());
2080 const Type *ElTy = DestTy->getElementType();
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002081 unsigned VL = DestTy->getNumElements();
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002082 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00002083 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002084 if (CV == CNZ) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002085 SDValue Op2 = getValue(I.getOperand(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00002086 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2087 Op2.getValueType(), Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002088 return;
2089 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002090 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002091 }
Bill Wendling49fcff82009-12-21 22:30:11 +00002092
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002093 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002094 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002095 SDValue Op2 = getValue(I.getOperand(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00002096 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2097 Op2.getValueType(), Op2));
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002098 return;
2099 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002100
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002101 visitBinary(I, ISD::FSUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002102}
2103
Dan Gohman2048b852009-11-23 18:04:58 +00002104void SelectionDAGBuilder::visitBinary(User &I, unsigned OpCode) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002105 SDValue Op1 = getValue(I.getOperand(0));
2106 SDValue Op2 = getValue(I.getOperand(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00002107 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2108 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002109}
2110
Dan Gohman2048b852009-11-23 18:04:58 +00002111void SelectionDAGBuilder::visitShift(User &I, unsigned Opcode) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002112 SDValue Op1 = getValue(I.getOperand(0));
2113 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman57fc82d2009-04-09 03:51:29 +00002114 if (!isa<VectorType>(I.getType()) &&
2115 Op2.getValueType() != TLI.getShiftAmountTy()) {
2116 // If the operand is smaller than the shift count type, promote it.
Owen Andersone50ed302009-08-10 22:56:29 +00002117 EVT PTy = TLI.getPointerTy();
2118 EVT STy = TLI.getShiftAmountTy();
Owen Anderson77547be2009-08-10 18:56:59 +00002119 if (STy.bitsGT(Op2.getValueType()))
Dan Gohman57fc82d2009-04-09 03:51:29 +00002120 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2121 TLI.getShiftAmountTy(), Op2);
2122 // If the operand is larger than the shift count type but the shift
2123 // count type has enough bits to represent any shift value, truncate
2124 // it now. This is a common case and it exposes the truncate to
2125 // optimization early.
Owen Anderson77547be2009-08-10 18:56:59 +00002126 else if (STy.getSizeInBits() >=
Dan Gohman57fc82d2009-04-09 03:51:29 +00002127 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2128 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2129 TLI.getShiftAmountTy(), Op2);
2130 // Otherwise we'll need to temporarily settle for some other
2131 // convenient type; type legalization will make adjustments as
2132 // needed.
Owen Anderson77547be2009-08-10 18:56:59 +00002133 else if (PTy.bitsLT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002134 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002135 TLI.getPointerTy(), Op2);
Owen Anderson77547be2009-08-10 18:56:59 +00002136 else if (PTy.bitsGT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002137 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002138 TLI.getPointerTy(), Op2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002139 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002140
Bill Wendling4533cac2010-01-28 21:51:40 +00002141 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2142 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002143}
2144
Dan Gohman2048b852009-11-23 18:04:58 +00002145void SelectionDAGBuilder::visitICmp(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002146 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2147 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2148 predicate = IC->getPredicate();
2149 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2150 predicate = ICmpInst::Predicate(IC->getPredicate());
2151 SDValue Op1 = getValue(I.getOperand(0));
2152 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002153 ISD::CondCode Opcode = getICmpCondCode(predicate);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002154
Owen Andersone50ed302009-08-10 22:56:29 +00002155 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002156 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002157}
2158
Dan Gohman2048b852009-11-23 18:04:58 +00002159void SelectionDAGBuilder::visitFCmp(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002160 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2161 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2162 predicate = FC->getPredicate();
2163 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2164 predicate = FCmpInst::Predicate(FC->getPredicate());
2165 SDValue Op1 = getValue(I.getOperand(0));
2166 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002167 ISD::CondCode Condition = getFCmpCondCode(predicate);
Owen Andersone50ed302009-08-10 22:56:29 +00002168 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002169 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002170}
2171
Dan Gohman2048b852009-11-23 18:04:58 +00002172void SelectionDAGBuilder::visitSelect(User &I) {
Owen Andersone50ed302009-08-10 22:56:29 +00002173 SmallVector<EVT, 4> ValueVTs;
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002174 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2175 unsigned NumValues = ValueVTs.size();
Bill Wendling49fcff82009-12-21 22:30:11 +00002176 if (NumValues == 0) return;
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002177
Bill Wendling49fcff82009-12-21 22:30:11 +00002178 SmallVector<SDValue, 4> Values(NumValues);
2179 SDValue Cond = getValue(I.getOperand(0));
2180 SDValue TrueVal = getValue(I.getOperand(1));
2181 SDValue FalseVal = getValue(I.getOperand(2));
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002182
Bill Wendling4533cac2010-01-28 21:51:40 +00002183 for (unsigned i = 0; i != NumValues; ++i)
Bill Wendling49fcff82009-12-21 22:30:11 +00002184 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2185 TrueVal.getNode()->getValueType(i), Cond,
2186 SDValue(TrueVal.getNode(),
2187 TrueVal.getResNo() + i),
2188 SDValue(FalseVal.getNode(),
2189 FalseVal.getResNo() + i));
2190
Bill Wendling4533cac2010-01-28 21:51:40 +00002191 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2192 DAG.getVTList(&ValueVTs[0], NumValues),
2193 &Values[0], NumValues));
Bill Wendling49fcff82009-12-21 22:30:11 +00002194}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002195
Dan Gohman2048b852009-11-23 18:04:58 +00002196void SelectionDAGBuilder::visitTrunc(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002197 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2198 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002199 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002200 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002201}
2202
Dan Gohman2048b852009-11-23 18:04:58 +00002203void SelectionDAGBuilder::visitZExt(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002204 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2205 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2206 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002207 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002208 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002209}
2210
Dan Gohman2048b852009-11-23 18:04:58 +00002211void SelectionDAGBuilder::visitSExt(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002212 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2213 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2214 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002215 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002216 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002217}
2218
Dan Gohman2048b852009-11-23 18:04:58 +00002219void SelectionDAGBuilder::visitFPTrunc(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002220 // FPTrunc is never a no-op cast, no need to check
2221 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002222 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002223 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2224 DestVT, N, DAG.getIntPtrConstant(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002225}
2226
Dan Gohman2048b852009-11-23 18:04:58 +00002227void SelectionDAGBuilder::visitFPExt(User &I){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002228 // FPTrunc is never a no-op cast, no need to check
2229 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002230 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002231 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002232}
2233
Dan Gohman2048b852009-11-23 18:04:58 +00002234void SelectionDAGBuilder::visitFPToUI(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002235 // FPToUI is never a no-op cast, no need to check
2236 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002237 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002238 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002239}
2240
Dan Gohman2048b852009-11-23 18:04:58 +00002241void SelectionDAGBuilder::visitFPToSI(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002242 // FPToSI is never a no-op cast, no need to check
2243 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002244 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002245 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002246}
2247
Dan Gohman2048b852009-11-23 18:04:58 +00002248void SelectionDAGBuilder::visitUIToFP(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002249 // UIToFP is never a no-op cast, no need to check
2250 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002251 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002252 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002253}
2254
Dan Gohman2048b852009-11-23 18:04:58 +00002255void SelectionDAGBuilder::visitSIToFP(User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002256 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002257 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002258 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002259 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002260}
2261
Dan Gohman2048b852009-11-23 18:04:58 +00002262void SelectionDAGBuilder::visitPtrToInt(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002263 // What to do depends on the size of the integer and the size of the pointer.
2264 // We can either truncate, zero extend, or no-op, accordingly.
2265 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002266 EVT SrcVT = N.getValueType();
2267 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002268 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002269}
2270
Dan Gohman2048b852009-11-23 18:04:58 +00002271void SelectionDAGBuilder::visitIntToPtr(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002272 // What to do depends on the size of the integer and the size of the pointer.
2273 // We can either truncate, zero extend, or no-op, accordingly.
2274 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002275 EVT SrcVT = N.getValueType();
2276 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002277 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002278}
2279
Dan Gohman2048b852009-11-23 18:04:58 +00002280void SelectionDAGBuilder::visitBitCast(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002281 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002282 EVT DestVT = TLI.getValueType(I.getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002283
Bill Wendling49fcff82009-12-21 22:30:11 +00002284 // BitCast assures us that source and destination are the same size so this is
2285 // either a BIT_CONVERT or a no-op.
Bill Wendling4533cac2010-01-28 21:51:40 +00002286 if (DestVT != N.getValueType())
2287 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
2288 DestVT, N)); // convert types.
2289 else
Bill Wendling49fcff82009-12-21 22:30:11 +00002290 setValue(&I, N); // noop cast.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002291}
2292
Dan Gohman2048b852009-11-23 18:04:58 +00002293void SelectionDAGBuilder::visitInsertElement(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002294 SDValue InVec = getValue(I.getOperand(0));
2295 SDValue InVal = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002296 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00002297 TLI.getPointerTy(),
2298 getValue(I.getOperand(2)));
Bill Wendling4533cac2010-01-28 21:51:40 +00002299 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2300 TLI.getValueType(I.getType()),
2301 InVec, InVal, InIdx));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002302}
2303
Dan Gohman2048b852009-11-23 18:04:58 +00002304void SelectionDAGBuilder::visitExtractElement(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002305 SDValue InVec = getValue(I.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00002306 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00002307 TLI.getPointerTy(),
2308 getValue(I.getOperand(1)));
Bill Wendling4533cac2010-01-28 21:51:40 +00002309 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2310 TLI.getValueType(I.getType()), InVec, InIdx));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002311}
2312
Mon P Wangaeb06d22008-11-10 04:46:22 +00002313// Utility for visitShuffleVector - Returns true if the mask is mask starting
2314// from SIndx and increasing to the element length (undefs are allowed).
Nate Begeman5a5ca152009-04-29 05:20:52 +00002315static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2316 unsigned MaskNumElts = Mask.size();
2317 for (unsigned i = 0; i != MaskNumElts; ++i)
2318 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
Nate Begeman9008ca62009-04-27 18:41:29 +00002319 return false;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002320 return true;
2321}
2322
Dan Gohman2048b852009-11-23 18:04:58 +00002323void SelectionDAGBuilder::visitShuffleVector(User &I) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002324 SmallVector<int, 8> Mask;
Mon P Wang230e4fa2008-11-21 04:25:21 +00002325 SDValue Src1 = getValue(I.getOperand(0));
2326 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002327
Nate Begeman9008ca62009-04-27 18:41:29 +00002328 // Convert the ConstantVector mask operand into an array of ints, with -1
2329 // representing undef values.
2330 SmallVector<Constant*, 8> MaskElts;
Chris Lattnerb29d5962010-02-01 20:48:08 +00002331 cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
Nate Begeman5a5ca152009-04-29 05:20:52 +00002332 unsigned MaskNumElts = MaskElts.size();
2333 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002334 if (isa<UndefValue>(MaskElts[i]))
2335 Mask.push_back(-1);
2336 else
2337 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2338 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002339
Owen Andersone50ed302009-08-10 22:56:29 +00002340 EVT VT = TLI.getValueType(I.getType());
2341 EVT SrcVT = Src1.getValueType();
Nate Begeman5a5ca152009-04-29 05:20:52 +00002342 unsigned SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002343
Mon P Wangc7849c22008-11-16 05:06:27 +00002344 if (SrcNumElts == MaskNumElts) {
Bill Wendling4533cac2010-01-28 21:51:40 +00002345 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2346 &Mask[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002347 return;
2348 }
2349
2350 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002351 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2352 // Mask is longer than the source vectors and is a multiple of the source
2353 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang230e4fa2008-11-21 04:25:21 +00002354 // lengths match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002355 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2356 // The shuffle is concatenating two vectors together.
Bill Wendling4533cac2010-01-28 21:51:40 +00002357 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2358 VT, Src1, Src2));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002359 return;
2360 }
2361
Mon P Wangc7849c22008-11-16 05:06:27 +00002362 // Pad both vectors with undefs to make them the same length as the mask.
2363 unsigned NumConcat = MaskNumElts / SrcNumElts;
Nate Begeman9008ca62009-04-27 18:41:29 +00002364 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2365 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
Dale Johannesene8d72302009-02-06 23:05:02 +00002366 SDValue UndefVal = DAG.getUNDEF(SrcVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002367
Nate Begeman9008ca62009-04-27 18:41:29 +00002368 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2369 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002370 MOps1[0] = Src1;
2371 MOps2[0] = Src2;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002372
2373 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2374 getCurDebugLoc(), VT,
Nate Begeman9008ca62009-04-27 18:41:29 +00002375 &MOps1[0], NumConcat);
2376 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002377 getCurDebugLoc(), VT,
Nate Begeman9008ca62009-04-27 18:41:29 +00002378 &MOps2[0], NumConcat);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002379
Mon P Wangaeb06d22008-11-10 04:46:22 +00002380 // Readjust mask for new input vector length.
Nate Begeman9008ca62009-04-27 18:41:29 +00002381 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002382 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002383 int Idx = Mask[i];
Nate Begeman5a5ca152009-04-29 05:20:52 +00002384 if (Idx < (int)SrcNumElts)
Nate Begeman9008ca62009-04-27 18:41:29 +00002385 MappedOps.push_back(Idx);
2386 else
2387 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002388 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002389
Bill Wendling4533cac2010-01-28 21:51:40 +00002390 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2391 &MappedOps[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002392 return;
2393 }
2394
Mon P Wangc7849c22008-11-16 05:06:27 +00002395 if (SrcNumElts > MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002396 // Analyze the access pattern of the vector to see if we can extract
2397 // two subvectors and do the shuffle. The analysis is done by calculating
2398 // the range of elements the mask access on both vectors.
2399 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2400 int MaxRange[2] = {-1, -1};
2401
Nate Begeman5a5ca152009-04-29 05:20:52 +00002402 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002403 int Idx = Mask[i];
2404 int Input = 0;
2405 if (Idx < 0)
2406 continue;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002407
Nate Begeman5a5ca152009-04-29 05:20:52 +00002408 if (Idx >= (int)SrcNumElts) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002409 Input = 1;
2410 Idx -= SrcNumElts;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002411 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002412 if (Idx > MaxRange[Input])
2413 MaxRange[Input] = Idx;
2414 if (Idx < MinRange[Input])
2415 MinRange[Input] = Idx;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002416 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002417
Mon P Wangc7849c22008-11-16 05:06:27 +00002418 // Check if the access is smaller than the vector size and can we find
2419 // a reasonable extract index.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002420 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not
2421 // Extract.
Mon P Wangc7849c22008-11-16 05:06:27 +00002422 int StartIdx[2]; // StartIdx to extract from
2423 for (int Input=0; Input < 2; ++Input) {
Nate Begeman5a5ca152009-04-29 05:20:52 +00002424 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002425 RangeUse[Input] = 0; // Unused
2426 StartIdx[Input] = 0;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002427 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002428 // Fits within range but we should see if we can find a good
Mon P Wang230e4fa2008-11-21 04:25:21 +00002429 // start index that is a multiple of the mask length.
Nate Begeman5a5ca152009-04-29 05:20:52 +00002430 if (MaxRange[Input] < (int)MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002431 RangeUse[Input] = 1; // Extract from beginning of the vector
2432 StartIdx[Input] = 0;
2433 } else {
2434 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002435 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002436 StartIdx[Input] + MaskNumElts < SrcNumElts)
Mon P Wangc7849c22008-11-16 05:06:27 +00002437 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002438 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002439 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002440 }
2441
Bill Wendling636e2582009-08-21 18:16:06 +00002442 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
Bill Wendling4533cac2010-01-28 21:51:40 +00002443 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
Mon P Wangc7849c22008-11-16 05:06:27 +00002444 return;
2445 }
2446 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2447 // Extract appropriate subvector and generate a vector shuffle
2448 for (int Input=0; Input < 2; ++Input) {
Bill Wendling87710f02009-12-21 23:47:40 +00002449 SDValue &Src = Input == 0 ? Src1 : Src2;
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002450 if (RangeUse[Input] == 0)
Dale Johannesene8d72302009-02-06 23:05:02 +00002451 Src = DAG.getUNDEF(VT);
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002452 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00002453 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002454 Src, DAG.getIntPtrConstant(StartIdx[Input]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002455 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002456
Mon P Wangc7849c22008-11-16 05:06:27 +00002457 // Calculate new mask.
Nate Begeman9008ca62009-04-27 18:41:29 +00002458 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002459 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002460 int Idx = Mask[i];
2461 if (Idx < 0)
2462 MappedOps.push_back(Idx);
Nate Begeman5a5ca152009-04-29 05:20:52 +00002463 else if (Idx < (int)SrcNumElts)
Nate Begeman9008ca62009-04-27 18:41:29 +00002464 MappedOps.push_back(Idx - StartIdx[0]);
2465 else
2466 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
Mon P Wangc7849c22008-11-16 05:06:27 +00002467 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002468
Bill Wendling4533cac2010-01-28 21:51:40 +00002469 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2470 &MappedOps[0]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002471 return;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002472 }
2473 }
2474
Mon P Wangc7849c22008-11-16 05:06:27 +00002475 // We can't use either concat vectors or extract subvectors so fall back to
2476 // replacing the shuffle with extract and build vector.
2477 // to insert and build vector.
Owen Andersone50ed302009-08-10 22:56:29 +00002478 EVT EltVT = VT.getVectorElementType();
2479 EVT PtrVT = TLI.getPointerTy();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002480 SmallVector<SDValue,8> Ops;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002481 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002482 if (Mask[i] < 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002483 Ops.push_back(DAG.getUNDEF(EltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002484 } else {
Nate Begeman9008ca62009-04-27 18:41:29 +00002485 int Idx = Mask[i];
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002486 SDValue Res;
2487
Nate Begeman5a5ca152009-04-29 05:20:52 +00002488 if (Idx < (int)SrcNumElts)
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002489 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2490 EltVT, Src1, DAG.getConstant(Idx, PtrVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002491 else
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002492 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2493 EltVT, Src2,
2494 DAG.getConstant(Idx - SrcNumElts, PtrVT));
2495
2496 Ops.push_back(Res);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002497 }
2498 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002499
Bill Wendling4533cac2010-01-28 21:51:40 +00002500 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2501 VT, &Ops[0], Ops.size()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002502}
2503
Dan Gohman2048b852009-11-23 18:04:58 +00002504void SelectionDAGBuilder::visitInsertValue(InsertValueInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002505 const Value *Op0 = I.getOperand(0);
2506 const Value *Op1 = I.getOperand(1);
2507 const Type *AggTy = I.getType();
2508 const Type *ValTy = Op1->getType();
2509 bool IntoUndef = isa<UndefValue>(Op0);
2510 bool FromUndef = isa<UndefValue>(Op1);
2511
2512 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2513 I.idx_begin(), I.idx_end());
2514
Owen Andersone50ed302009-08-10 22:56:29 +00002515 SmallVector<EVT, 4> AggValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002516 ComputeValueVTs(TLI, AggTy, AggValueVTs);
Owen Andersone50ed302009-08-10 22:56:29 +00002517 SmallVector<EVT, 4> ValValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002518 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2519
2520 unsigned NumAggValues = AggValueVTs.size();
2521 unsigned NumValValues = ValValueVTs.size();
2522 SmallVector<SDValue, 4> Values(NumAggValues);
2523
2524 SDValue Agg = getValue(Op0);
2525 SDValue Val = getValue(Op1);
2526 unsigned i = 0;
2527 // Copy the beginning value(s) from the original aggregate.
2528 for (; i != LinearIndex; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002529 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002530 SDValue(Agg.getNode(), Agg.getResNo() + i);
2531 // Copy values from the inserted value(s).
2532 for (; i != LinearIndex + NumValValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002533 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002534 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2535 // Copy remaining value(s) from the original aggregate.
2536 for (; i != NumAggValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002537 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002538 SDValue(Agg.getNode(), Agg.getResNo() + i);
2539
Bill Wendling4533cac2010-01-28 21:51:40 +00002540 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2541 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2542 &Values[0], NumAggValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002543}
2544
Dan Gohman2048b852009-11-23 18:04:58 +00002545void SelectionDAGBuilder::visitExtractValue(ExtractValueInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002546 const Value *Op0 = I.getOperand(0);
2547 const Type *AggTy = Op0->getType();
2548 const Type *ValTy = I.getType();
2549 bool OutOfUndef = isa<UndefValue>(Op0);
2550
2551 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2552 I.idx_begin(), I.idx_end());
2553
Owen Andersone50ed302009-08-10 22:56:29 +00002554 SmallVector<EVT, 4> ValValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002555 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2556
2557 unsigned NumValValues = ValValueVTs.size();
2558 SmallVector<SDValue, 4> Values(NumValValues);
2559
2560 SDValue Agg = getValue(Op0);
2561 // Copy out the selected value(s).
2562 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2563 Values[i - LinearIndex] =
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002564 OutOfUndef ?
Dale Johannesene8d72302009-02-06 23:05:02 +00002565 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002566 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002567
Bill Wendling4533cac2010-01-28 21:51:40 +00002568 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2569 DAG.getVTList(&ValValueVTs[0], NumValValues),
2570 &Values[0], NumValValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002571}
2572
Dan Gohman2048b852009-11-23 18:04:58 +00002573void SelectionDAGBuilder::visitGetElementPtr(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002574 SDValue N = getValue(I.getOperand(0));
2575 const Type *Ty = I.getOperand(0)->getType();
2576
2577 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2578 OI != E; ++OI) {
2579 Value *Idx = *OI;
2580 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2581 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2582 if (Field) {
2583 // N = N + Offset
2584 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002585 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002586 DAG.getIntPtrConstant(Offset));
2587 }
Bill Wendlinge1a90422009-12-21 23:10:19 +00002588
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002589 Ty = StTy->getElementType(Field);
2590 } else {
2591 Ty = cast<SequentialType>(Ty)->getElementType();
2592
2593 // If this is a constant subscript, handle it quickly.
2594 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2595 if (CI->getZExtValue() == 0) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002596 uint64_t Offs =
Duncan Sands777d2302009-05-09 07:06:46 +00002597 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Evan Cheng65b52df2009-02-09 21:01:06 +00002598 SDValue OffsVal;
Owen Andersone50ed302009-08-10 22:56:29 +00002599 EVT PTy = TLI.getPointerTy();
Owen Anderson77547be2009-08-10 18:56:59 +00002600 unsigned PtrBits = PTy.getSizeInBits();
Bill Wendlinge1a90422009-12-21 23:10:19 +00002601 if (PtrBits < 64)
Evan Cheng65b52df2009-02-09 21:01:06 +00002602 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2603 TLI.getPointerTy(),
Owen Anderson825b72b2009-08-11 20:47:22 +00002604 DAG.getConstant(Offs, MVT::i64));
Bill Wendlinge1a90422009-12-21 23:10:19 +00002605 else
Evan Chengb1032a82009-02-09 20:54:38 +00002606 OffsVal = DAG.getIntPtrConstant(Offs);
Bill Wendlinge1a90422009-12-21 23:10:19 +00002607
Dale Johannesen66978ee2009-01-31 02:22:37 +00002608 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Evan Chengb1032a82009-02-09 20:54:38 +00002609 OffsVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002610 continue;
2611 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002612
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002613 // N = N + Idx * ElementSize;
Dan Gohman7abbd042009-10-23 17:57:43 +00002614 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
2615 TD->getTypeAllocSize(Ty));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002616 SDValue IdxN = getValue(Idx);
2617
2618 // If the index is smaller or larger than intptr_t, truncate or extend
2619 // it.
Duncan Sands3a66a682009-10-13 21:04:12 +00002620 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002621
2622 // If this is a multiply by a power of two, turn it into a shl
2623 // immediately. This is a very common case.
2624 if (ElementSize != 1) {
Dan Gohman7abbd042009-10-23 17:57:43 +00002625 if (ElementSize.isPowerOf2()) {
2626 unsigned Amt = ElementSize.logBase2();
Scott Michelfdc40a02009-02-17 22:15:04 +00002627 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002628 N.getValueType(), IdxN,
Duncan Sands92abc622009-01-31 15:50:11 +00002629 DAG.getConstant(Amt, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002630 } else {
Dan Gohman7abbd042009-10-23 17:57:43 +00002631 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
Scott Michelfdc40a02009-02-17 22:15:04 +00002632 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002633 N.getValueType(), IdxN, Scale);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002634 }
2635 }
2636
Scott Michelfdc40a02009-02-17 22:15:04 +00002637 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002638 N.getValueType(), N, IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002639 }
2640 }
Bill Wendlinge1a90422009-12-21 23:10:19 +00002641
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002642 setValue(&I, N);
2643}
2644
Dan Gohman2048b852009-11-23 18:04:58 +00002645void SelectionDAGBuilder::visitAlloca(AllocaInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002646 // If this is a fixed sized alloca in the entry block of the function,
2647 // allocate it statically on the stack.
2648 if (FuncInfo.StaticAllocaMap.count(&I))
2649 return; // getValue will auto-populate this.
2650
2651 const Type *Ty = I.getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002652 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002653 unsigned Align =
2654 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2655 I.getAlignment());
2656
2657 SDValue AllocSize = getValue(I.getArraySize());
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002658
Chris Lattner0b18e592009-03-17 19:36:00 +00002659 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2660 AllocSize,
2661 DAG.getConstant(TySize, AllocSize.getValueType()));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002662
Owen Andersone50ed302009-08-10 22:56:29 +00002663 EVT IntPtr = TLI.getPointerTy();
Duncan Sands3a66a682009-10-13 21:04:12 +00002664 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002665
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002666 // Handle alignment. If the requested alignment is less than or equal to
2667 // the stack alignment, ignore it. If the size is greater than or equal to
2668 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2669 unsigned StackAlign =
2670 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2671 if (Align <= StackAlign)
2672 Align = 0;
2673
2674 // Round the size of the allocation up to the stack alignment size
2675 // by add SA-1 to the size.
Scott Michelfdc40a02009-02-17 22:15:04 +00002676 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002677 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002678 DAG.getIntPtrConstant(StackAlign-1));
Bill Wendling856ff412009-12-22 00:12:37 +00002679
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002680 // Mask out the low bits for alignment purposes.
Scott Michelfdc40a02009-02-17 22:15:04 +00002681 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002682 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002683 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2684
2685 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Owen Anderson825b72b2009-08-11 20:47:22 +00002686 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
Scott Michelfdc40a02009-02-17 22:15:04 +00002687 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002688 VTs, Ops, 3);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002689 setValue(&I, DSA);
2690 DAG.setRoot(DSA.getValue(1));
Bill Wendling856ff412009-12-22 00:12:37 +00002691
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002692 // Inform the Frame Information that we have just allocated a variable-sized
2693 // object.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00002694 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002695}
2696
Dan Gohman2048b852009-11-23 18:04:58 +00002697void SelectionDAGBuilder::visitLoad(LoadInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002698 const Value *SV = I.getOperand(0);
2699 SDValue Ptr = getValue(SV);
2700
2701 const Type *Ty = I.getType();
2702 bool isVolatile = I.isVolatile();
2703 unsigned Alignment = I.getAlignment();
2704
Owen Andersone50ed302009-08-10 22:56:29 +00002705 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002706 SmallVector<uint64_t, 4> Offsets;
2707 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2708 unsigned NumValues = ValueVTs.size();
2709 if (NumValues == 0)
2710 return;
2711
2712 SDValue Root;
2713 bool ConstantMemory = false;
2714 if (I.isVolatile())
2715 // Serialize volatile loads with other side effects.
2716 Root = getRoot();
2717 else if (AA->pointsToConstantMemory(SV)) {
2718 // Do not serialize (non-volatile) loads of constant memory with anything.
2719 Root = DAG.getEntryNode();
2720 ConstantMemory = true;
2721 } else {
2722 // Do not serialize non-volatile loads against each other.
2723 Root = DAG.getRoot();
2724 }
2725
2726 SmallVector<SDValue, 4> Values(NumValues);
2727 SmallVector<SDValue, 4> Chains(NumValues);
Owen Andersone50ed302009-08-10 22:56:29 +00002728 EVT PtrVT = Ptr.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002729 for (unsigned i = 0; i != NumValues; ++i) {
Bill Wendling856ff412009-12-22 00:12:37 +00002730 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2731 PtrVT, Ptr,
2732 DAG.getConstant(Offsets[i], PtrVT));
Dale Johannesen66978ee2009-01-31 02:22:37 +00002733 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
Bill Wendling856ff412009-12-22 00:12:37 +00002734 A, SV, Offsets[i], isVolatile, Alignment);
2735
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002736 Values[i] = L;
2737 Chains[i] = L.getValue(1);
2738 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002739
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002740 if (!ConstantMemory) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002741 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Bill Wendling856ff412009-12-22 00:12:37 +00002742 MVT::Other, &Chains[0], NumValues);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002743 if (isVolatile)
2744 DAG.setRoot(Chain);
2745 else
2746 PendingLoads.push_back(Chain);
2747 }
2748
Bill Wendling4533cac2010-01-28 21:51:40 +00002749 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2750 DAG.getVTList(&ValueVTs[0], NumValues),
2751 &Values[0], NumValues));
Bill Wendling856ff412009-12-22 00:12:37 +00002752}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002753
Dan Gohman2048b852009-11-23 18:04:58 +00002754void SelectionDAGBuilder::visitStore(StoreInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002755 Value *SrcV = I.getOperand(0);
2756 Value *PtrV = I.getOperand(1);
2757
Owen Andersone50ed302009-08-10 22:56:29 +00002758 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002759 SmallVector<uint64_t, 4> Offsets;
2760 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2761 unsigned NumValues = ValueVTs.size();
2762 if (NumValues == 0)
2763 return;
2764
2765 // Get the lowered operands. Note that we do this after
2766 // checking if NumResults is zero, because with zero results
2767 // the operands won't have values in the map.
2768 SDValue Src = getValue(SrcV);
2769 SDValue Ptr = getValue(PtrV);
2770
2771 SDValue Root = getRoot();
2772 SmallVector<SDValue, 4> Chains(NumValues);
Owen Andersone50ed302009-08-10 22:56:29 +00002773 EVT PtrVT = Ptr.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002774 bool isVolatile = I.isVolatile();
2775 unsigned Alignment = I.getAlignment();
Bill Wendling856ff412009-12-22 00:12:37 +00002776
2777 for (unsigned i = 0; i != NumValues; ++i) {
2778 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
2779 DAG.getConstant(Offsets[i], PtrVT));
Dale Johannesen66978ee2009-01-31 02:22:37 +00002780 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002781 SDValue(Src.getNode(), Src.getResNo() + i),
Bill Wendling856ff412009-12-22 00:12:37 +00002782 Add, PtrV, Offsets[i], isVolatile, Alignment);
Bill Wendling856ff412009-12-22 00:12:37 +00002783 }
2784
Bill Wendling4533cac2010-01-28 21:51:40 +00002785 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2786 MVT::Other, &Chains[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002787}
2788
2789/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2790/// node.
Dan Gohman2048b852009-11-23 18:04:58 +00002791void SelectionDAGBuilder::visitTargetIntrinsic(CallInst &I,
2792 unsigned Intrinsic) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002793 bool HasChain = !I.doesNotAccessMemory();
2794 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2795
2796 // Build the operand list.
2797 SmallVector<SDValue, 8> Ops;
2798 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2799 if (OnlyLoad) {
2800 // We don't need to serialize loads against other loads.
2801 Ops.push_back(DAG.getRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002802 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002803 Ops.push_back(getRoot());
2804 }
2805 }
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002806
2807 // Info is set by getTgtMemInstrinsic
2808 TargetLowering::IntrinsicInfo Info;
2809 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2810
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002811 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002812 if (!IsTgtIntrinsic)
2813 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002814
2815 // Add all operands of the call to the operand list.
2816 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2817 SDValue Op = getValue(I.getOperand(i));
2818 assert(TLI.isTypeLegal(Op.getValueType()) &&
2819 "Intrinsic uses a non-legal type?");
2820 Ops.push_back(Op);
2821 }
2822
Owen Andersone50ed302009-08-10 22:56:29 +00002823 SmallVector<EVT, 4> ValueVTs;
Bob Wilson8d919552009-07-31 22:41:21 +00002824 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2825#ifndef NDEBUG
2826 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
2827 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
2828 "Intrinsic uses a non-legal type?");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002829 }
Bob Wilson8d919552009-07-31 22:41:21 +00002830#endif // NDEBUG
Bill Wendling856ff412009-12-22 00:12:37 +00002831
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002832 if (HasChain)
Owen Anderson825b72b2009-08-11 20:47:22 +00002833 ValueVTs.push_back(MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002834
Bob Wilson8d919552009-07-31 22:41:21 +00002835 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002836
2837 // Create the node.
2838 SDValue Result;
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002839 if (IsTgtIntrinsic) {
2840 // This is target intrinsic that touches memory
Dale Johannesen66978ee2009-01-31 02:22:37 +00002841 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002842 VTs, &Ops[0], Ops.size(),
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002843 Info.memVT, Info.ptrVal, Info.offset,
2844 Info.align, Info.vol,
2845 Info.readMem, Info.writeMem);
Bill Wendling856ff412009-12-22 00:12:37 +00002846 } else if (!HasChain) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002847 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002848 VTs, &Ops[0], Ops.size());
Benjamin Kramerf0127052010-01-05 13:12:22 +00002849 } else if (!I.getType()->isVoidTy()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002850 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002851 VTs, &Ops[0], Ops.size());
Bill Wendling856ff412009-12-22 00:12:37 +00002852 } else {
Scott Michelfdc40a02009-02-17 22:15:04 +00002853 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002854 VTs, &Ops[0], Ops.size());
Bill Wendling856ff412009-12-22 00:12:37 +00002855 }
2856
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002857 if (HasChain) {
2858 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2859 if (OnlyLoad)
2860 PendingLoads.push_back(Chain);
2861 else
2862 DAG.setRoot(Chain);
2863 }
Bill Wendling856ff412009-12-22 00:12:37 +00002864
Benjamin Kramerf0127052010-01-05 13:12:22 +00002865 if (!I.getType()->isVoidTy()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002866 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Owen Andersone50ed302009-08-10 22:56:29 +00002867 EVT VT = TLI.getValueType(PTy);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002868 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002869 }
Bill Wendling856ff412009-12-22 00:12:37 +00002870
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002871 setValue(&I, Result);
2872 }
2873}
2874
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002875/// GetSignificand - Get the significand and build it into a floating-point
2876/// number with exponent of 1:
2877///
2878/// Op = (Op & 0x007fffff) | 0x3f800000;
2879///
2880/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002881static SDValue
Bill Wendling856ff412009-12-22 00:12:37 +00002882GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl, unsigned Order) {
Owen Anderson825b72b2009-08-11 20:47:22 +00002883 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
2884 DAG.getConstant(0x007fffff, MVT::i32));
2885 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
2886 DAG.getConstant(0x3f800000, MVT::i32));
Bill Wendling4533cac2010-01-28 21:51:40 +00002887 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00002888}
2889
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002890/// GetExponent - Get the exponent:
2891///
Bill Wendlinge9a72862009-01-20 21:17:57 +00002892/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002893///
2894/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002895static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00002896GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
Bill Wendling856ff412009-12-22 00:12:37 +00002897 DebugLoc dl, unsigned Order) {
Owen Anderson825b72b2009-08-11 20:47:22 +00002898 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
2899 DAG.getConstant(0x7f800000, MVT::i32));
2900 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
Duncan Sands92abc622009-01-31 15:50:11 +00002901 DAG.getConstant(23, TLI.getPointerTy()));
Owen Anderson825b72b2009-08-11 20:47:22 +00002902 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
2903 DAG.getConstant(127, MVT::i32));
Bill Wendling4533cac2010-01-28 21:51:40 +00002904 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00002905}
2906
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002907/// getF32Constant - Get 32-bit floating point constant.
2908static SDValue
2909getF32Constant(SelectionDAG &DAG, unsigned Flt) {
Owen Anderson825b72b2009-08-11 20:47:22 +00002910 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002911}
2912
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002913/// Inlined utility function to implement binary input atomic intrinsics for
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002914/// visitIntrinsicCall: I is a call instruction
2915/// Op is the associated NodeType for I
2916const char *
Dan Gohman2048b852009-11-23 18:04:58 +00002917SelectionDAGBuilder::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002918 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00002919 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00002920 DAG.getAtomic(Op, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002921 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00002922 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002923 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00002924 getValue(I.getOperand(2)),
2925 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002926 setValue(&I, L);
2927 DAG.setRoot(L.getValue(1));
2928 return 0;
2929}
2930
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002931// implVisitAluOverflow - Lower arithmetic overflow instrinsics.
Bill Wendling74c37652008-12-09 22:08:41 +00002932const char *
Dan Gohman2048b852009-11-23 18:04:58 +00002933SelectionDAGBuilder::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002934 SDValue Op1 = getValue(I.getOperand(1));
2935 SDValue Op2 = getValue(I.getOperand(2));
Bill Wendling74c37652008-12-09 22:08:41 +00002936
Owen Anderson825b72b2009-08-11 20:47:22 +00002937 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
Bill Wendling4533cac2010-01-28 21:51:40 +00002938 setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2));
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002939 return 0;
2940}
Bill Wendling74c37652008-12-09 22:08:41 +00002941
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002942/// visitExp - Lower an exp intrinsic. Handles the special sequences for
2943/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00002944void
Dan Gohman2048b852009-11-23 18:04:58 +00002945SelectionDAGBuilder::visitExp(CallInst &I) {
Dale Johannesen59e577f2008-09-05 18:38:42 +00002946 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00002947 DebugLoc dl = getCurDebugLoc();
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002948
Owen Anderson825b72b2009-08-11 20:47:22 +00002949 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002950 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2951 SDValue Op = getValue(I.getOperand(1));
2952
2953 // Put the exponent in the right bit position for later addition to the
2954 // final result:
2955 //
2956 // #define LOG2OFe 1.4426950f
2957 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
Owen Anderson825b72b2009-08-11 20:47:22 +00002958 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002959 getF32Constant(DAG, 0x3fb8aa3b));
Owen Anderson825b72b2009-08-11 20:47:22 +00002960 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002961
2962 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00002963 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
2964 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002965
2966 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00002967 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00002968 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendling856ff412009-12-22 00:12:37 +00002969
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002970 if (LimitFloatPrecision <= 6) {
2971 // For floating-point precision of 6:
2972 //
2973 // TwoToFractionalPartOfX =
2974 // 0.997535578f +
2975 // (0.735607626f + 0.252464424f * x) * x;
2976 //
2977 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00002978 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002979 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00002980 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002981 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00002982 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
2983 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002984 getF32Constant(DAG, 0x3f7f5e7e));
Owen Anderson825b72b2009-08-11 20:47:22 +00002985 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002986
2987 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00002988 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002989 TwoToFracPartOfX, IntegerPartOfX);
2990
Owen Anderson825b72b2009-08-11 20:47:22 +00002991 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002992 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
2993 // For floating-point precision of 12:
2994 //
2995 // TwoToFractionalPartOfX =
2996 // 0.999892986f +
2997 // (0.696457318f +
2998 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
2999 //
3000 // 0.000107046256 error, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003001 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003002 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003003 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003004 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003005 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3006 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003007 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00003008 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3009 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003010 getF32Constant(DAG, 0x3f7ff8fd));
Owen Anderson825b72b2009-08-11 20:47:22 +00003011 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003012
3013 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00003014 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003015 TwoToFracPartOfX, IntegerPartOfX);
3016
Owen Anderson825b72b2009-08-11 20:47:22 +00003017 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003018 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3019 // For floating-point precision of 18:
3020 //
3021 // TwoToFractionalPartOfX =
3022 // 0.999999982f +
3023 // (0.693148872f +
3024 // (0.240227044f +
3025 // (0.554906021e-1f +
3026 // (0.961591928e-2f +
3027 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3028 //
3029 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003030 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003031 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003032 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003033 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003034 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3035 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003036 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003037 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3038 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003039 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003040 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3041 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003042 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003043 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3044 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003045 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003046 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3047 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003048 getF32Constant(DAG, 0x3f800000));
Scott Michelfdc40a02009-02-17 22:15:04 +00003049 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003050 MVT::i32, t13);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003051
3052 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00003053 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003054 TwoToFracPartOfX, IntegerPartOfX);
3055
Owen Anderson825b72b2009-08-11 20:47:22 +00003056 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003057 }
3058 } else {
3059 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003060 result = DAG.getNode(ISD::FEXP, dl,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003061 getValue(I.getOperand(1)).getValueType(),
3062 getValue(I.getOperand(1)));
3063 }
3064
Dale Johannesen59e577f2008-09-05 18:38:42 +00003065 setValue(&I, result);
3066}
3067
Bill Wendling39150252008-09-09 20:39:27 +00003068/// visitLog - Lower a log intrinsic. Handles the special sequences for
3069/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003070void
Dan Gohman2048b852009-11-23 18:04:58 +00003071SelectionDAGBuilder::visitLog(CallInst &I) {
Dale Johannesen59e577f2008-09-05 18:38:42 +00003072 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003073 DebugLoc dl = getCurDebugLoc();
Bill Wendling39150252008-09-09 20:39:27 +00003074
Owen Anderson825b72b2009-08-11 20:47:22 +00003075 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling39150252008-09-09 20:39:27 +00003076 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3077 SDValue Op = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003078 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling39150252008-09-09 20:39:27 +00003079
3080 // Scale the exponent by log(2) [0.69314718f].
Bill Wendling856ff412009-12-22 00:12:37 +00003081 SDValue Exp = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
Owen Anderson825b72b2009-08-11 20:47:22 +00003082 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003083 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003084
3085 // Get the significand and build it into a floating-point number with
3086 // exponent of 1.
Bill Wendling856ff412009-12-22 00:12:37 +00003087 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
Bill Wendling39150252008-09-09 20:39:27 +00003088
3089 if (LimitFloatPrecision <= 6) {
3090 // For floating-point precision of 6:
3091 //
3092 // LogofMantissa =
3093 // -1.1609546f +
3094 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003095 //
Bill Wendling39150252008-09-09 20:39:27 +00003096 // error 0.0034276066, which is better than 8 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003097 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003098 getF32Constant(DAG, 0xbe74c456));
Owen Anderson825b72b2009-08-11 20:47:22 +00003099 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003100 getF32Constant(DAG, 0x3fb3a2b1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003101 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3102 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003103 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00003104
Scott Michelfdc40a02009-02-17 22:15:04 +00003105 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003106 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003107 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3108 // For floating-point precision of 12:
3109 //
3110 // LogOfMantissa =
3111 // -1.7417939f +
3112 // (2.8212026f +
3113 // (-1.4699568f +
3114 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3115 //
3116 // error 0.000061011436, which is 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003117 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003118 getF32Constant(DAG, 0xbd67b6d6));
Owen Anderson825b72b2009-08-11 20:47:22 +00003119 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003120 getF32Constant(DAG, 0x3ee4f4b8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003121 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3122 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003123 getF32Constant(DAG, 0x3fbc278b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003124 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3125 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003126 getF32Constant(DAG, 0x40348e95));
Owen Anderson825b72b2009-08-11 20:47:22 +00003127 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3128 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003129 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00003130
Scott Michelfdc40a02009-02-17 22:15:04 +00003131 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003132 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003133 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3134 // For floating-point precision of 18:
3135 //
3136 // LogOfMantissa =
3137 // -2.1072184f +
3138 // (4.2372794f +
3139 // (-3.7029485f +
3140 // (2.2781945f +
3141 // (-0.87823314f +
3142 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3143 //
3144 // error 0.0000023660568, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003145 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003146 getF32Constant(DAG, 0xbc91e5ac));
Owen Anderson825b72b2009-08-11 20:47:22 +00003147 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003148 getF32Constant(DAG, 0x3e4350aa));
Owen Anderson825b72b2009-08-11 20:47:22 +00003149 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3150 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003151 getF32Constant(DAG, 0x3f60d3e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003152 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3153 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003154 getF32Constant(DAG, 0x4011cdf0));
Owen Anderson825b72b2009-08-11 20:47:22 +00003155 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3156 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003157 getF32Constant(DAG, 0x406cfd1c));
Owen Anderson825b72b2009-08-11 20:47:22 +00003158 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3159 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003160 getF32Constant(DAG, 0x408797cb));
Owen Anderson825b72b2009-08-11 20:47:22 +00003161 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3162 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003163 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003164
Scott Michelfdc40a02009-02-17 22:15:04 +00003165 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003166 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003167 }
3168 } else {
3169 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003170 result = DAG.getNode(ISD::FLOG, dl,
Bill Wendling39150252008-09-09 20:39:27 +00003171 getValue(I.getOperand(1)).getValueType(),
3172 getValue(I.getOperand(1)));
3173 }
3174
Dale Johannesen59e577f2008-09-05 18:38:42 +00003175 setValue(&I, result);
3176}
3177
Bill Wendling3eb59402008-09-09 00:28:24 +00003178/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3179/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003180void
Dan Gohman2048b852009-11-23 18:04:58 +00003181SelectionDAGBuilder::visitLog2(CallInst &I) {
Dale Johannesen59e577f2008-09-05 18:38:42 +00003182 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003183 DebugLoc dl = getCurDebugLoc();
Bill Wendling3eb59402008-09-09 00:28:24 +00003184
Owen Anderson825b72b2009-08-11 20:47:22 +00003185 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003186 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3187 SDValue Op = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003188 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003189
Bill Wendling39150252008-09-09 20:39:27 +00003190 // Get the exponent.
Bill Wendling856ff412009-12-22 00:12:37 +00003191 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
3192
Bill Wendling3eb59402008-09-09 00:28:24 +00003193 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003194 // exponent of 1.
Bill Wendling856ff412009-12-22 00:12:37 +00003195 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003196
Bill Wendling3eb59402008-09-09 00:28:24 +00003197 // Different possible minimax approximations of significand in
3198 // floating-point for various degrees of accuracy over [1,2].
3199 if (LimitFloatPrecision <= 6) {
3200 // For floating-point precision of 6:
3201 //
3202 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3203 //
3204 // error 0.0049451742, which is more than 7 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003205 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003206 getF32Constant(DAG, 0xbeb08fe0));
Owen Anderson825b72b2009-08-11 20:47:22 +00003207 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003208 getF32Constant(DAG, 0x40019463));
Owen Anderson825b72b2009-08-11 20:47:22 +00003209 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3210 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003211 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003212
Scott Michelfdc40a02009-02-17 22:15:04 +00003213 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003214 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003215 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3216 // For floating-point precision of 12:
3217 //
3218 // Log2ofMantissa =
3219 // -2.51285454f +
3220 // (4.07009056f +
3221 // (-2.12067489f +
3222 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003223 //
Bill Wendling3eb59402008-09-09 00:28:24 +00003224 // error 0.0000876136000, which is better than 13 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003225 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003226 getF32Constant(DAG, 0xbda7262e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003227 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003228 getF32Constant(DAG, 0x3f25280b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003229 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3230 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003231 getF32Constant(DAG, 0x4007b923));
Owen Anderson825b72b2009-08-11 20:47:22 +00003232 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3233 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003234 getF32Constant(DAG, 0x40823e2f));
Owen Anderson825b72b2009-08-11 20:47:22 +00003235 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3236 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003237 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003238
Scott Michelfdc40a02009-02-17 22:15:04 +00003239 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003240 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003241 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3242 // For floating-point precision of 18:
3243 //
3244 // Log2ofMantissa =
3245 // -3.0400495f +
3246 // (6.1129976f +
3247 // (-5.3420409f +
3248 // (3.2865683f +
3249 // (-1.2669343f +
3250 // (0.27515199f -
3251 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3252 //
3253 // error 0.0000018516, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003254 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003255 getF32Constant(DAG, 0xbcd2769e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003256 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003257 getF32Constant(DAG, 0x3e8ce0b9));
Owen Anderson825b72b2009-08-11 20:47:22 +00003258 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3259 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003260 getF32Constant(DAG, 0x3fa22ae7));
Owen Anderson825b72b2009-08-11 20:47:22 +00003261 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3262 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003263 getF32Constant(DAG, 0x40525723));
Owen Anderson825b72b2009-08-11 20:47:22 +00003264 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3265 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003266 getF32Constant(DAG, 0x40aaf200));
Owen Anderson825b72b2009-08-11 20:47:22 +00003267 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3268 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003269 getF32Constant(DAG, 0x40c39dad));
Owen Anderson825b72b2009-08-11 20:47:22 +00003270 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3271 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003272 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003273
Scott Michelfdc40a02009-02-17 22:15:04 +00003274 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003275 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003276 }
Dale Johannesen853244f2008-09-05 23:49:37 +00003277 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003278 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003279 result = DAG.getNode(ISD::FLOG2, dl,
Dale Johannesen853244f2008-09-05 23:49:37 +00003280 getValue(I.getOperand(1)).getValueType(),
3281 getValue(I.getOperand(1)));
3282 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003283
Dale Johannesen59e577f2008-09-05 18:38:42 +00003284 setValue(&I, result);
3285}
3286
Bill Wendling3eb59402008-09-09 00:28:24 +00003287/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3288/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003289void
Dan Gohman2048b852009-11-23 18:04:58 +00003290SelectionDAGBuilder::visitLog10(CallInst &I) {
Dale Johannesen59e577f2008-09-05 18:38:42 +00003291 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003292 DebugLoc dl = getCurDebugLoc();
Bill Wendling181b6272008-10-19 20:34:04 +00003293
Owen Anderson825b72b2009-08-11 20:47:22 +00003294 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003295 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3296 SDValue Op = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003297 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003298
Bill Wendling39150252008-09-09 20:39:27 +00003299 // Scale the exponent by log10(2) [0.30102999f].
Bill Wendling856ff412009-12-22 00:12:37 +00003300 SDValue Exp = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
Owen Anderson825b72b2009-08-11 20:47:22 +00003301 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003302 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003303
3304 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003305 // exponent of 1.
Bill Wendling856ff412009-12-22 00:12:37 +00003306 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
Bill Wendling3eb59402008-09-09 00:28:24 +00003307
3308 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003309 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003310 //
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003311 // Log10ofMantissa =
3312 // -0.50419619f +
3313 // (0.60948995f - 0.10380950f * x) * x;
3314 //
3315 // error 0.0014886165, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003316 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003317 getF32Constant(DAG, 0xbdd49a13));
Owen Anderson825b72b2009-08-11 20:47:22 +00003318 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003319 getF32Constant(DAG, 0x3f1c0789));
Owen Anderson825b72b2009-08-11 20:47:22 +00003320 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3321 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003322 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003323
Scott Michelfdc40a02009-02-17 22:15:04 +00003324 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003325 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003326 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3327 // For floating-point precision of 12:
3328 //
3329 // Log10ofMantissa =
3330 // -0.64831180f +
3331 // (0.91751397f +
3332 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3333 //
3334 // error 0.00019228036, which is better than 12 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003335 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003336 getF32Constant(DAG, 0x3d431f31));
Owen Anderson825b72b2009-08-11 20:47:22 +00003337 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003338 getF32Constant(DAG, 0x3ea21fb2));
Owen Anderson825b72b2009-08-11 20:47:22 +00003339 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3340 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003341 getF32Constant(DAG, 0x3f6ae232));
Owen Anderson825b72b2009-08-11 20:47:22 +00003342 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3343 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003344 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00003345
Scott Michelfdc40a02009-02-17 22:15:04 +00003346 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003347 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003348 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003349 // For floating-point precision of 18:
3350 //
3351 // Log10ofMantissa =
3352 // -0.84299375f +
3353 // (1.5327582f +
3354 // (-1.0688956f +
3355 // (0.49102474f +
3356 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3357 //
3358 // error 0.0000037995730, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003359 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003360 getF32Constant(DAG, 0x3c5d51ce));
Owen Anderson825b72b2009-08-11 20:47:22 +00003361 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003362 getF32Constant(DAG, 0x3e00685a));
Owen Anderson825b72b2009-08-11 20:47:22 +00003363 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3364 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003365 getF32Constant(DAG, 0x3efb6798));
Owen Anderson825b72b2009-08-11 20:47:22 +00003366 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3367 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003368 getF32Constant(DAG, 0x3f88d192));
Owen Anderson825b72b2009-08-11 20:47:22 +00003369 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3370 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003371 getF32Constant(DAG, 0x3fc4316c));
Owen Anderson825b72b2009-08-11 20:47:22 +00003372 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3373 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003374 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003375
Scott Michelfdc40a02009-02-17 22:15:04 +00003376 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003377 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003378 }
Dale Johannesen852680a2008-09-05 21:27:19 +00003379 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003380 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003381 result = DAG.getNode(ISD::FLOG10, dl,
Dale Johannesen852680a2008-09-05 21:27:19 +00003382 getValue(I.getOperand(1)).getValueType(),
3383 getValue(I.getOperand(1)));
3384 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003385
Dale Johannesen59e577f2008-09-05 18:38:42 +00003386 setValue(&I, result);
3387}
3388
Bill Wendlinge10c8142008-09-09 22:39:21 +00003389/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3390/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003391void
Dan Gohman2048b852009-11-23 18:04:58 +00003392SelectionDAGBuilder::visitExp2(CallInst &I) {
Dale Johannesen601d3c02008-09-05 01:48:15 +00003393 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003394 DebugLoc dl = getCurDebugLoc();
Bill Wendlinge10c8142008-09-09 22:39:21 +00003395
Owen Anderson825b72b2009-08-11 20:47:22 +00003396 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00003397 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3398 SDValue Op = getValue(I.getOperand(1));
3399
Owen Anderson825b72b2009-08-11 20:47:22 +00003400 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003401
3402 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00003403 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3404 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003405
3406 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00003407 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003408 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003409
3410 if (LimitFloatPrecision <= 6) {
3411 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003412 //
Bill Wendlinge10c8142008-09-09 22:39:21 +00003413 // TwoToFractionalPartOfX =
3414 // 0.997535578f +
3415 // (0.735607626f + 0.252464424f * x) * x;
3416 //
3417 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003418 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003419 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00003420 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003421 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003422 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3423 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003424 getF32Constant(DAG, 0x3f7f5e7e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003425 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003426 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003427 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003428
Scott Michelfdc40a02009-02-17 22:15:04 +00003429 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003430 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003431 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3432 // For floating-point precision of 12:
3433 //
3434 // TwoToFractionalPartOfX =
3435 // 0.999892986f +
3436 // (0.696457318f +
3437 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3438 //
3439 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003440 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003441 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003442 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003443 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003444 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3445 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003446 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00003447 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3448 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003449 getF32Constant(DAG, 0x3f7ff8fd));
Owen Anderson825b72b2009-08-11 20:47:22 +00003450 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003451 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003452 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003453
Scott Michelfdc40a02009-02-17 22:15:04 +00003454 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003455 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003456 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3457 // For floating-point precision of 18:
3458 //
3459 // TwoToFractionalPartOfX =
3460 // 0.999999982f +
3461 // (0.693148872f +
3462 // (0.240227044f +
3463 // (0.554906021e-1f +
3464 // (0.961591928e-2f +
3465 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3466 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003467 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003468 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003469 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003470 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003471 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3472 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003473 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003474 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3475 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003476 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003477 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3478 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003479 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003480 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3481 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003482 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003483 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3484 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003485 getF32Constant(DAG, 0x3f800000));
Owen Anderson825b72b2009-08-11 20:47:22 +00003486 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003487 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003488 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003489
Scott Michelfdc40a02009-02-17 22:15:04 +00003490 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003491 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003492 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00003493 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003494 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003495 result = DAG.getNode(ISD::FEXP2, dl,
Dale Johannesen601d3c02008-09-05 01:48:15 +00003496 getValue(I.getOperand(1)).getValueType(),
3497 getValue(I.getOperand(1)));
3498 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00003499
Dale Johannesen601d3c02008-09-05 01:48:15 +00003500 setValue(&I, result);
3501}
3502
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003503/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3504/// limited-precision mode with x == 10.0f.
3505void
Dan Gohman2048b852009-11-23 18:04:58 +00003506SelectionDAGBuilder::visitPow(CallInst &I) {
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003507 SDValue result;
3508 Value *Val = I.getOperand(1);
Dale Johannesen66978ee2009-01-31 02:22:37 +00003509 DebugLoc dl = getCurDebugLoc();
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003510 bool IsExp10 = false;
3511
Owen Anderson825b72b2009-08-11 20:47:22 +00003512 if (getValue(Val).getValueType() == MVT::f32 &&
3513 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003514 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3515 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3516 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3517 APFloat Ten(10.0f);
3518 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3519 }
3520 }
3521 }
3522
3523 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3524 SDValue Op = getValue(I.getOperand(2));
3525
3526 // Put the exponent in the right bit position for later addition to the
3527 // final result:
3528 //
3529 // #define LOG2OF10 3.3219281f
3530 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
Owen Anderson825b72b2009-08-11 20:47:22 +00003531 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003532 getF32Constant(DAG, 0x40549a78));
Owen Anderson825b72b2009-08-11 20:47:22 +00003533 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003534
3535 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00003536 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3537 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003538
3539 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00003540 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003541 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003542
3543 if (LimitFloatPrecision <= 6) {
3544 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003545 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003546 // twoToFractionalPartOfX =
3547 // 0.997535578f +
3548 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003549 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003550 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003551 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003552 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00003553 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003554 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003555 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3556 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003557 getF32Constant(DAG, 0x3f7f5e7e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003558 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003559 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003560 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003561
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003562 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003563 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003564 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3565 // For floating-point precision of 12:
3566 //
3567 // TwoToFractionalPartOfX =
3568 // 0.999892986f +
3569 // (0.696457318f +
3570 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3571 //
3572 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003573 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003574 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003575 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003576 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003577 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3578 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003579 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00003580 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3581 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003582 getF32Constant(DAG, 0x3f7ff8fd));
Owen Anderson825b72b2009-08-11 20:47:22 +00003583 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003584 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003585 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003586
Scott Michelfdc40a02009-02-17 22:15:04 +00003587 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003588 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003589 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3590 // For floating-point precision of 18:
3591 //
3592 // TwoToFractionalPartOfX =
3593 // 0.999999982f +
3594 // (0.693148872f +
3595 // (0.240227044f +
3596 // (0.554906021e-1f +
3597 // (0.961591928e-2f +
3598 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3599 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003600 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003601 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003602 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003603 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003604 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3605 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003606 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003607 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3608 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003609 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003610 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3611 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003612 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003613 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3614 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003615 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003616 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3617 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003618 getF32Constant(DAG, 0x3f800000));
Owen Anderson825b72b2009-08-11 20:47:22 +00003619 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003620 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003621 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003622
Scott Michelfdc40a02009-02-17 22:15:04 +00003623 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003624 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003625 }
3626 } else {
3627 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003628 result = DAG.getNode(ISD::FPOW, dl,
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003629 getValue(I.getOperand(1)).getValueType(),
3630 getValue(I.getOperand(1)),
3631 getValue(I.getOperand(2)));
3632 }
3633
3634 setValue(&I, result);
3635}
3636
Chris Lattnerf031e8a2010-01-01 03:32:16 +00003637
3638/// ExpandPowI - Expand a llvm.powi intrinsic.
3639static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS,
3640 SelectionDAG &DAG) {
3641 // If RHS is a constant, we can expand this out to a multiplication tree,
3642 // otherwise we end up lowering to a call to __powidf2 (for example). When
3643 // optimizing for size, we only want to do this if the expansion would produce
3644 // a small number of multiplies, otherwise we do the full expansion.
3645 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3646 // Get the exponent as a positive value.
3647 unsigned Val = RHSC->getSExtValue();
3648 if ((int)Val < 0) Val = -Val;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003649
Chris Lattnerf031e8a2010-01-01 03:32:16 +00003650 // powi(x, 0) -> 1.0
3651 if (Val == 0)
3652 return DAG.getConstantFP(1.0, LHS.getValueType());
3653
3654 Function *F = DAG.getMachineFunction().getFunction();
3655 if (!F->hasFnAttr(Attribute::OptimizeForSize) ||
3656 // If optimizing for size, don't insert too many multiplies. This
3657 // inserts up to 5 multiplies.
3658 CountPopulation_32(Val)+Log2_32(Val) < 7) {
3659 // We use the simple binary decomposition method to generate the multiply
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003660 // sequence. There are more optimal ways to do this (for example,
Chris Lattnerf031e8a2010-01-01 03:32:16 +00003661 // powi(x,15) generates one more multiply than it should), but this has
3662 // the benefit of being both really simple and much better than a libcall.
3663 SDValue Res; // Logically starts equal to 1.0
3664 SDValue CurSquare = LHS;
3665 while (Val) {
Mikhail Glushenkovbfdfea82010-01-01 04:41:36 +00003666 if (Val & 1) {
Chris Lattnerf031e8a2010-01-01 03:32:16 +00003667 if (Res.getNode())
3668 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
3669 else
3670 Res = CurSquare; // 1.0*CurSquare.
Mikhail Glushenkovbfdfea82010-01-01 04:41:36 +00003671 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003672
Chris Lattnerf031e8a2010-01-01 03:32:16 +00003673 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
3674 CurSquare, CurSquare);
3675 Val >>= 1;
3676 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003677
Chris Lattnerf031e8a2010-01-01 03:32:16 +00003678 // If the original was negative, invert the result, producing 1/(x*x*x).
3679 if (RHSC->getSExtValue() < 0)
3680 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
3681 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
3682 return Res;
3683 }
3684 }
3685
3686 // Otherwise, expand to a libcall.
3687 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
3688}
3689
3690
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003691/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3692/// we want to emit this as a call to a named external function, return the name
3693/// otherwise lower it and return null.
3694const char *
Dan Gohman2048b852009-11-23 18:04:58 +00003695SelectionDAGBuilder::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00003696 DebugLoc dl = getCurDebugLoc();
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003697 SDValue Res;
3698
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003699 switch (Intrinsic) {
3700 default:
3701 // By default, turn this into a target intrinsic node.
3702 visitTargetIntrinsic(I, Intrinsic);
3703 return 0;
3704 case Intrinsic::vastart: visitVAStart(I); return 0;
3705 case Intrinsic::vaend: visitVAEnd(I); return 0;
3706 case Intrinsic::vacopy: visitVACopy(I); return 0;
3707 case Intrinsic::returnaddress:
Bill Wendling4533cac2010-01-28 21:51:40 +00003708 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
3709 getValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003710 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00003711 case Intrinsic::frameaddress:
Bill Wendling4533cac2010-01-28 21:51:40 +00003712 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
3713 getValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003714 return 0;
3715 case Intrinsic::setjmp:
3716 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003717 case Intrinsic::longjmp:
3718 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattner824b9582008-11-21 16:42:48 +00003719 case Intrinsic::memcpy: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003720 SDValue Op1 = getValue(I.getOperand(1));
3721 SDValue Op2 = getValue(I.getOperand(2));
3722 SDValue Op3 = getValue(I.getOperand(3));
3723 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Bill Wendling4533cac2010-01-28 21:51:40 +00003724 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
3725 I.getOperand(1), 0, I.getOperand(2), 0));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003726 return 0;
3727 }
Chris Lattner824b9582008-11-21 16:42:48 +00003728 case Intrinsic::memset: {
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.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
3734 I.getOperand(1), 0));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003735 return 0;
3736 }
Chris Lattner824b9582008-11-21 16:42:48 +00003737 case Intrinsic::memmove: {
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();
3742
3743 // If the source and destination are known to not be aliases, we can
3744 // lower memmove as memcpy.
3745 uint64_t Size = -1ULL;
3746 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003747 Size = C->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003748 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3749 AliasAnalysis::NoAlias) {
Bill Wendling4533cac2010-01-28 21:51:40 +00003750 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
3751 I.getOperand(1), 0, I.getOperand(2), 0));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003752 return 0;
3753 }
3754
Bill Wendling4533cac2010-01-28 21:51:40 +00003755 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
3756 I.getOperand(1), 0, I.getOperand(2), 0));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003757 return 0;
3758 }
Bill Wendling92c1e122009-02-13 02:16:35 +00003759 case Intrinsic::dbg_declare: {
Dale Johannesen904c2fa2010-02-01 19:54:53 +00003760 // FIXME: currently, we get here only if OptLevel != CodeGenOpt::None.
3761 // The real handling of this intrinsic is in FastISel.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003762 if (OptLevel != CodeGenOpt::None)
Devang Patel7e1e31f2009-07-02 22:43:26 +00003763 // FIXME: Variable debug info is not supported here.
3764 return 0;
Devang Patel24f20e02009-08-22 17:12:53 +00003765 DwarfWriter *DW = DAG.getDwarfWriter();
3766 if (!DW)
3767 return 0;
Devang Patel7e1e31f2009-07-02 22:43:26 +00003768 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Chris Lattnerbf0ca2b2009-12-29 09:32:19 +00003769 if (!DIDescriptor::ValidDebugInfo(DI.getVariable(), CodeGenOpt::None))
Devang Patel7e1e31f2009-07-02 22:43:26 +00003770 return 0;
3771
Devang Patelac1ceb32009-10-09 22:42:28 +00003772 MDNode *Variable = DI.getVariable();
Devang Patel24f20e02009-08-22 17:12:53 +00003773 Value *Address = DI.getAddress();
Dale Johannesen8ac38f22010-02-08 21:53:27 +00003774 if (!Address)
3775 return 0;
Devang Patel24f20e02009-08-22 17:12:53 +00003776 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
3777 Address = BCI->getOperand(0);
3778 AllocaInst *AI = dyn_cast<AllocaInst>(Address);
3779 // Don't handle byval struct arguments or VLAs, for example.
3780 if (!AI)
3781 return 0;
Devang Patelbd1d6a82009-09-05 00:34:14 +00003782 DenseMap<const AllocaInst*, int>::iterator SI =
3783 FuncInfo.StaticAllocaMap.find(AI);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003784 if (SI == FuncInfo.StaticAllocaMap.end())
Devang Patelbd1d6a82009-09-05 00:34:14 +00003785 return 0; // VLAs.
3786 int FI = SI->second;
Devang Patel70d75ca2009-11-12 19:02:56 +00003787
Chris Lattner3990b122009-12-28 23:41:32 +00003788 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo())
3789 if (MDNode *Dbg = DI.getMetadata("dbg"))
Chris Lattner0eb41982009-12-28 20:45:51 +00003790 MMI->setVariableDbgInfo(Variable, FI, Dbg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003791 return 0;
Bill Wendling92c1e122009-02-13 02:16:35 +00003792 }
Dale Johannesen904c2fa2010-02-01 19:54:53 +00003793 case Intrinsic::dbg_value: {
3794 // FIXME: currently, we get here only if OptLevel != CodeGenOpt::None.
3795 // The real handling of this intrinsic is in FastISel.
3796 if (OptLevel != CodeGenOpt::None)
3797 // FIXME: Variable debug info is not supported here.
3798 return 0;
3799 DwarfWriter *DW = DAG.getDwarfWriter();
3800 if (!DW)
3801 return 0;
3802 DbgValueInst &DI = cast<DbgValueInst>(I);
3803 if (!DIDescriptor::ValidDebugInfo(DI.getVariable(), CodeGenOpt::None))
3804 return 0;
3805
3806 MDNode *Variable = DI.getVariable();
3807 Value *V = DI.getValue();
3808 if (!V)
3809 return 0;
3810 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
3811 V = BCI->getOperand(0);
3812 AllocaInst *AI = dyn_cast<AllocaInst>(V);
3813 // Don't handle byval struct arguments or VLAs, for example.
3814 if (!AI)
3815 return 0;
3816 DenseMap<const AllocaInst*, int>::iterator SI =
3817 FuncInfo.StaticAllocaMap.find(AI);
3818 if (SI == FuncInfo.StaticAllocaMap.end())
3819 return 0; // VLAs.
3820 int FI = SI->second;
3821 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo())
3822 if (MDNode *Dbg = DI.getMetadata("dbg"))
3823 MMI->setVariableDbgInfo(Variable, FI, Dbg);
3824 return 0;
3825 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003826 case Intrinsic::eh_exception: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003827 // Insert the EXCEPTIONADDR instruction.
Duncan Sandsb0f1e172009-05-22 20:36:31 +00003828 assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!");
Owen Anderson825b72b2009-08-11 20:47:22 +00003829 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003830 SDValue Ops[1];
3831 Ops[0] = DAG.getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003832 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003833 setValue(&I, Op);
3834 DAG.setRoot(Op.getValue(1));
3835 return 0;
3836 }
3837
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00003838 case Intrinsic::eh_selector: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003839 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003840
Chris Lattner3a5815f2009-09-17 23:54:54 +00003841 if (CurMBB->isLandingPad())
3842 AddCatchInfo(I, MMI, CurMBB);
3843 else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003844#ifndef NDEBUG
Chris Lattner3a5815f2009-09-17 23:54:54 +00003845 FuncInfo.CatchInfoLost.insert(&I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003846#endif
Chris Lattner3a5815f2009-09-17 23:54:54 +00003847 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3848 unsigned Reg = TLI.getExceptionSelectorRegister();
3849 if (Reg) CurMBB->addLiveIn(Reg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003850 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003851
Chris Lattner3a5815f2009-09-17 23:54:54 +00003852 // Insert the EHSELECTION instruction.
3853 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3854 SDValue Ops[2];
3855 Ops[0] = getValue(I.getOperand(1));
3856 Ops[1] = getRoot();
3857 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
Chris Lattner3a5815f2009-09-17 23:54:54 +00003858 DAG.setRoot(Op.getValue(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00003859 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003860 return 0;
3861 }
3862
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00003863 case Intrinsic::eh_typeid_for: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003864 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003865
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003866 if (MMI) {
3867 // Find the type id for the given typeinfo.
3868 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003869 unsigned TypeID = MMI->getTypeIDFor(GV);
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003870 Res = DAG.getConstant(TypeID, MVT::i32);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003871 } else {
3872 // Return something different to eh_selector.
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003873 Res = DAG.getConstant(1, MVT::i32);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003874 }
3875
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003876 setValue(&I, Res);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003877 return 0;
3878 }
3879
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003880 case Intrinsic::eh_return_i32:
3881 case Intrinsic::eh_return_i64:
3882 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003883 MMI->setCallsEHReturn(true);
Bill Wendling4533cac2010-01-28 21:51:40 +00003884 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
3885 MVT::Other,
3886 getControlRoot(),
3887 getValue(I.getOperand(1)),
3888 getValue(I.getOperand(2))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003889 } else {
3890 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3891 }
3892
3893 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003894 case Intrinsic::eh_unwind_init:
3895 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3896 MMI->setCallsUnwindInit(true);
3897 }
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003898 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003899 case Intrinsic::eh_dwarf_cfa: {
Owen Andersone50ed302009-08-10 22:56:29 +00003900 EVT VT = getValue(I.getOperand(1)).getValueType();
Duncan Sands3a66a682009-10-13 21:04:12 +00003901 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), dl,
3902 TLI.getPointerTy());
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003903 SDValue Offset = DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003904 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003905 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003906 TLI.getPointerTy()),
3907 CfaArg);
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003908 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003909 TLI.getPointerTy(),
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003910 DAG.getConstant(0, TLI.getPointerTy()));
Bill Wendling4533cac2010-01-28 21:51:40 +00003911 setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
3912 FA, Offset));
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003913 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003914 }
Jim Grosbachca752c92010-01-28 01:45:32 +00003915 case Intrinsic::eh_sjlj_callsite: {
3916 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3917 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
3918 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
3919 assert(MMI->getCurrentCallSite() == 0 && "Overlapping call sites!");
3920
3921 MMI->setCurrentCallSite(CI->getZExtValue());
3922 return 0;
3923 }
3924
Mon P Wang77cdf302008-11-10 20:54:11 +00003925 case Intrinsic::convertff:
3926 case Intrinsic::convertfsi:
3927 case Intrinsic::convertfui:
3928 case Intrinsic::convertsif:
3929 case Intrinsic::convertuif:
3930 case Intrinsic::convertss:
3931 case Intrinsic::convertsu:
3932 case Intrinsic::convertus:
3933 case Intrinsic::convertuu: {
3934 ISD::CvtCode Code = ISD::CVT_INVALID;
3935 switch (Intrinsic) {
3936 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
3937 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
3938 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
3939 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
3940 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
3941 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
3942 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
3943 case Intrinsic::convertus: Code = ISD::CVT_US; break;
3944 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
3945 }
Owen Andersone50ed302009-08-10 22:56:29 +00003946 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003947 Value *Op1 = I.getOperand(1);
3948 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
3949 DAG.getValueType(DestVT),
3950 DAG.getValueType(getValue(Op1).getValueType()),
3951 getValue(I.getOperand(2)),
3952 getValue(I.getOperand(3)),
3953 Code);
3954 setValue(&I, Res);
Mon P Wang77cdf302008-11-10 20:54:11 +00003955 return 0;
3956 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003957 case Intrinsic::sqrt:
Bill Wendling4533cac2010-01-28 21:51:40 +00003958 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
3959 getValue(I.getOperand(1)).getValueType(),
3960 getValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003961 return 0;
3962 case Intrinsic::powi:
Bill Wendling4533cac2010-01-28 21:51:40 +00003963 setValue(&I, ExpandPowI(dl, getValue(I.getOperand(1)),
3964 getValue(I.getOperand(2)), DAG));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003965 return 0;
3966 case Intrinsic::sin:
Bill Wendling4533cac2010-01-28 21:51:40 +00003967 setValue(&I, DAG.getNode(ISD::FSIN, 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::cos:
Bill Wendling4533cac2010-01-28 21:51:40 +00003972 setValue(&I, DAG.getNode(ISD::FCOS, dl,
3973 getValue(I.getOperand(1)).getValueType(),
3974 getValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003975 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003976 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003977 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003978 return 0;
3979 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003980 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003981 return 0;
3982 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003983 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003984 return 0;
3985 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003986 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003987 return 0;
3988 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00003989 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003990 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003991 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003992 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003993 return 0;
3994 case Intrinsic::pcmarker: {
3995 SDValue Tmp = getValue(I.getOperand(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00003996 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003997 return 0;
3998 }
3999 case Intrinsic::readcyclecounter: {
4000 SDValue Op = getRoot();
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004001 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4002 DAG.getVTList(MVT::i64, MVT::Other),
4003 &Op, 1);
4004 setValue(&I, Res);
4005 DAG.setRoot(Res.getValue(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004006 return 0;
4007 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004008 case Intrinsic::bswap:
Bill Wendling4533cac2010-01-28 21:51:40 +00004009 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
4010 getValue(I.getOperand(1)).getValueType(),
4011 getValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004012 return 0;
4013 case Intrinsic::cttz: {
4014 SDValue Arg = getValue(I.getOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00004015 EVT Ty = Arg.getValueType();
Bill Wendling4533cac2010-01-28 21:51:40 +00004016 setValue(&I, DAG.getNode(ISD::CTTZ, dl, Ty, Arg));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004017 return 0;
4018 }
4019 case Intrinsic::ctlz: {
4020 SDValue Arg = getValue(I.getOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00004021 EVT Ty = Arg.getValueType();
Bill Wendling4533cac2010-01-28 21:51:40 +00004022 setValue(&I, DAG.getNode(ISD::CTLZ, dl, Ty, Arg));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004023 return 0;
4024 }
4025 case Intrinsic::ctpop: {
4026 SDValue Arg = getValue(I.getOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00004027 EVT Ty = Arg.getValueType();
Bill Wendling4533cac2010-01-28 21:51:40 +00004028 setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004029 return 0;
4030 }
4031 case Intrinsic::stacksave: {
4032 SDValue Op = getRoot();
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004033 Res = DAG.getNode(ISD::STACKSAVE, dl,
4034 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4035 setValue(&I, Res);
4036 DAG.setRoot(Res.getValue(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004037 return 0;
4038 }
4039 case Intrinsic::stackrestore: {
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004040 Res = getValue(I.getOperand(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00004041 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004042 return 0;
4043 }
Bill Wendling57344502008-11-18 11:01:33 +00004044 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00004045 // Emit code into the DAG to store the stack guard onto the stack.
4046 MachineFunction &MF = DAG.getMachineFunction();
4047 MachineFrameInfo *MFI = MF.getFrameInfo();
Owen Andersone50ed302009-08-10 22:56:29 +00004048 EVT PtrTy = TLI.getPointerTy();
Bill Wendlingb2a42982008-11-06 02:29:10 +00004049
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004050 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4051 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
Bill Wendlingb2a42982008-11-06 02:29:10 +00004052
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004053 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00004054 MFI->setStackProtectorIndex(FI);
4055
4056 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4057
4058 // Store the stack protector onto the stack.
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004059 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4060 PseudoSourceValue::getFixedStack(FI),
4061 0, true);
4062 setValue(&I, Res);
4063 DAG.setRoot(Res);
Bill Wendlingb2a42982008-11-06 02:29:10 +00004064 return 0;
4065 }
Eric Christopher7b5e6172009-10-27 00:52:25 +00004066 case Intrinsic::objectsize: {
4067 // If we don't know by now, we're never going to know.
4068 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2));
4069
4070 assert(CI && "Non-constant type in __builtin_object_size?");
4071
Eric Christopher7e5d2ff2009-10-28 21:32:16 +00004072 SDValue Arg = getValue(I.getOperand(0));
4073 EVT Ty = Arg.getValueType();
4074
Eric Christopherd060b252009-12-23 02:51:48 +00004075 if (CI->getZExtValue() == 0)
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004076 Res = DAG.getConstant(-1ULL, Ty);
Eric Christopher7b5e6172009-10-27 00:52:25 +00004077 else
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004078 Res = DAG.getConstant(0, Ty);
4079
4080 setValue(&I, Res);
Eric Christopher7b5e6172009-10-27 00:52:25 +00004081 return 0;
4082 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004083 case Intrinsic::var_annotation:
4084 // Discard annotate attributes
4085 return 0;
4086
4087 case Intrinsic::init_trampoline: {
4088 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4089
4090 SDValue Ops[6];
4091 Ops[0] = getRoot();
4092 Ops[1] = getValue(I.getOperand(1));
4093 Ops[2] = getValue(I.getOperand(2));
4094 Ops[3] = getValue(I.getOperand(3));
4095 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4096 Ops[5] = DAG.getSrcValue(F);
4097
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004098 Res = DAG.getNode(ISD::TRAMPOLINE, dl,
4099 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4100 Ops, 6);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004101
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004102 setValue(&I, Res);
4103 DAG.setRoot(Res.getValue(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004104 return 0;
4105 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004106 case Intrinsic::gcroot:
4107 if (GFI) {
4108 Value *Alloca = I.getOperand(1);
4109 Constant *TypeMap = cast<Constant>(I.getOperand(2));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004110
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004111 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4112 GFI->addStackRoot(FI->getIndex(), TypeMap);
4113 }
4114 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004115 case Intrinsic::gcread:
4116 case Intrinsic::gcwrite:
Torok Edwinc23197a2009-07-14 16:55:14 +00004117 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004118 return 0;
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004119 case Intrinsic::flt_rounds:
Bill Wendling4533cac2010-01-28 21:51:40 +00004120 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004121 return 0;
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004122 case Intrinsic::trap:
Bill Wendling4533cac2010-01-28 21:51:40 +00004123 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004124 return 0;
Bill Wendlingef375462008-11-21 02:38:44 +00004125 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00004126 return implVisitAluOverflow(I, ISD::UADDO);
4127 case Intrinsic::sadd_with_overflow:
4128 return implVisitAluOverflow(I, ISD::SADDO);
4129 case Intrinsic::usub_with_overflow:
4130 return implVisitAluOverflow(I, ISD::USUBO);
4131 case Intrinsic::ssub_with_overflow:
4132 return implVisitAluOverflow(I, ISD::SSUBO);
4133 case Intrinsic::umul_with_overflow:
4134 return implVisitAluOverflow(I, ISD::UMULO);
4135 case Intrinsic::smul_with_overflow:
4136 return implVisitAluOverflow(I, ISD::SMULO);
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004137
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004138 case Intrinsic::prefetch: {
4139 SDValue Ops[4];
4140 Ops[0] = getRoot();
4141 Ops[1] = getValue(I.getOperand(1));
4142 Ops[2] = getValue(I.getOperand(2));
4143 Ops[3] = getValue(I.getOperand(3));
Bill Wendling4533cac2010-01-28 21:51:40 +00004144 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004145 return 0;
4146 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004147
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004148 case Intrinsic::memory_barrier: {
4149 SDValue Ops[6];
4150 Ops[0] = getRoot();
4151 for (int x = 1; x < 6; ++x)
4152 Ops[x] = getValue(I.getOperand(x));
4153
Bill Wendling4533cac2010-01-28 21:51:40 +00004154 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004155 return 0;
4156 }
4157 case Intrinsic::atomic_cmp_swap: {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004158 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004159 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00004160 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004161 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4162 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004163 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004164 getValue(I.getOperand(2)),
4165 getValue(I.getOperand(3)),
4166 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004167 setValue(&I, L);
4168 DAG.setRoot(L.getValue(1));
4169 return 0;
4170 }
4171 case Intrinsic::atomic_load_add:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004172 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004173 case Intrinsic::atomic_load_sub:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004174 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004175 case Intrinsic::atomic_load_or:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004176 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004177 case Intrinsic::atomic_load_xor:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004178 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004179 case Intrinsic::atomic_load_and:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004180 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004181 case Intrinsic::atomic_load_nand:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004182 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004183 case Intrinsic::atomic_load_max:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004184 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004185 case Intrinsic::atomic_load_min:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004186 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004187 case Intrinsic::atomic_load_umin:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004188 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004189 case Intrinsic::atomic_load_umax:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004190 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004191 case Intrinsic::atomic_swap:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004192 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Duncan Sandsf07c9492009-11-10 09:08:09 +00004193
4194 case Intrinsic::invariant_start:
4195 case Intrinsic::lifetime_start:
4196 // Discard region information.
Bill Wendling4533cac2010-01-28 21:51:40 +00004197 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
Duncan Sandsf07c9492009-11-10 09:08:09 +00004198 return 0;
4199 case Intrinsic::invariant_end:
4200 case Intrinsic::lifetime_end:
4201 // Discard region information.
4202 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004203 }
4204}
4205
Dan Gohman98ca4f22009-08-05 01:29:28 +00004206/// Test if the given instruction is in a position to be optimized
4207/// with a tail-call. This roughly means that it's in a block with
4208/// a return and there's nothing that needs to be scheduled
4209/// between it and the return.
4210///
4211/// This function only tests target-independent requirements.
Dan Gohman98ca4f22009-08-05 01:29:28 +00004212static bool
Evan Cheng86809cc2010-02-03 03:28:02 +00004213isInTailCallPosition(CallSite CS, Attributes CalleeRetAttr,
Dan Gohman98ca4f22009-08-05 01:29:28 +00004214 const TargetLowering &TLI) {
Evan Cheng86809cc2010-02-03 03:28:02 +00004215 const Instruction *I = CS.getInstruction();
Dan Gohman98ca4f22009-08-05 01:29:28 +00004216 const BasicBlock *ExitBB = I->getParent();
4217 const TerminatorInst *Term = ExitBB->getTerminator();
4218 const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
4219 const Function *F = ExitBB->getParent();
4220
Dan Gohmanc2e93b22010-02-08 20:34:14 +00004221 // The block must end in a return statement or unreachable.
4222 //
4223 // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
4224 // an unreachable, for now. The way tailcall optimization is currently
4225 // implemented means it will add an epilogue followed by a jump. That is
4226 // not profitable. Also, if the callee is a special function (e.g.
4227 // longjmp on x86), it can end up causing miscompilation that has not
4228 // been fully understood.
4229 if (!Ret &&
4230 (!GuaranteedTailCallOpt || !isa<UnreachableInst>(Term))) return false;
Dan Gohman98ca4f22009-08-05 01:29:28 +00004231
4232 // If I will have a chain, make sure no other instruction that will have a
4233 // chain interposes between I and the return.
4234 if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
4235 !I->isSafeToSpeculativelyExecute())
4236 for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
4237 --BBI) {
4238 if (&*BBI == I)
4239 break;
4240 if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
4241 !BBI->isSafeToSpeculativelyExecute())
4242 return false;
4243 }
4244
4245 // If the block ends with a void return or unreachable, it doesn't matter
4246 // what the call's return type is.
4247 if (!Ret || Ret->getNumOperands() == 0) return true;
4248
Dan Gohmaned9bab32009-11-14 02:06:30 +00004249 // If the return value is undef, it doesn't matter what the call's
4250 // return type is.
4251 if (isa<UndefValue>(Ret->getOperand(0))) return true;
4252
Dan Gohman98ca4f22009-08-05 01:29:28 +00004253 // Conservatively require the attributes of the call to match those of
Dan Gohman01205a82009-11-13 18:49:38 +00004254 // the return. Ignore noalias because it doesn't affect the call sequence.
4255 unsigned CallerRetAttr = F->getAttributes().getRetAttributes();
4256 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
Dan Gohman98ca4f22009-08-05 01:29:28 +00004257 return false;
4258
Evan Cheng6fdce652010-02-04 19:07:06 +00004259 // It's not safe to eliminate the sign / zero extension of the return value.
Evan Cheng446bc102010-02-04 02:45:02 +00004260 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
4261 return false;
4262
Dan Gohman98ca4f22009-08-05 01:29:28 +00004263 // Otherwise, make sure the unmodified return value of I is the return value.
4264 for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ;
4265 U = dyn_cast<Instruction>(U->getOperand(0))) {
4266 if (!U)
4267 return false;
4268 if (!U->hasOneUse())
4269 return false;
4270 if (U == I)
4271 break;
4272 // Check for a truly no-op truncate.
4273 if (isa<TruncInst>(U) &&
4274 TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType()))
4275 continue;
4276 // Check for a truly no-op bitcast.
4277 if (isa<BitCastInst>(U) &&
4278 (U->getOperand(0)->getType() == U->getType() ||
4279 (isa<PointerType>(U->getOperand(0)->getType()) &&
4280 isa<PointerType>(U->getType()))))
4281 continue;
4282 // Otherwise it's not a true no-op.
4283 return false;
4284 }
4285
4286 return true;
4287}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004288
Dan Gohman2048b852009-11-23 18:04:58 +00004289void SelectionDAGBuilder::LowerCallTo(CallSite CS, SDValue Callee,
4290 bool isTailCall,
4291 MachineBasicBlock *LandingPad) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004292 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4293 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004294 const Type *RetTy = FTy->getReturnType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004295 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4296 unsigned BeginLabel = 0, EndLabel = 0;
4297
4298 TargetLowering::ArgListTy Args;
4299 TargetLowering::ArgListEntry Entry;
4300 Args.reserve(CS.arg_size());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004301
4302 // Check whether the function can return without sret-demotion.
4303 SmallVector<EVT, 4> OutVTs;
4304 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
4305 SmallVector<uint64_t, 4> Offsets;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004306 getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
Bill Wendlinge80ae832009-12-22 00:50:32 +00004307 OutVTs, OutsFlags, TLI, &Offsets);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004308
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004309 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004310 FTy->isVarArg(), OutVTs, OutsFlags, DAG);
4311
4312 SDValue DemoteStackSlot;
4313
4314 if (!CanLowerReturn) {
4315 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
4316 FTy->getReturnType());
4317 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
4318 FTy->getReturnType());
4319 MachineFunction &MF = DAG.getMachineFunction();
David Greene3f2bf852009-11-12 20:49:22 +00004320 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004321 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
4322
4323 DemoteStackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4324 Entry.Node = DemoteStackSlot;
4325 Entry.Ty = StackSlotPtrType;
4326 Entry.isSExt = false;
4327 Entry.isZExt = false;
4328 Entry.isInReg = false;
4329 Entry.isSRet = true;
4330 Entry.isNest = false;
4331 Entry.isByVal = false;
4332 Entry.Alignment = Align;
4333 Args.push_back(Entry);
4334 RetTy = Type::getVoidTy(FTy->getContext());
4335 }
4336
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004337 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004338 i != e; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004339 SDValue ArgNode = getValue(*i);
4340 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4341
4342 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00004343 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4344 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4345 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4346 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4347 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4348 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004349 Entry.Alignment = CS.getParamAlignment(attrInd);
4350 Args.push_back(Entry);
4351 }
4352
4353 if (LandingPad && MMI) {
4354 // Insert a label before the invoke call to mark the try range. This can be
4355 // used to detect deletion of the invoke via the MachineModuleInfo.
4356 BeginLabel = MMI->NextLabelID();
Jim Grosbach1b747ad2009-08-11 00:09:57 +00004357
Jim Grosbachca752c92010-01-28 01:45:32 +00004358 // For SjLj, keep track of which landing pads go with which invokes
4359 // so as to maintain the ordering of pads in the LSDA.
4360 unsigned CallSiteIndex = MMI->getCurrentCallSite();
4361 if (CallSiteIndex) {
4362 MMI->setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
4363 // Now that the call site is handled, stop tracking it.
4364 MMI->setCurrentCallSite(0);
4365 }
4366
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004367 // Both PendingLoads and PendingExports must be flushed here;
4368 // this call might not return.
4369 (void)getRoot();
Bill Wendling0d580132009-12-23 01:28:19 +00004370 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4371 getControlRoot(), BeginLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004372 }
4373
Dan Gohman98ca4f22009-08-05 01:29:28 +00004374 // Check if target-independent constraints permit a tail call here.
4375 // Target-dependent constraints are checked within TLI.LowerCallTo.
4376 if (isTailCall &&
Evan Cheng86809cc2010-02-03 03:28:02 +00004377 !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI))
Dan Gohman98ca4f22009-08-05 01:29:28 +00004378 isTailCall = false;
4379
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004380 std::pair<SDValue,SDValue> Result =
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004381 TLI.LowerCallTo(getRoot(), RetTy,
Devang Patel05988662008-09-25 21:00:45 +00004382 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004383 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
Tilmann Scheller6b61cd12009-07-03 06:44:53 +00004384 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004385 CS.getCallingConv(),
Dan Gohman98ca4f22009-08-05 01:29:28 +00004386 isTailCall,
4387 !CS.getInstruction()->use_empty(),
Bill Wendling3ea3c242009-12-22 02:10:19 +00004388 Callee, Args, DAG, getCurDebugLoc(), SDNodeOrder);
Dan Gohman98ca4f22009-08-05 01:29:28 +00004389 assert((isTailCall || Result.second.getNode()) &&
4390 "Non-null chain expected with non-tail call!");
4391 assert((Result.second.getNode() || !Result.first.getNode()) &&
4392 "Null value expected with tail call!");
Bill Wendlinge80ae832009-12-22 00:50:32 +00004393 if (Result.first.getNode()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004394 setValue(CS.getInstruction(), Result.first);
Bill Wendlinge80ae832009-12-22 00:50:32 +00004395 } else if (!CanLowerReturn && Result.second.getNode()) {
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004396 // The instruction result is the result of loading from the
4397 // hidden sret parameter.
4398 SmallVector<EVT, 1> PVTs;
4399 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
4400
4401 ComputeValueVTs(TLI, PtrRetTy, PVTs);
4402 assert(PVTs.size() == 1 && "Pointers should fit in one register");
4403 EVT PtrVT = PVTs[0];
4404 unsigned NumValues = OutVTs.size();
4405 SmallVector<SDValue, 4> Values(NumValues);
4406 SmallVector<SDValue, 4> Chains(NumValues);
4407
4408 for (unsigned i = 0; i < NumValues; ++i) {
Bill Wendlinge80ae832009-12-22 00:50:32 +00004409 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
4410 DemoteStackSlot,
4411 DAG.getConstant(Offsets[i], PtrVT));
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004412 SDValue L = DAG.getLoad(OutVTs[i], getCurDebugLoc(), Result.second,
Bill Wendlinge80ae832009-12-22 00:50:32 +00004413 Add, NULL, Offsets[i], false, 1);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004414 Values[i] = L;
4415 Chains[i] = L.getValue(1);
4416 }
Bill Wendlinge80ae832009-12-22 00:50:32 +00004417
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004418 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
4419 MVT::Other, &Chains[0], NumValues);
4420 PendingLoads.push_back(Chain);
Kenneth Uildriks93ae4072010-01-16 23:37:33 +00004421
4422 // Collect the legal value parts into potentially illegal values
4423 // that correspond to the original function's return values.
4424 SmallVector<EVT, 4> RetTys;
4425 RetTy = FTy->getReturnType();
4426 ComputeValueVTs(TLI, RetTy, RetTys);
4427 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4428 SmallVector<SDValue, 4> ReturnValues;
4429 unsigned CurReg = 0;
4430 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4431 EVT VT = RetTys[I];
4432 EVT RegisterVT = TLI.getRegisterType(RetTy->getContext(), VT);
4433 unsigned NumRegs = TLI.getNumRegisters(RetTy->getContext(), VT);
4434
4435 SDValue ReturnValue =
4436 getCopyFromParts(DAG, getCurDebugLoc(), SDNodeOrder, &Values[CurReg], NumRegs,
4437 RegisterVT, VT, AssertOp);
4438 ReturnValues.push_back(ReturnValue);
Kenneth Uildriks93ae4072010-01-16 23:37:33 +00004439 CurReg += NumRegs;
4440 }
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004441
Bill Wendling4533cac2010-01-28 21:51:40 +00004442 setValue(CS.getInstruction(),
4443 DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
4444 DAG.getVTList(&RetTys[0], RetTys.size()),
4445 &ReturnValues[0], ReturnValues.size()));
Bill Wendlinge80ae832009-12-22 00:50:32 +00004446
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004447 }
Bill Wendlinge80ae832009-12-22 00:50:32 +00004448
4449 // As a special case, a null chain means that a tail call has been emitted and
4450 // the DAG root is already updated.
Bill Wendling4533cac2010-01-28 21:51:40 +00004451 if (Result.second.getNode())
Dan Gohman98ca4f22009-08-05 01:29:28 +00004452 DAG.setRoot(Result.second);
Bill Wendling4533cac2010-01-28 21:51:40 +00004453 else
Dan Gohman98ca4f22009-08-05 01:29:28 +00004454 HasTailCall = true;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004455
4456 if (LandingPad && MMI) {
4457 // Insert a label at the end of the invoke call to mark the try range. This
4458 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4459 EndLabel = MMI->NextLabelID();
Bill Wendling0d580132009-12-23 01:28:19 +00004460 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4461 getRoot(), EndLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004462
4463 // Inform MachineModuleInfo of range.
4464 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4465 }
4466}
4467
Chris Lattner8047d9a2009-12-24 00:37:38 +00004468/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
4469/// value is equal or not-equal to zero.
4470static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
4471 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
4472 UI != E; ++UI) {
4473 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
4474 if (IC->isEquality())
4475 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
4476 if (C->isNullValue())
4477 continue;
4478 // Unknown instruction.
4479 return false;
4480 }
4481 return true;
4482}
4483
Chris Lattner04b091a2009-12-24 01:07:17 +00004484static SDValue getMemCmpLoad(Value *PtrVal, MVT LoadVT, const Type *LoadTy,
Chris Lattner8047d9a2009-12-24 00:37:38 +00004485 SelectionDAGBuilder &Builder) {
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004486
Chris Lattner8047d9a2009-12-24 00:37:38 +00004487 // Check to see if this load can be trivially constant folded, e.g. if the
4488 // input is from a string literal.
4489 if (Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
4490 // Cast pointer to the type we really want to load.
4491 LoadInput = ConstantExpr::getBitCast(LoadInput,
4492 PointerType::getUnqual(LoadTy));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004493
Chris Lattner8047d9a2009-12-24 00:37:38 +00004494 if (Constant *LoadCst = ConstantFoldLoadFromConstPtr(LoadInput, Builder.TD))
4495 return Builder.getValue(LoadCst);
4496 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004497
Chris Lattner8047d9a2009-12-24 00:37:38 +00004498 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
4499 // still constant memory, the input chain can be the entry node.
4500 SDValue Root;
4501 bool ConstantMemory = false;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004502
Chris Lattner8047d9a2009-12-24 00:37:38 +00004503 // Do not serialize (non-volatile) loads of constant memory with anything.
4504 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
4505 Root = Builder.DAG.getEntryNode();
4506 ConstantMemory = true;
4507 } else {
4508 // Do not serialize non-volatile loads against each other.
4509 Root = Builder.DAG.getRoot();
4510 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004511
Chris Lattner8047d9a2009-12-24 00:37:38 +00004512 SDValue Ptr = Builder.getValue(PtrVal);
4513 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root,
4514 Ptr, PtrVal /*SrcValue*/, 0/*SVOffset*/,
4515 false /*volatile*/, 1 /* align=1 */);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004516
Chris Lattner8047d9a2009-12-24 00:37:38 +00004517 if (!ConstantMemory)
4518 Builder.PendingLoads.push_back(LoadVal.getValue(1));
4519 return LoadVal;
4520}
4521
4522
4523/// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
4524/// If so, return true and lower it, otherwise return false and it will be
4525/// lowered like a normal call.
4526bool SelectionDAGBuilder::visitMemCmpCall(CallInst &I) {
4527 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
4528 if (I.getNumOperands() != 4)
4529 return false;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004530
Chris Lattner8047d9a2009-12-24 00:37:38 +00004531 Value *LHS = I.getOperand(1), *RHS = I.getOperand(2);
4532 if (!isa<PointerType>(LHS->getType()) || !isa<PointerType>(RHS->getType()) ||
4533 !isa<IntegerType>(I.getOperand(3)->getType()) ||
4534 !isa<IntegerType>(I.getType()))
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004535 return false;
4536
Chris Lattner8047d9a2009-12-24 00:37:38 +00004537 ConstantInt *Size = dyn_cast<ConstantInt>(I.getOperand(3));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004538
Chris Lattner8047d9a2009-12-24 00:37:38 +00004539 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
4540 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
Chris Lattner04b091a2009-12-24 01:07:17 +00004541 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) {
4542 bool ActuallyDoIt = true;
4543 MVT LoadVT;
4544 const Type *LoadTy;
4545 switch (Size->getZExtValue()) {
4546 default:
4547 LoadVT = MVT::Other;
4548 LoadTy = 0;
4549 ActuallyDoIt = false;
4550 break;
4551 case 2:
4552 LoadVT = MVT::i16;
4553 LoadTy = Type::getInt16Ty(Size->getContext());
4554 break;
4555 case 4:
4556 LoadVT = MVT::i32;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004557 LoadTy = Type::getInt32Ty(Size->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00004558 break;
4559 case 8:
4560 LoadVT = MVT::i64;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004561 LoadTy = Type::getInt64Ty(Size->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00004562 break;
4563 /*
4564 case 16:
4565 LoadVT = MVT::v4i32;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004566 LoadTy = Type::getInt32Ty(Size->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00004567 LoadTy = VectorType::get(LoadTy, 4);
4568 break;
4569 */
4570 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004571
Chris Lattner04b091a2009-12-24 01:07:17 +00004572 // This turns into unaligned loads. We only do this if the target natively
4573 // supports the MVT we'll be loading or if it is small enough (<= 4) that
4574 // we'll only produce a small number of byte loads.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004575
Chris Lattner04b091a2009-12-24 01:07:17 +00004576 // Require that we can find a legal MVT, and only do this if the target
4577 // supports unaligned loads of that type. Expanding into byte loads would
4578 // bloat the code.
4579 if (ActuallyDoIt && Size->getZExtValue() > 4) {
4580 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
4581 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
4582 if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT))
4583 ActuallyDoIt = false;
4584 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004585
Chris Lattner04b091a2009-12-24 01:07:17 +00004586 if (ActuallyDoIt) {
4587 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
4588 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004589
Chris Lattner04b091a2009-12-24 01:07:17 +00004590 SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal,
4591 ISD::SETNE);
4592 EVT CallVT = TLI.getValueType(I.getType(), true);
4593 setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT));
4594 return true;
4595 }
Chris Lattner8047d9a2009-12-24 00:37:38 +00004596 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004597
4598
Chris Lattner8047d9a2009-12-24 00:37:38 +00004599 return false;
4600}
4601
4602
Dan Gohman2048b852009-11-23 18:04:58 +00004603void SelectionDAGBuilder::visitCall(CallInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004604 const char *RenameFn = 0;
4605 if (Function *F = I.getCalledFunction()) {
4606 if (F->isDeclaration()) {
Dale Johannesen49de9822009-02-05 01:49:45 +00004607 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4608 if (II) {
4609 if (unsigned IID = II->getIntrinsicID(F)) {
4610 RenameFn = visitIntrinsicCall(I, IID);
4611 if (!RenameFn)
4612 return;
4613 }
4614 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004615 if (unsigned IID = F->getIntrinsicID()) {
4616 RenameFn = visitIntrinsicCall(I, IID);
4617 if (!RenameFn)
4618 return;
4619 }
4620 }
4621
4622 // Check for well-known libc/libm calls. If the function is internal, it
4623 // can't be a library call.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004624 if (!F->hasLocalLinkage() && F->hasName()) {
4625 StringRef Name = F->getName();
4626 if (Name == "copysign" || Name == "copysignf") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004627 if (I.getNumOperands() == 3 && // Basic sanity checks.
4628 I.getOperand(1)->getType()->isFloatingPoint() &&
4629 I.getType() == I.getOperand(1)->getType() &&
4630 I.getType() == I.getOperand(2)->getType()) {
4631 SDValue LHS = getValue(I.getOperand(1));
4632 SDValue RHS = getValue(I.getOperand(2));
Bill Wendling0d580132009-12-23 01:28:19 +00004633 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
4634 LHS.getValueType(), LHS, RHS));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004635 return;
4636 }
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004637 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004638 if (I.getNumOperands() == 2 && // Basic sanity checks.
4639 I.getOperand(1)->getType()->isFloatingPoint() &&
4640 I.getType() == I.getOperand(1)->getType()) {
4641 SDValue Tmp = getValue(I.getOperand(1));
Bill Wendling0d580132009-12-23 01:28:19 +00004642 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
4643 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004644 return;
4645 }
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004646 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004647 if (I.getNumOperands() == 2 && // Basic sanity checks.
4648 I.getOperand(1)->getType()->isFloatingPoint() &&
Dale Johannesena45bfd32009-09-25 18:00:35 +00004649 I.getType() == I.getOperand(1)->getType() &&
4650 I.onlyReadsMemory()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004651 SDValue Tmp = getValue(I.getOperand(1));
Bill Wendling0d580132009-12-23 01:28:19 +00004652 setValue(&I, DAG.getNode(ISD::FSIN, 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 == "cos" || Name == "cosf" || Name == "cosl") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004657 if (I.getNumOperands() == 2 && // Basic sanity checks.
4658 I.getOperand(1)->getType()->isFloatingPoint() &&
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::FCOS, getCurDebugLoc(),
4663 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004664 return;
4665 }
Dale Johannesen52fb79b2009-09-25 17:23:22 +00004666 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
4667 if (I.getNumOperands() == 2 && // Basic sanity checks.
4668 I.getOperand(1)->getType()->isFloatingPoint() &&
Dale Johannesena45bfd32009-09-25 18:00:35 +00004669 I.getType() == I.getOperand(1)->getType() &&
4670 I.onlyReadsMemory()) {
Dale Johannesen52fb79b2009-09-25 17:23:22 +00004671 SDValue Tmp = getValue(I.getOperand(1));
Bill Wendling0d580132009-12-23 01:28:19 +00004672 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
4673 Tmp.getValueType(), Tmp));
Dale Johannesen52fb79b2009-09-25 17:23:22 +00004674 return;
4675 }
Chris Lattner8047d9a2009-12-24 00:37:38 +00004676 } else if (Name == "memcmp") {
4677 if (visitMemCmpCall(I))
4678 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004679 }
4680 }
4681 } else if (isa<InlineAsm>(I.getOperand(0))) {
4682 visitInlineAsm(&I);
4683 return;
4684 }
4685
4686 SDValue Callee;
4687 if (!RenameFn)
4688 Callee = getValue(I.getOperand(0));
4689 else
Bill Wendling056292f2008-09-16 21:48:12 +00004690 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004691
Bill Wendling0d580132009-12-23 01:28:19 +00004692 // Check if we can potentially perform a tail call. More detailed checking is
4693 // be done within LowerCallTo, after more information about the call is known.
Evan Cheng11e67932010-01-26 23:13:04 +00004694 LowerCallTo(&I, Callee, I.isTailCall());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004695}
4696
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004697/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004698/// this value and returns the result as a ValueVT value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004699/// Chain/Flag as the input and updates them for the output Chain/Flag.
4700/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004701SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
Bill Wendlingec72e322009-12-22 01:11:43 +00004702 unsigned Order, SDValue &Chain,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004703 SDValue *Flag) const {
4704 // Assemble the legal parts into the final values.
4705 SmallVector<SDValue, 4> Values(ValueVTs.size());
4706 SmallVector<SDValue, 8> Parts;
4707 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4708 // Copy the legal parts from the registers.
Owen Andersone50ed302009-08-10 22:56:29 +00004709 EVT ValueVT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00004710 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
Owen Andersone50ed302009-08-10 22:56:29 +00004711 EVT RegisterVT = RegVTs[Value];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004712
4713 Parts.resize(NumRegs);
4714 for (unsigned i = 0; i != NumRegs; ++i) {
4715 SDValue P;
Bill Wendlingec72e322009-12-22 01:11:43 +00004716 if (Flag == 0) {
Dale Johannesena04b7572009-02-03 23:04:43 +00004717 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
Bill Wendlingec72e322009-12-22 01:11:43 +00004718 } else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004719 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004720 *Flag = P.getValue(2);
4721 }
Bill Wendlingec72e322009-12-22 01:11:43 +00004722
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004723 Chain = P.getValue(1);
Bill Wendlingec72e322009-12-22 01:11:43 +00004724
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004725 // If the source register was virtual and if we know something about it,
4726 // add an assert node.
4727 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4728 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4729 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4730 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4731 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4732 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004733
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004734 unsigned RegSize = RegisterVT.getSizeInBits();
4735 unsigned NumSignBits = LOI.NumSignBits;
4736 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004737
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004738 // FIXME: We capture more information than the dag can represent. For
4739 // now, just use the tightest assertzext/assertsext possible.
4740 bool isSExt = true;
Owen Anderson825b72b2009-08-11 20:47:22 +00004741 EVT FromVT(MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004742 if (NumSignBits == RegSize)
Owen Anderson825b72b2009-08-11 20:47:22 +00004743 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004744 else if (NumZeroBits >= RegSize-1)
Owen Anderson825b72b2009-08-11 20:47:22 +00004745 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004746 else if (NumSignBits > RegSize-8)
Owen Anderson825b72b2009-08-11 20:47:22 +00004747 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
Dan Gohman07c26ee2009-03-31 01:38:29 +00004748 else if (NumZeroBits >= RegSize-8)
Owen Anderson825b72b2009-08-11 20:47:22 +00004749 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004750 else if (NumSignBits > RegSize-16)
Owen Anderson825b72b2009-08-11 20:47:22 +00004751 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
Dan Gohman07c26ee2009-03-31 01:38:29 +00004752 else if (NumZeroBits >= RegSize-16)
Owen Anderson825b72b2009-08-11 20:47:22 +00004753 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004754 else if (NumSignBits > RegSize-32)
Owen Anderson825b72b2009-08-11 20:47:22 +00004755 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
Dan Gohman07c26ee2009-03-31 01:38:29 +00004756 else if (NumZeroBits >= RegSize-32)
Owen Anderson825b72b2009-08-11 20:47:22 +00004757 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004758
Bill Wendling4533cac2010-01-28 21:51:40 +00004759 if (FromVT != MVT::Other)
Dale Johannesen66978ee2009-01-31 02:22:37 +00004760 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004761 RegisterVT, P, DAG.getValueType(FromVT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004762 }
4763 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004764
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004765 Parts[i] = P;
4766 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004767
Bill Wendling3ea3c242009-12-22 02:10:19 +00004768 Values[Value] = getCopyFromParts(DAG, dl, Order, Parts.begin(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00004769 NumRegs, RegisterVT, ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004770 Part += NumRegs;
4771 Parts.clear();
4772 }
4773
Bill Wendling4533cac2010-01-28 21:51:40 +00004774 return DAG.getNode(ISD::MERGE_VALUES, dl,
4775 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4776 &Values[0], ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004777}
4778
4779/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004780/// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004781/// Chain/Flag as the input and updates them for the output Chain/Flag.
4782/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004783void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Bill Wendlingec72e322009-12-22 01:11:43 +00004784 unsigned Order, SDValue &Chain,
4785 SDValue *Flag) const {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004786 // Get the list of the values's legal parts.
4787 unsigned NumRegs = Regs.size();
4788 SmallVector<SDValue, 8> Parts(NumRegs);
4789 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00004790 EVT ValueVT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00004791 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
Owen Andersone50ed302009-08-10 22:56:29 +00004792 EVT RegisterVT = RegVTs[Value];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004793
Bill Wendling3ea3c242009-12-22 02:10:19 +00004794 getCopyToParts(DAG, dl, Order,
4795 Val.getValue(Val.getResNo() + Value),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004796 &Parts[Part], NumParts, RegisterVT);
4797 Part += NumParts;
4798 }
4799
4800 // Copy the parts into the registers.
4801 SmallVector<SDValue, 8> Chains(NumRegs);
4802 for (unsigned i = 0; i != NumRegs; ++i) {
4803 SDValue Part;
Bill Wendlingec72e322009-12-22 01:11:43 +00004804 if (Flag == 0) {
Dale Johannesena04b7572009-02-03 23:04:43 +00004805 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
Bill Wendlingec72e322009-12-22 01:11:43 +00004806 } else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004807 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004808 *Flag = Part.getValue(1);
4809 }
Bill Wendlingec72e322009-12-22 01:11:43 +00004810
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004811 Chains[i] = Part.getValue(0);
4812 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004813
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004814 if (NumRegs == 1 || Flag)
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004815 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004816 // flagged to it. That is the CopyToReg nodes and the user are considered
4817 // a single scheduling unit. If we create a TokenFactor and return it as
4818 // chain, then the TokenFactor is both a predecessor (operand) of the
4819 // user as well as a successor (the TF operands are flagged to the user).
4820 // c1, f1 = CopyToReg
4821 // c2, f2 = CopyToReg
4822 // c3 = TokenFactor c1, c2
4823 // ...
4824 // = op c3, ..., f2
4825 Chain = Chains[NumRegs-1];
4826 else
Owen Anderson825b72b2009-08-11 20:47:22 +00004827 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004828}
4829
4830/// AddInlineAsmOperands - Add this value to the specified inlineasm node
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004831/// operand list. This adds the code marker and includes the number of
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004832/// values added into it.
Evan Cheng697cbbf2009-03-20 18:03:34 +00004833void RegsForValue::AddInlineAsmOperands(unsigned Code,
4834 bool HasMatching,unsigned MatchingIdx,
Bill Wendling651ad132009-12-22 01:25:10 +00004835 SelectionDAG &DAG, unsigned Order,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004836 std::vector<SDValue> &Ops) const {
Evan Cheng697cbbf2009-03-20 18:03:34 +00004837 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
4838 unsigned Flag = Code | (Regs.size() << 3);
4839 if (HasMatching)
4840 Flag |= 0x80000000 | (MatchingIdx << 16);
Dale Johannesen99499332009-12-23 07:32:51 +00004841 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
Bill Wendling651ad132009-12-22 01:25:10 +00004842 Ops.push_back(Res);
4843
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004844 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
Owen Anderson23b9b192009-08-12 00:36:31 +00004845 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
Owen Andersone50ed302009-08-10 22:56:29 +00004846 EVT RegisterVT = RegVTs[Value];
Chris Lattner58f15c42008-10-17 16:21:11 +00004847 for (unsigned i = 0; i != NumRegs; ++i) {
4848 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Bill Wendling4533cac2010-01-28 21:51:40 +00004849 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner58f15c42008-10-17 16:21:11 +00004850 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004851 }
4852}
4853
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004854/// isAllocatableRegister - If the specified register is safe to allocate,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004855/// i.e. it isn't a stack pointer or some other special register, return the
4856/// register class for the register. Otherwise, return null.
4857static const TargetRegisterClass *
4858isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4859 const TargetLowering &TLI,
4860 const TargetRegisterInfo *TRI) {
Owen Anderson825b72b2009-08-11 20:47:22 +00004861 EVT FoundVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004862 const TargetRegisterClass *FoundRC = 0;
4863 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4864 E = TRI->regclass_end(); RCI != E; ++RCI) {
Owen Anderson825b72b2009-08-11 20:47:22 +00004865 EVT ThisVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004866
4867 const TargetRegisterClass *RC = *RCI;
Dan Gohmanf451cb82010-02-10 16:03:48 +00004868 // If none of the value types for this register class are valid, we
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004869 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4870 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4871 I != E; ++I) {
4872 if (TLI.isTypeLegal(*I)) {
4873 // If we have already found this register in a different register class,
4874 // choose the one with the largest VT specified. For example, on
4875 // PowerPC, we favor f64 register classes over f32.
Owen Anderson825b72b2009-08-11 20:47:22 +00004876 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004877 ThisVT = *I;
4878 break;
4879 }
4880 }
4881 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004882
Owen Anderson825b72b2009-08-11 20:47:22 +00004883 if (ThisVT == MVT::Other) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004884
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004885 // NOTE: This isn't ideal. In particular, this might allocate the
4886 // frame pointer in functions that need it (due to them not being taken
4887 // out of allocation, because a variable sized allocation hasn't been seen
4888 // yet). This is a slight code pessimization, but should still work.
4889 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4890 E = RC->allocation_order_end(MF); I != E; ++I)
4891 if (*I == Reg) {
4892 // We found a matching register class. Keep looking at others in case
4893 // we find one with larger registers that this physreg is also in.
4894 FoundRC = RC;
4895 FoundVT = ThisVT;
4896 break;
4897 }
4898 }
4899 return FoundRC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004900}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004901
4902
4903namespace llvm {
4904/// AsmOperandInfo - This contains information for each constraint that we are
4905/// lowering.
Cedric Venetaff9c272009-02-14 16:06:42 +00004906class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
Daniel Dunbarc0c3b9a2008-09-10 04:16:29 +00004907 public TargetLowering::AsmOperandInfo {
Cedric Venetaff9c272009-02-14 16:06:42 +00004908public:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004909 /// CallOperand - If this is the result output operand or a clobber
4910 /// this is null, otherwise it is the incoming operand to the CallInst.
4911 /// This gets modified as the asm is processed.
4912 SDValue CallOperand;
4913
4914 /// AssignedRegs - If this is a register or register class operand, this
4915 /// contains the set of register corresponding to the operand.
4916 RegsForValue AssignedRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004917
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004918 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4919 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4920 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004921
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004922 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4923 /// busy in OutputRegs/InputRegs.
4924 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004925 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004926 std::set<unsigned> &InputRegs,
4927 const TargetRegisterInfo &TRI) const {
4928 if (isOutReg) {
4929 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4930 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4931 }
4932 if (isInReg) {
4933 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4934 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4935 }
4936 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004937
Owen Andersone50ed302009-08-10 22:56:29 +00004938 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
Chris Lattner81249c92008-10-17 17:05:25 +00004939 /// corresponds to. If there is no Value* for this operand, it returns
Owen Anderson825b72b2009-08-11 20:47:22 +00004940 /// MVT::Other.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004941 EVT getCallOperandValEVT(LLVMContext &Context,
Owen Anderson1d0be152009-08-13 21:58:54 +00004942 const TargetLowering &TLI,
Chris Lattner81249c92008-10-17 17:05:25 +00004943 const TargetData *TD) const {
Owen Anderson825b72b2009-08-11 20:47:22 +00004944 if (CallOperandVal == 0) return MVT::Other;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004945
Chris Lattner81249c92008-10-17 17:05:25 +00004946 if (isa<BasicBlock>(CallOperandVal))
4947 return TLI.getPointerTy();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004948
Chris Lattner81249c92008-10-17 17:05:25 +00004949 const llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004950
Chris Lattner81249c92008-10-17 17:05:25 +00004951 // If this is an indirect operand, the operand is a pointer to the
4952 // accessed type.
Bob Wilsone261b0c2009-12-22 18:34:19 +00004953 if (isIndirect) {
4954 const llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
4955 if (!PtrTy)
4956 llvm_report_error("Indirect operand for inline asm not a pointer!");
4957 OpTy = PtrTy->getElementType();
4958 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004959
Chris Lattner81249c92008-10-17 17:05:25 +00004960 // If OpTy is not a single value, it may be a struct/union that we
4961 // can tile with integers.
4962 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4963 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4964 switch (BitSize) {
4965 default: break;
4966 case 1:
4967 case 8:
4968 case 16:
4969 case 32:
4970 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00004971 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00004972 OpTy = IntegerType::get(Context, BitSize);
Chris Lattner81249c92008-10-17 17:05:25 +00004973 break;
4974 }
4975 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004976
Chris Lattner81249c92008-10-17 17:05:25 +00004977 return TLI.getValueType(OpTy, true);
4978 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004979
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004980private:
4981 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4982 /// specified set.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004983 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004984 const TargetRegisterInfo &TRI) {
4985 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4986 Regs.insert(Reg);
4987 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4988 for (; *Aliases; ++Aliases)
4989 Regs.insert(*Aliases);
4990 }
4991};
4992} // end llvm namespace.
4993
4994
4995/// GetRegistersForValue - Assign registers (virtual or physical) for the
4996/// specified operand. We prefer to assign virtual registers, to allow the
Bob Wilson266d9452009-12-17 05:07:36 +00004997/// register allocator to handle the assignment process. However, if the asm
4998/// uses features that we can't model on machineinstrs, we have SDISel do the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004999/// allocation. This produces generally horrible, but correct, code.
5000///
5001/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005002/// Input and OutputRegs are the set of already allocated physical registers.
5003///
Dan Gohman2048b852009-11-23 18:04:58 +00005004void SelectionDAGBuilder::
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005005GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005006 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005007 std::set<unsigned> &InputRegs) {
Dan Gohman0d24bfb2009-08-15 02:06:22 +00005008 LLVMContext &Context = FuncInfo.Fn->getContext();
Owen Anderson23b9b192009-08-12 00:36:31 +00005009
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005010 // Compute whether this value requires an input register, an output register,
5011 // or both.
5012 bool isOutReg = false;
5013 bool isInReg = false;
5014 switch (OpInfo.Type) {
5015 case InlineAsm::isOutput:
5016 isOutReg = true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005017
5018 // If there is an input constraint that matches this, we need to reserve
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005019 // the input register so no other inputs allocate to it.
Chris Lattner6bdcda32008-10-17 16:47:46 +00005020 isInReg = OpInfo.hasMatchingInput();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005021 break;
5022 case InlineAsm::isInput:
5023 isInReg = true;
5024 isOutReg = false;
5025 break;
5026 case InlineAsm::isClobber:
5027 isOutReg = true;
5028 isInReg = true;
5029 break;
5030 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005031
5032
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005033 MachineFunction &MF = DAG.getMachineFunction();
5034 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005035
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005036 // If this is a constraint for a single physreg, or a constraint for a
5037 // register class, find it.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005038 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005039 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5040 OpInfo.ConstraintVT);
5041
5042 unsigned NumRegs = 1;
Owen Anderson825b72b2009-08-11 20:47:22 +00005043 if (OpInfo.ConstraintVT != MVT::Other) {
Chris Lattner01426e12008-10-21 00:45:36 +00005044 // If this is a FP input in an integer register (or visa versa) insert a bit
5045 // cast of the input value. More generally, handle any case where the input
5046 // value disagrees with the register class we plan to stick this in.
5047 if (OpInfo.Type == InlineAsm::isInput &&
5048 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
Owen Andersone50ed302009-08-10 22:56:29 +00005049 // Try to convert to the first EVT that the reg class contains. If the
Chris Lattner01426e12008-10-21 00:45:36 +00005050 // types are identical size, use a bitcast to convert (e.g. two differing
5051 // vector types).
Owen Andersone50ed302009-08-10 22:56:29 +00005052 EVT RegVT = *PhysReg.second->vt_begin();
Chris Lattner01426e12008-10-21 00:45:36 +00005053 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005054 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005055 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00005056 OpInfo.ConstraintVT = RegVT;
5057 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5058 // If the input is a FP value and we want it in FP registers, do a
5059 // bitcast to the corresponding integer type. This turns an f64 value
5060 // into i64, which can be passed with two i32 values on a 32-bit
5061 // machine.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005062 RegVT = EVT::getIntegerVT(Context,
Owen Anderson23b9b192009-08-12 00:36:31 +00005063 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 }
5068 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005069
Owen Anderson23b9b192009-08-12 00:36:31 +00005070 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00005071 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005072
Owen Andersone50ed302009-08-10 22:56:29 +00005073 EVT RegVT;
5074 EVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005075
5076 // If this is a constraint for a specific physical register, like {r17},
5077 // assign it now.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005078 if (unsigned AssignedReg = PhysReg.first) {
5079 const TargetRegisterClass *RC = PhysReg.second;
Owen Anderson825b72b2009-08-11 20:47:22 +00005080 if (OpInfo.ConstraintVT == MVT::Other)
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005081 ValueVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005082
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005083 // Get the actual register value type. This is important, because the user
5084 // may have asked for (e.g.) the AX register in i32 type. We need to
5085 // remember that AX is actually i16 to get the right extension.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005086 RegVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005087
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005088 // This is a explicit reference to a physical register.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005089 Regs.push_back(AssignedReg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005090
5091 // If this is an expanded reference, add the rest of the regs to Regs.
5092 if (NumRegs != 1) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005093 TargetRegisterClass::iterator I = RC->begin();
5094 for (; *I != AssignedReg; ++I)
5095 assert(I != RC->end() && "Didn't find reg!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005096
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005097 // Already added the first reg.
5098 --NumRegs; ++I;
5099 for (; NumRegs; --NumRegs, ++I) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005100 assert(I != RC->end() && "Ran out of registers to allocate!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005101 Regs.push_back(*I);
5102 }
5103 }
Bill Wendling651ad132009-12-22 01:25:10 +00005104
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005105 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5106 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5107 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5108 return;
5109 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005110
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005111 // Otherwise, if this was a reference to an LLVM register class, create vregs
5112 // for this reference.
Chris Lattnerb3b44842009-03-24 15:25:07 +00005113 if (const TargetRegisterClass *RC = PhysReg.second) {
5114 RegVT = *RC->vt_begin();
Owen Anderson825b72b2009-08-11 20:47:22 +00005115 if (OpInfo.ConstraintVT == MVT::Other)
Evan Chengfb112882009-03-23 08:01:15 +00005116 ValueVT = RegVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005117
Evan Chengfb112882009-03-23 08:01:15 +00005118 // Create the appropriate number of virtual registers.
5119 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5120 for (; NumRegs; --NumRegs)
Chris Lattnerb3b44842009-03-24 15:25:07 +00005121 Regs.push_back(RegInfo.createVirtualRegister(RC));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005122
Evan Chengfb112882009-03-23 08:01:15 +00005123 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5124 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005125 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005126
Chris Lattnerfc9d1612009-03-24 15:22:11 +00005127 // This is a reference to a register class that doesn't directly correspond
5128 // to an LLVM register class. Allocate NumRegs consecutive, available,
5129 // registers from the class.
5130 std::vector<unsigned> RegClassRegs
5131 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5132 OpInfo.ConstraintVT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005133
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005134 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5135 unsigned NumAllocated = 0;
5136 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5137 unsigned Reg = RegClassRegs[i];
5138 // See if this register is available.
5139 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5140 (isInReg && InputRegs.count(Reg))) { // Already used.
5141 // Make sure we find consecutive registers.
5142 NumAllocated = 0;
5143 continue;
5144 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005145
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005146 // Check to see if this register is allocatable (i.e. don't give out the
5147 // stack pointer).
Chris Lattnerfc9d1612009-03-24 15:22:11 +00005148 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5149 if (!RC) { // Couldn't allocate this register.
5150 // Reset NumAllocated to make sure we return consecutive registers.
5151 NumAllocated = 0;
5152 continue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005153 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005154
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005155 // Okay, this register is good, we can use it.
5156 ++NumAllocated;
5157
5158 // If we allocated enough consecutive registers, succeed.
5159 if (NumAllocated == NumRegs) {
5160 unsigned RegStart = (i-NumAllocated)+1;
5161 unsigned RegEnd = i+1;
5162 // Mark all of the allocated registers used.
5163 for (unsigned i = RegStart; i != RegEnd; ++i)
5164 Regs.push_back(RegClassRegs[i]);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005165
5166 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005167 OpInfo.ConstraintVT);
5168 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5169 return;
5170 }
5171 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005172
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005173 // Otherwise, we couldn't allocate enough registers for this.
5174}
5175
Evan Chengda43bcf2008-09-24 00:05:32 +00005176/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5177/// processed uses a memory 'm' constraint.
5178static bool
5179hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
Dan Gohmane9530ec2009-01-15 16:58:17 +00005180 const TargetLowering &TLI) {
Evan Chengda43bcf2008-09-24 00:05:32 +00005181 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5182 InlineAsm::ConstraintInfo &CI = CInfos[i];
5183 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5184 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5185 if (CType == TargetLowering::C_Memory)
5186 return true;
5187 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005188
Chris Lattner6c147292009-04-30 00:48:50 +00005189 // Indirect operand accesses access memory.
5190 if (CI.isIndirect)
5191 return true;
Evan Chengda43bcf2008-09-24 00:05:32 +00005192 }
5193
5194 return false;
5195}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005196
5197/// visitInlineAsm - Handle a call to an InlineAsm object.
5198///
Dan Gohman2048b852009-11-23 18:04:58 +00005199void SelectionDAGBuilder::visitInlineAsm(CallSite CS) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005200 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5201
5202 /// ConstraintOperands - Information about all of the constraints.
5203 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005204
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005205 std::set<unsigned> OutputRegs, InputRegs;
5206
5207 // Do a prepass over the constraints, canonicalizing them, and building up the
5208 // ConstraintOperands list.
5209 std::vector<InlineAsm::ConstraintInfo>
5210 ConstraintInfos = IA->ParseConstraints();
5211
Evan Chengda43bcf2008-09-24 00:05:32 +00005212 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005213
Chris Lattner6c147292009-04-30 00:48:50 +00005214 SDValue Chain, Flag;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005215
Chris Lattner6c147292009-04-30 00:48:50 +00005216 // We won't need to flush pending loads if this asm doesn't touch
5217 // memory and is nonvolatile.
5218 if (hasMemory || IA->hasSideEffects())
Dale Johannesen97d14fc2009-04-18 00:09:40 +00005219 Chain = getRoot();
Chris Lattner6c147292009-04-30 00:48:50 +00005220 else
5221 Chain = DAG.getRoot();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005222
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005223 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5224 unsigned ResNo = 0; // ResNo - The result number of the next output.
5225 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5226 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5227 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005228
Owen Anderson825b72b2009-08-11 20:47:22 +00005229 EVT OpVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005230
5231 // Compute the value type for each operand.
5232 switch (OpInfo.Type) {
5233 case InlineAsm::isOutput:
5234 // Indirect outputs just consume an argument.
5235 if (OpInfo.isIndirect) {
5236 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5237 break;
5238 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005239
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005240 // The return value of the call is this value. As such, there is no
5241 // corresponding argument.
Benjamin Kramerf0127052010-01-05 13:12:22 +00005242 assert(!CS.getType()->isVoidTy() &&
Owen Anderson1d0be152009-08-13 21:58:54 +00005243 "Bad inline asm!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005244 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5245 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5246 } else {
5247 assert(ResNo == 0 && "Asm only has one result!");
5248 OpVT = TLI.getValueType(CS.getType());
5249 }
5250 ++ResNo;
5251 break;
5252 case InlineAsm::isInput:
5253 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5254 break;
5255 case InlineAsm::isClobber:
5256 // Nothing to do.
5257 break;
5258 }
5259
5260 // If this is an input or an indirect output, process the call argument.
5261 // BasicBlocks are labels, currently appearing only in asm's.
5262 if (OpInfo.CallOperandVal) {
Dale Johannesen5339c552009-07-20 23:27:39 +00005263 // Strip bitcasts, if any. This mostly comes up for functions.
Dale Johannesen76711242009-08-06 22:45:51 +00005264 OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts();
5265
Chris Lattner81249c92008-10-17 17:05:25 +00005266 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005267 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00005268 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005269 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005270 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005271
Owen Anderson1d0be152009-08-13 21:58:54 +00005272 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005273 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005274
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005275 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005276 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005277
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005278 // Second pass over the constraints: compute which constraint option to use
5279 // and assign registers to constraints that want a specific physreg.
5280 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5281 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005282
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005283 // If this is an output operand with a matching input operand, look up the
Evan Cheng09dc9c02008-12-16 18:21:39 +00005284 // matching input. If their types mismatch, e.g. one is an integer, the
5285 // other is floating point, or their sizes are different, flag it as an
5286 // error.
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005287 if (OpInfo.hasMatchingInput()) {
5288 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5289 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Evan Cheng09dc9c02008-12-16 18:21:39 +00005290 if ((OpInfo.ConstraintVT.isInteger() !=
5291 Input.ConstraintVT.isInteger()) ||
5292 (OpInfo.ConstraintVT.getSizeInBits() !=
5293 Input.ConstraintVT.getSizeInBits())) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005294 llvm_report_error("Unsupported asm: input constraint"
Torok Edwin7d696d82009-07-11 13:10:19 +00005295 " with a matching output constraint of incompatible"
5296 " type!");
Evan Cheng09dc9c02008-12-16 18:21:39 +00005297 }
5298 Input.ConstraintVT = OpInfo.ConstraintVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005299 }
5300 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005301
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005302 // Compute the constraint code and ConstraintType to use.
Evan Chengda43bcf2008-09-24 00:05:32 +00005303 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005304
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005305 // If this is a memory input, and if the operand is not indirect, do what we
5306 // need to to provide an address for the memory input.
5307 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5308 !OpInfo.isIndirect) {
5309 assert(OpInfo.Type == InlineAsm::isInput &&
5310 "Can only indirectify direct input operands!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005311
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005312 // Memory operands really want the address of the value. If we don't have
5313 // an indirect input, put it in the constpool if we can, otherwise spill
5314 // it to a stack slot.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005315
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005316 // If the operand is a float, integer, or vector constant, spill to a
5317 // constant pool entry to get its address.
5318 Value *OpVal = OpInfo.CallOperandVal;
5319 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5320 isa<ConstantVector>(OpVal)) {
5321 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5322 TLI.getPointerTy());
5323 } else {
5324 // Otherwise, create a stack slot and emit a store to it before the
5325 // asm.
5326 const Type *Ty = OpVal->getType();
Duncan Sands777d2302009-05-09 07:06:46 +00005327 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005328 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5329 MachineFunction &MF = DAG.getMachineFunction();
David Greene3f2bf852009-11-12 20:49:22 +00005330 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005331 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Dale Johannesen66978ee2009-01-31 02:22:37 +00005332 Chain = DAG.getStore(Chain, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005333 OpInfo.CallOperand, StackSlot, NULL, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005334 OpInfo.CallOperand = StackSlot;
5335 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005336
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005337 // There is no longer a Value* corresponding to this operand.
5338 OpInfo.CallOperandVal = 0;
Bill Wendling651ad132009-12-22 01:25:10 +00005339
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005340 // It is now an indirect operand.
5341 OpInfo.isIndirect = true;
5342 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005343
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005344 // If this constraint is for a specific register, allocate it before
5345 // anything else.
5346 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005347 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005348 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005349
Bill Wendling651ad132009-12-22 01:25:10 +00005350 ConstraintInfos.clear();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005351
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005352 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00005353 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005354 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5355 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005356
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005357 // C_Register operands have already been allocated, Other/Memory don't need
5358 // to be.
5359 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005360 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005361 }
5362
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005363 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5364 std::vector<SDValue> AsmNodeOperands;
5365 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5366 AsmNodeOperands.push_back(
Dan Gohmanf2d7fb32010-01-04 21:00:54 +00005367 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
5368 TLI.getPointerTy()));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005369
5370
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005371 // Loop over all of the inputs, copying the operand values into the
5372 // appropriate registers and processing the output regs.
5373 RegsForValue RetValRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005374
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005375 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5376 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005377
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005378 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5379 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5380
5381 switch (OpInfo.Type) {
5382 case InlineAsm::isOutput: {
5383 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5384 OpInfo.ConstraintType != TargetLowering::C_Register) {
5385 // Memory output, or 'other' output (e.g. 'X' constraint).
5386 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5387
5388 // Add information to the INLINEASM node to know about this output.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005389 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5390 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005391 TLI.getPointerTy()));
5392 AsmNodeOperands.push_back(OpInfo.CallOperand);
5393 break;
5394 }
5395
5396 // Otherwise, this is a register or register class output.
5397
5398 // Copy the output from the appropriate register. Find a register that
5399 // we can use.
5400 if (OpInfo.AssignedRegs.Regs.empty()) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005401 llvm_report_error("Couldn't allocate output reg for"
Torok Edwin7d696d82009-07-11 13:10:19 +00005402 " constraint '" + OpInfo.ConstraintCode + "'!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005403 }
5404
5405 // If this is an indirect operand, store through the pointer after the
5406 // asm.
5407 if (OpInfo.isIndirect) {
5408 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5409 OpInfo.CallOperandVal));
5410 } else {
5411 // This is the result value of the call.
Benjamin Kramerf0127052010-01-05 13:12:22 +00005412 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005413 // Concatenate this output onto the outputs list.
5414 RetValRegs.append(OpInfo.AssignedRegs);
5415 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005416
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005417 // Add information to the INLINEASM node to know that this register is
5418 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00005419 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5420 6 /* EARLYCLOBBER REGDEF */ :
5421 2 /* REGDEF */ ,
Evan Chengfb112882009-03-23 08:01:15 +00005422 false,
5423 0,
Bill Wendling651ad132009-12-22 01:25:10 +00005424 DAG, SDNodeOrder,
5425 AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005426 break;
5427 }
5428 case InlineAsm::isInput: {
5429 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005430
Chris Lattner6bdcda32008-10-17 16:47:46 +00005431 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005432 // If this is required to match an output register we have already set,
5433 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00005434 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005435
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005436 // Scan until we find the definition we already emitted of this operand.
5437 // When we find it, create a RegsForValue operand.
5438 unsigned CurOp = 2; // The first operand.
5439 for (; OperandNo; --OperandNo) {
5440 // Advance to the next operand.
Evan Cheng697cbbf2009-03-20 18:03:34 +00005441 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005442 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005443 assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5444 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5445 (OpFlag & 7) == 4 /*MEM*/) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005446 "Skipped past definitions?");
Evan Cheng697cbbf2009-03-20 18:03:34 +00005447 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005448 }
5449
Evan Cheng697cbbf2009-03-20 18:03:34 +00005450 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005451 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005452 if ((OpFlag & 7) == 2 /*REGDEF*/
5453 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5454 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
Dan Gohman15480bd2009-06-15 22:32:41 +00005455 if (OpInfo.isIndirect) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005456 llvm_report_error("Don't know how to handle tied indirect "
Torok Edwin7d696d82009-07-11 13:10:19 +00005457 "register inputs yet!");
Dan Gohman15480bd2009-06-15 22:32:41 +00005458 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005459 RegsForValue MatchedRegs;
5460 MatchedRegs.TLI = &TLI;
5461 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
Owen Andersone50ed302009-08-10 22:56:29 +00005462 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
Evan Chengfb112882009-03-23 08:01:15 +00005463 MatchedRegs.RegVTs.push_back(RegVT);
5464 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005465 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
Evan Chengfb112882009-03-23 08:01:15 +00005466 i != e; ++i)
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005467 MatchedRegs.Regs.push_back
5468 (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005469
5470 // Use the produced MatchedRegs object to
Dale Johannesen66978ee2009-01-31 02:22:37 +00005471 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
Bill Wendlingec72e322009-12-22 01:11:43 +00005472 SDNodeOrder, Chain, &Flag);
Evan Chengfb112882009-03-23 08:01:15 +00005473 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5474 true, OpInfo.getMatchedOperand(),
Bill Wendling651ad132009-12-22 01:25:10 +00005475 DAG, SDNodeOrder, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005476 break;
5477 } else {
Evan Cheng697cbbf2009-03-20 18:03:34 +00005478 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5479 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5480 "Unexpected number of operands");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005481 // Add information to the INLINEASM node to know about this input.
Evan Chengfb112882009-03-23 08:01:15 +00005482 // See InlineAsm.h isUseOperandTiedToDef.
5483 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
Evan Cheng697cbbf2009-03-20 18:03:34 +00005484 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005485 TLI.getPointerTy()));
5486 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5487 break;
5488 }
5489 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005490
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005491 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005492 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005493 "Don't know how to handle indirect other inputs yet!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005494
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005495 std::vector<SDValue> Ops;
5496 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Chengda43bcf2008-09-24 00:05:32 +00005497 hasMemory, Ops, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005498 if (Ops.empty()) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005499 llvm_report_error("Invalid operand for inline asm"
Torok Edwin7d696d82009-07-11 13:10:19 +00005500 " constraint '" + OpInfo.ConstraintCode + "'!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005501 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005502
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005503 // Add information to the INLINEASM node to know about this input.
5504 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005505 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005506 TLI.getPointerTy()));
5507 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5508 break;
5509 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5510 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5511 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5512 "Memory operands expect pointer values");
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.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005515 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5516 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005517 TLI.getPointerTy()));
5518 AsmNodeOperands.push_back(InOperandVal);
5519 break;
5520 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005521
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005522 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5523 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5524 "Unknown constraint type!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005525 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005526 "Don't know how to handle indirect register inputs yet!");
5527
5528 // Copy the input into the appropriate registers.
Evan Cheng8112b532010-02-10 01:21:02 +00005529 if (OpInfo.AssignedRegs.Regs.empty() ||
5530 !OpInfo.AssignedRegs.areValueTypesLegal()) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005531 llvm_report_error("Couldn't allocate input reg for"
Torok Edwin7d696d82009-07-11 13:10:19 +00005532 " constraint '"+ OpInfo.ConstraintCode +"'!");
Evan Chengaa765b82008-09-25 00:14:04 +00005533 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005534
Dale Johannesen66978ee2009-01-31 02:22:37 +00005535 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
Bill Wendlingec72e322009-12-22 01:11:43 +00005536 SDNodeOrder, Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005537
Evan Cheng697cbbf2009-03-20 18:03:34 +00005538 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
Bill Wendling651ad132009-12-22 01:25:10 +00005539 DAG, SDNodeOrder,
5540 AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005541 break;
5542 }
5543 case InlineAsm::isClobber: {
5544 // Add the clobbered value to the operand list, so that the register
5545 // allocator is aware that the physreg got clobbered.
5546 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesen91aac102008-09-17 21:13:11 +00005547 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
Bill Wendling651ad132009-12-22 01:25:10 +00005548 false, 0, DAG, SDNodeOrder,
5549 AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005550 break;
5551 }
5552 }
5553 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005554
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005555 // Finish up input operands.
5556 AsmNodeOperands[0] = Chain;
5557 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005558
Dale Johannesen66978ee2009-01-31 02:22:37 +00005559 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00005560 DAG.getVTList(MVT::Other, MVT::Flag),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005561 &AsmNodeOperands[0], AsmNodeOperands.size());
5562 Flag = Chain.getValue(1);
5563
5564 // If this asm returns a register value, copy the result from that register
5565 // and set it as the value of the call.
5566 if (!RetValRegs.Regs.empty()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00005567 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
Bill Wendlingec72e322009-12-22 01:11:43 +00005568 SDNodeOrder, Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005569
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005570 // FIXME: Why don't we do this for inline asms with MRVs?
5571 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
Owen Andersone50ed302009-08-10 22:56:29 +00005572 EVT ResultType = TLI.getValueType(CS.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005573
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005574 // If any of the results of the inline asm is a vector, it may have the
5575 // wrong width/num elts. This can happen for register classes that can
5576 // contain multiple different value types. The preg or vreg allocated may
5577 // not have the same VT as was expected. Convert it to the right type
5578 // with bit_convert.
5579 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005580 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005581 ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005582
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005583 } else if (ResultType != Val.getValueType() &&
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005584 ResultType.isInteger() && Val.getValueType().isInteger()) {
5585 // If a result value was tied to an input value, the computed result may
5586 // have a wider width than the expected result. Extract the relevant
5587 // portion.
Dale Johannesen66978ee2009-01-31 02:22:37 +00005588 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005589 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005590
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005591 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00005592 }
Dan Gohman95915732008-10-18 01:03:45 +00005593
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005594 setValue(CS.getInstruction(), Val);
Dale Johannesenec65a7d2009-04-14 00:56:56 +00005595 // Don't need to use this as a chain in this case.
5596 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5597 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005598 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005599
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005600 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005601
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005602 // Process indirect outputs, first output all of the flagged copies out of
5603 // physregs.
5604 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5605 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5606 Value *Ptr = IndirectStoresToEmit[i].second;
Dale Johannesen66978ee2009-01-31 02:22:37 +00005607 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
Bill Wendlingec72e322009-12-22 01:11:43 +00005608 SDNodeOrder, Chain, &Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005609 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6c147292009-04-30 00:48:50 +00005610
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005611 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005612
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005613 // Emit the non-flagged stores from the physregs.
5614 SmallVector<SDValue, 8> OutChains;
Bill Wendling651ad132009-12-22 01:25:10 +00005615 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
5616 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
5617 StoresToEmit[i].first,
5618 getValue(StoresToEmit[i].second),
5619 StoresToEmit[i].second, 0);
5620 OutChains.push_back(Val);
Bill Wendling651ad132009-12-22 01:25:10 +00005621 }
5622
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005623 if (!OutChains.empty())
Owen Anderson825b72b2009-08-11 20:47:22 +00005624 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005625 &OutChains[0], OutChains.size());
Bill Wendling651ad132009-12-22 01:25:10 +00005626
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005627 DAG.setRoot(Chain);
5628}
5629
Dan Gohman2048b852009-11-23 18:04:58 +00005630void SelectionDAGBuilder::visitVAStart(CallInst &I) {
Bill Wendlingc1d3c942009-12-23 00:44:51 +00005631 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
5632 MVT::Other, getRoot(),
5633 getValue(I.getOperand(1)),
5634 DAG.getSrcValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005635}
5636
Dan Gohman2048b852009-11-23 18:04:58 +00005637void SelectionDAGBuilder::visitVAArg(VAArgInst &I) {
Dale Johannesena04b7572009-02-03 23:04:43 +00005638 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5639 getRoot(), getValue(I.getOperand(0)),
5640 DAG.getSrcValue(I.getOperand(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005641 setValue(&I, V);
5642 DAG.setRoot(V.getValue(1));
5643}
5644
Dan Gohman2048b852009-11-23 18:04:58 +00005645void SelectionDAGBuilder::visitVAEnd(CallInst &I) {
Bill Wendlingc1d3c942009-12-23 00:44:51 +00005646 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
5647 MVT::Other, getRoot(),
5648 getValue(I.getOperand(1)),
5649 DAG.getSrcValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005650}
5651
Dan Gohman2048b852009-11-23 18:04:58 +00005652void SelectionDAGBuilder::visitVACopy(CallInst &I) {
Bill Wendlingc1d3c942009-12-23 00:44:51 +00005653 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
5654 MVT::Other, getRoot(),
5655 getValue(I.getOperand(1)),
5656 getValue(I.getOperand(2)),
5657 DAG.getSrcValue(I.getOperand(1)),
5658 DAG.getSrcValue(I.getOperand(2))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005659}
5660
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005661/// TargetLowering::LowerCallTo - This is the default LowerCallTo
Dan Gohman98ca4f22009-08-05 01:29:28 +00005662/// implementation, which just calls LowerCall.
5663/// FIXME: When all targets are
5664/// migrated to using LowerCall, this hook should be integrated into SDISel.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005665std::pair<SDValue, SDValue>
5666TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5667 bool RetSExt, bool RetZExt, bool isVarArg,
Tilmann Scheller6b61cd12009-07-03 06:44:53 +00005668 bool isInreg, unsigned NumFixedArgs,
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00005669 CallingConv::ID CallConv, bool isTailCall,
Dan Gohman98ca4f22009-08-05 01:29:28 +00005670 bool isReturnValueUsed,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005671 SDValue Callee,
Bill Wendling3ea3c242009-12-22 02:10:19 +00005672 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl,
5673 unsigned Order) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005674 // Handle all of the outgoing arguments.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005675 SmallVector<ISD::OutputArg, 32> Outs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005676 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Owen Andersone50ed302009-08-10 22:56:29 +00005677 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005678 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5679 for (unsigned Value = 0, NumValues = ValueVTs.size();
5680 Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00005681 EVT VT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00005682 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005683 SDValue Op = SDValue(Args[i].Node.getNode(),
5684 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005685 ISD::ArgFlagsTy Flags;
5686 unsigned OriginalAlignment =
5687 getTargetData()->getABITypeAlignment(ArgTy);
5688
5689 if (Args[i].isZExt)
5690 Flags.setZExt();
5691 if (Args[i].isSExt)
5692 Flags.setSExt();
5693 if (Args[i].isInReg)
5694 Flags.setInReg();
5695 if (Args[i].isSRet)
5696 Flags.setSRet();
5697 if (Args[i].isByVal) {
5698 Flags.setByVal();
5699 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5700 const Type *ElementTy = Ty->getElementType();
5701 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sands777d2302009-05-09 07:06:46 +00005702 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005703 // For ByVal, alignment should come from FE. BE will guess if this
5704 // info is not there but there are cases it cannot get right.
5705 if (Args[i].Alignment)
5706 FrameAlign = Args[i].Alignment;
5707 Flags.setByValAlign(FrameAlign);
5708 Flags.setByValSize(FrameSize);
5709 }
5710 if (Args[i].isNest)
5711 Flags.setNest();
5712 Flags.setOrigAlign(OriginalAlignment);
5713
Owen Anderson23b9b192009-08-12 00:36:31 +00005714 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
5715 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005716 SmallVector<SDValue, 4> Parts(NumParts);
5717 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5718
5719 if (Args[i].isSExt)
5720 ExtendKind = ISD::SIGN_EXTEND;
5721 else if (Args[i].isZExt)
5722 ExtendKind = ISD::ZERO_EXTEND;
5723
Bill Wendling3ea3c242009-12-22 02:10:19 +00005724 getCopyToParts(DAG, dl, Order, Op, &Parts[0], NumParts,
5725 PartVT, ExtendKind);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005726
Dan Gohman98ca4f22009-08-05 01:29:28 +00005727 for (unsigned j = 0; j != NumParts; ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005728 // if it isn't first piece, alignment must be 1
Dan Gohman98ca4f22009-08-05 01:29:28 +00005729 ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs);
5730 if (NumParts > 1 && j == 0)
5731 MyFlags.Flags.setSplit();
5732 else if (j != 0)
5733 MyFlags.Flags.setOrigAlign(1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005734
Dan Gohman98ca4f22009-08-05 01:29:28 +00005735 Outs.push_back(MyFlags);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005736 }
5737 }
5738 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005739
Dan Gohman98ca4f22009-08-05 01:29:28 +00005740 // Handle the incoming return values from the call.
5741 SmallVector<ISD::InputArg, 32> Ins;
Owen Andersone50ed302009-08-10 22:56:29 +00005742 SmallVector<EVT, 4> RetTys;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005743 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005744 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Owen Andersone50ed302009-08-10 22:56:29 +00005745 EVT VT = RetTys[I];
Owen Anderson23b9b192009-08-12 00:36:31 +00005746 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5747 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005748 for (unsigned i = 0; i != NumRegs; ++i) {
5749 ISD::InputArg MyFlags;
5750 MyFlags.VT = RegisterVT;
5751 MyFlags.Used = isReturnValueUsed;
5752 if (RetSExt)
5753 MyFlags.Flags.setSExt();
5754 if (RetZExt)
5755 MyFlags.Flags.setZExt();
5756 if (isInreg)
5757 MyFlags.Flags.setInReg();
5758 Ins.push_back(MyFlags);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005759 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005760 }
5761
Dan Gohman98ca4f22009-08-05 01:29:28 +00005762 SmallVector<SDValue, 4> InVals;
Evan Cheng022d9e12010-02-02 23:55:14 +00005763 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
Dan Gohman98ca4f22009-08-05 01:29:28 +00005764 Outs, Ins, dl, DAG, InVals);
Dan Gohman5e866062009-08-06 15:37:27 +00005765
5766 // Verify that the target's LowerCall behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +00005767 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00005768 "LowerCall didn't return a valid chain!");
5769 assert((!isTailCall || InVals.empty()) &&
5770 "LowerCall emitted a return value for a tail call!");
5771 assert((isTailCall || InVals.size() == Ins.size()) &&
5772 "LowerCall didn't emit the correct number of values!");
5773 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5774 assert(InVals[i].getNode() &&
5775 "LowerCall emitted a null value!");
5776 assert(Ins[i].VT == InVals[i].getValueType() &&
5777 "LowerCall emitted a value with the wrong type!");
5778 });
Dan Gohman98ca4f22009-08-05 01:29:28 +00005779
5780 // For a tail call, the return value is merely live-out and there aren't
5781 // any nodes in the DAG representing it. Return a special value to
5782 // indicate that a tail call has been emitted and no more Instructions
5783 // should be processed in the current block.
5784 if (isTailCall) {
5785 DAG.setRoot(Chain);
5786 return std::make_pair(SDValue(), SDValue());
5787 }
5788
5789 // Collect the legal value parts into potentially illegal values
5790 // that correspond to the original function's return values.
5791 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5792 if (RetSExt)
5793 AssertOp = ISD::AssertSext;
5794 else if (RetZExt)
5795 AssertOp = ISD::AssertZext;
5796 SmallVector<SDValue, 4> ReturnValues;
5797 unsigned CurReg = 0;
5798 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Owen Andersone50ed302009-08-10 22:56:29 +00005799 EVT VT = RetTys[I];
Owen Anderson23b9b192009-08-12 00:36:31 +00005800 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5801 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005802
Bill Wendling4533cac2010-01-28 21:51:40 +00005803 ReturnValues.push_back(getCopyFromParts(DAG, dl, Order, &InVals[CurReg],
5804 NumRegs, RegisterVT, VT,
5805 AssertOp));
Dan Gohman98ca4f22009-08-05 01:29:28 +00005806 CurReg += NumRegs;
5807 }
5808
5809 // For a function returning void, there is no return value. We can't create
5810 // such a node, so we just return a null return value in that case. In
5811 // that case, nothing will actualy look at the value.
5812 if (ReturnValues.empty())
5813 return std::make_pair(SDValue(), Chain);
5814
5815 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
5816 DAG.getVTList(&RetTys[0], RetTys.size()),
5817 &ReturnValues[0], ReturnValues.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005818 return std::make_pair(Res, Chain);
5819}
5820
Duncan Sands9fbc7e22009-01-21 09:00:29 +00005821void TargetLowering::LowerOperationWrapper(SDNode *N,
5822 SmallVectorImpl<SDValue> &Results,
5823 SelectionDAG &DAG) {
5824 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptabb326bb2009-01-21 04:48:39 +00005825 if (Res.getNode())
5826 Results.push_back(Res);
5827}
5828
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005829SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005830 llvm_unreachable("LowerOperation not implemented for this target!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005831 return SDValue();
5832}
5833
Dan Gohman2048b852009-11-23 18:04:58 +00005834void SelectionDAGBuilder::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005835 SDValue Op = getValue(V);
5836 assert((Op.getOpcode() != ISD::CopyFromReg ||
5837 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5838 "Copy from a reg to the same reg!");
5839 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5840
Owen Anderson23b9b192009-08-12 00:36:31 +00005841 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005842 SDValue Chain = DAG.getEntryNode();
Bill Wendlingec72e322009-12-22 01:11:43 +00005843 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), SDNodeOrder, Chain, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005844 PendingExports.push_back(Chain);
5845}
5846
5847#include "llvm/CodeGen/SelectionDAGISel.h"
5848
Dan Gohman8c2b5252009-10-30 01:27:03 +00005849void SelectionDAGISel::LowerArguments(BasicBlock *LLVMBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005850 // If this is the entry block, emit arguments.
5851 Function &F = *LLVMBB->getParent();
Dan Gohman2048b852009-11-23 18:04:58 +00005852 SelectionDAG &DAG = SDB->DAG;
Dan Gohman98ca4f22009-08-05 01:29:28 +00005853 SDValue OldRoot = DAG.getRoot();
Dan Gohman2048b852009-11-23 18:04:58 +00005854 DebugLoc dl = SDB->getCurDebugLoc();
Dan Gohman98ca4f22009-08-05 01:29:28 +00005855 const TargetData *TD = TLI.getTargetData();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005856 SmallVector<ISD::InputArg, 16> Ins;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005857
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +00005858 // Check whether the function can return without sret-demotion.
5859 SmallVector<EVT, 4> OutVTs;
5860 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005861 getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005862 OutVTs, OutsFlags, TLI);
5863 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
5864
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005865 FLI.CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(), F.isVarArg(),
Bill Wendling3ea3c242009-12-22 02:10:19 +00005866 OutVTs, OutsFlags, DAG);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005867 if (!FLI.CanLowerReturn) {
5868 // Put in an sret pointer parameter before all the other parameters.
5869 SmallVector<EVT, 1> ValueVTs;
5870 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5871
5872 // NOTE: Assuming that a pointer will never break down to more than one VT
5873 // or one register.
5874 ISD::ArgFlagsTy Flags;
5875 Flags.setSRet();
5876 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), ValueVTs[0]);
5877 ISD::InputArg RetArg(Flags, RegisterVT, true);
5878 Ins.push_back(RetArg);
5879 }
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +00005880
Dan Gohman98ca4f22009-08-05 01:29:28 +00005881 // Set up the incoming argument description vector.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005882 unsigned Idx = 1;
5883 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5884 I != E; ++I, ++Idx) {
Owen Andersone50ed302009-08-10 22:56:29 +00005885 SmallVector<EVT, 4> ValueVTs;
Dan Gohman98ca4f22009-08-05 01:29:28 +00005886 ComputeValueVTs(TLI, I->getType(), ValueVTs);
5887 bool isArgValueUsed = !I->use_empty();
5888 for (unsigned Value = 0, NumValues = ValueVTs.size();
5889 Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00005890 EVT VT = ValueVTs[Value];
Owen Anderson1d0be152009-08-13 21:58:54 +00005891 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Dan Gohman98ca4f22009-08-05 01:29:28 +00005892 ISD::ArgFlagsTy Flags;
5893 unsigned OriginalAlignment =
5894 TD->getABITypeAlignment(ArgTy);
5895
5896 if (F.paramHasAttr(Idx, Attribute::ZExt))
5897 Flags.setZExt();
5898 if (F.paramHasAttr(Idx, Attribute::SExt))
5899 Flags.setSExt();
5900 if (F.paramHasAttr(Idx, Attribute::InReg))
5901 Flags.setInReg();
5902 if (F.paramHasAttr(Idx, Attribute::StructRet))
5903 Flags.setSRet();
5904 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
5905 Flags.setByVal();
5906 const PointerType *Ty = cast<PointerType>(I->getType());
5907 const Type *ElementTy = Ty->getElementType();
5908 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
5909 unsigned FrameSize = TD->getTypeAllocSize(ElementTy);
5910 // For ByVal, alignment should be passed from FE. BE will guess if
5911 // this info is not there but there are cases it cannot get right.
5912 if (F.getParamAlignment(Idx))
5913 FrameAlign = F.getParamAlignment(Idx);
5914 Flags.setByValAlign(FrameAlign);
5915 Flags.setByValSize(FrameSize);
5916 }
5917 if (F.paramHasAttr(Idx, Attribute::Nest))
5918 Flags.setNest();
5919 Flags.setOrigAlign(OriginalAlignment);
5920
Owen Anderson23b9b192009-08-12 00:36:31 +00005921 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5922 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005923 for (unsigned i = 0; i != NumRegs; ++i) {
5924 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
5925 if (NumRegs > 1 && i == 0)
5926 MyFlags.Flags.setSplit();
5927 // if it isn't first piece, alignment must be 1
5928 else if (i > 0)
5929 MyFlags.Flags.setOrigAlign(1);
5930 Ins.push_back(MyFlags);
5931 }
5932 }
5933 }
5934
5935 // Call the target to set up the argument values.
5936 SmallVector<SDValue, 8> InVals;
5937 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
5938 F.isVarArg(), Ins,
5939 dl, DAG, InVals);
Dan Gohman5e866062009-08-06 15:37:27 +00005940
5941 // Verify that the target's LowerFormalArguments behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +00005942 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00005943 "LowerFormalArguments didn't return a valid chain!");
5944 assert(InVals.size() == Ins.size() &&
5945 "LowerFormalArguments didn't emit the correct number of values!");
Bill Wendling3ea58b62009-12-22 21:35:02 +00005946 DEBUG({
5947 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5948 assert(InVals[i].getNode() &&
5949 "LowerFormalArguments emitted a null value!");
5950 assert(Ins[i].VT == InVals[i].getValueType() &&
5951 "LowerFormalArguments emitted a value with the wrong type!");
5952 }
5953 });
Bill Wendling3ea3c242009-12-22 02:10:19 +00005954
Dan Gohman5e866062009-08-06 15:37:27 +00005955 // Update the DAG with the new chain value resulting from argument lowering.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005956 DAG.setRoot(NewRoot);
5957
5958 // Set up the argument values.
5959 unsigned i = 0;
5960 Idx = 1;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005961 if (!FLI.CanLowerReturn) {
5962 // Create a virtual register for the sret pointer, and put in a copy
5963 // from the sret argument into it.
5964 SmallVector<EVT, 1> ValueVTs;
5965 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5966 EVT VT = ValueVTs[0];
5967 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5968 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Bill Wendling3ea58b62009-12-22 21:35:02 +00005969 SDValue ArgValue = getCopyFromParts(DAG, dl, 0, &InVals[0], 1,
Bill Wendling3ea3c242009-12-22 02:10:19 +00005970 RegVT, VT, AssertOp);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005971
Dan Gohman2048b852009-11-23 18:04:58 +00005972 MachineFunction& MF = SDB->DAG.getMachineFunction();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005973 MachineRegisterInfo& RegInfo = MF.getRegInfo();
5974 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
5975 FLI.DemoteRegister = SRetReg;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005976 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(),
5977 SRetReg, ArgValue);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005978 DAG.setRoot(NewRoot);
Bill Wendling3ea3c242009-12-22 02:10:19 +00005979
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005980 // i indexes lowered arguments. Bump it past the hidden sret argument.
5981 // Idx indexes LLVM arguments. Don't touch it.
5982 ++i;
5983 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00005984
Dan Gohman98ca4f22009-08-05 01:29:28 +00005985 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5986 ++I, ++Idx) {
5987 SmallVector<SDValue, 4> ArgValues;
Owen Andersone50ed302009-08-10 22:56:29 +00005988 SmallVector<EVT, 4> ValueVTs;
Dan Gohman98ca4f22009-08-05 01:29:28 +00005989 ComputeValueVTs(TLI, I->getType(), ValueVTs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005990 unsigned NumValues = ValueVTs.size();
Dan Gohman98ca4f22009-08-05 01:29:28 +00005991 for (unsigned Value = 0; Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00005992 EVT VT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00005993 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5994 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005995
5996 if (!I->use_empty()) {
5997 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5998 if (F.paramHasAttr(Idx, Attribute::SExt))
5999 AssertOp = ISD::AssertSext;
6000 else if (F.paramHasAttr(Idx, Attribute::ZExt))
6001 AssertOp = ISD::AssertZext;
6002
Bill Wendling3ea58b62009-12-22 21:35:02 +00006003 ArgValues.push_back(getCopyFromParts(DAG, dl, 0, &InVals[i],
Bill Wendling3ea3c242009-12-22 02:10:19 +00006004 NumParts, PartVT, VT,
6005 AssertOp));
Dan Gohman98ca4f22009-08-05 01:29:28 +00006006 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006007
Dan Gohman98ca4f22009-08-05 01:29:28 +00006008 i += NumParts;
6009 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006010
Dan Gohman98ca4f22009-08-05 01:29:28 +00006011 if (!I->use_empty()) {
Bill Wendling3ea3c242009-12-22 02:10:19 +00006012 SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues,
6013 SDB->getCurDebugLoc());
6014 SDB->setValue(I, Res);
6015
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006016 // If this argument is live outside of the entry block, insert a copy from
6017 // whereever we got it to the vreg that other BB's will reference it as.
Dan Gohman2048b852009-11-23 18:04:58 +00006018 SDB->CopyToExportRegsIfNeeded(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006019 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006020 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006021
Dan Gohman98ca4f22009-08-05 01:29:28 +00006022 assert(i == InVals.size() && "Argument register count mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006023
6024 // Finally, if the target has anything special to do, allow it to do so.
6025 // FIXME: this should insert code into the DAG!
Dan Gohman2048b852009-11-23 18:04:58 +00006026 EmitFunctionEntryCode(F, SDB->DAG.getMachineFunction());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006027}
6028
6029/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
6030/// ensure constants are generated when needed. Remember the virtual registers
6031/// that need to be added to the Machine PHI nodes as input. We cannot just
6032/// directly add them, because expansion might result in multiple MBB's for one
6033/// BB. As such, the start of the BB might correspond to a different MBB than
6034/// the end.
6035///
6036void
6037SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
6038 TerminatorInst *TI = LLVMBB->getTerminator();
6039
6040 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6041
6042 // Check successor nodes' PHI nodes that expect a constant to be available
6043 // from this block.
6044 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6045 BasicBlock *SuccBB = TI->getSuccessor(succ);
6046 if (!isa<PHINode>(SuccBB->begin())) continue;
6047 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006048
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006049 // If this terminator has multiple identical successors (common for
6050 // switches), only handle each succ once.
6051 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006052
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006053 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6054 PHINode *PN;
6055
6056 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6057 // nodes and Machine PHI nodes, but the incoming operands have not been
6058 // emitted yet.
6059 for (BasicBlock::iterator I = SuccBB->begin();
6060 (PN = dyn_cast<PHINode>(I)); ++I) {
6061 // Ignore dead phi's.
6062 if (PN->use_empty()) continue;
6063
6064 unsigned Reg;
6065 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6066
6067 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
Dan Gohman2048b852009-11-23 18:04:58 +00006068 unsigned &RegOut = SDB->ConstantsOut[C];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006069 if (RegOut == 0) {
6070 RegOut = FuncInfo->CreateRegForValue(C);
Dan Gohman2048b852009-11-23 18:04:58 +00006071 SDB->CopyValueToVirtualRegister(C, RegOut);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006072 }
6073 Reg = RegOut;
6074 } else {
6075 Reg = FuncInfo->ValueMap[PHIOp];
6076 if (Reg == 0) {
6077 assert(isa<AllocaInst>(PHIOp) &&
6078 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
6079 "Didn't codegen value into a register!??");
6080 Reg = FuncInfo->CreateRegForValue(PHIOp);
Dan Gohman2048b852009-11-23 18:04:58 +00006081 SDB->CopyValueToVirtualRegister(PHIOp, Reg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006082 }
6083 }
6084
6085 // Remember that this register needs to added to the machine PHI node as
6086 // the input for this MBB.
Owen Andersone50ed302009-08-10 22:56:29 +00006087 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006088 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6089 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
Owen Andersone50ed302009-08-10 22:56:29 +00006090 EVT VT = ValueVTs[vti];
Owen Anderson23b9b192009-08-12 00:36:31 +00006091 unsigned NumRegisters = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006092 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Dan Gohman2048b852009-11-23 18:04:58 +00006093 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006094 Reg += NumRegisters;
6095 }
6096 }
6097 }
Dan Gohman2048b852009-11-23 18:04:58 +00006098 SDB->ConstantsOut.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006099}
6100
Dan Gohman3df24e62008-09-03 23:12:08 +00006101/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
6102/// supports legal types, and it emits MachineInstrs directly instead of
6103/// creating SelectionDAG nodes.
6104///
6105bool
6106SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
6107 FastISel *F) {
6108 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006109
Dan Gohman3df24e62008-09-03 23:12:08 +00006110 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
Dan Gohman2048b852009-11-23 18:04:58 +00006111 unsigned OrigNumPHINodesToUpdate = SDB->PHINodesToUpdate.size();
Dan Gohman3df24e62008-09-03 23:12:08 +00006112
6113 // Check successor nodes' PHI nodes that expect a constant to be available
6114 // from this block.
6115 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6116 BasicBlock *SuccBB = TI->getSuccessor(succ);
6117 if (!isa<PHINode>(SuccBB->begin())) continue;
6118 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006119
Dan Gohman3df24e62008-09-03 23:12:08 +00006120 // If this terminator has multiple identical successors (common for
6121 // switches), only handle each succ once.
6122 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006123
Dan Gohman3df24e62008-09-03 23:12:08 +00006124 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6125 PHINode *PN;
6126
6127 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6128 // nodes and Machine PHI nodes, but the incoming operands have not been
6129 // emitted yet.
6130 for (BasicBlock::iterator I = SuccBB->begin();
6131 (PN = dyn_cast<PHINode>(I)); ++I) {
6132 // Ignore dead phi's.
6133 if (PN->use_empty()) continue;
6134
6135 // Only handle legal types. Two interesting things to note here. First,
6136 // by bailing out early, we may leave behind some dead instructions,
6137 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
6138 // own moves. Second, this check is necessary becuase FastISel doesn't
6139 // use CreateRegForValue to create registers, so it always creates
6140 // exactly one register for each non-void instruction.
Owen Andersone50ed302009-08-10 22:56:29 +00006141 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
Owen Anderson825b72b2009-08-11 20:47:22 +00006142 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
6143 // Promote MVT::i1.
6144 if (VT == MVT::i1)
Owen Anderson23b9b192009-08-12 00:36:31 +00006145 VT = TLI.getTypeToTransformTo(*CurDAG->getContext(), VT);
Dan Gohman74321ab2008-09-10 21:01:31 +00006146 else {
Dan Gohman2048b852009-11-23 18:04:58 +00006147 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
Dan Gohman74321ab2008-09-10 21:01:31 +00006148 return false;
6149 }
Dan Gohman3df24e62008-09-03 23:12:08 +00006150 }
6151
6152 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6153
6154 unsigned Reg = F->getRegForValue(PHIOp);
6155 if (Reg == 0) {
Dan Gohman2048b852009-11-23 18:04:58 +00006156 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
Dan Gohman3df24e62008-09-03 23:12:08 +00006157 return false;
6158 }
Dan Gohman2048b852009-11-23 18:04:58 +00006159 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
Dan Gohman3df24e62008-09-03 23:12:08 +00006160 }
6161 }
6162
6163 return true;
6164}