blob: 8b380c68c273f6fde1b70e952d5ddfaf754dc683 [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
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000134 /// append - Add the specified values to this one.
135 void append(const RegsForValue &RHS) {
136 TLI = RHS.TLI;
137 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
138 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
139 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
140 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000141
142
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000143 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000144 /// this value and returns the result as a ValueVTs value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000145 /// Chain/Flag as the input and updates them for the output Chain/Flag.
146 /// If the Flag pointer is NULL, no flag is used.
Bill Wendlingec72e322009-12-22 01:11:43 +0000147 SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl, unsigned Order,
148 SDValue &Chain, SDValue *Flag) const;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000149
150 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000151 /// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000152 /// Chain/Flag as the input and updates them for the output Chain/Flag.
153 /// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000154 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Bill Wendlingec72e322009-12-22 01:11:43 +0000155 unsigned Order, SDValue &Chain, SDValue *Flag) const;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000156
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000157 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
Evan Cheng697cbbf2009-03-20 18:03:34 +0000158 /// operand list. This adds the code marker, matching input operand index
159 /// (if applicable), and includes the number of values added into it.
160 void AddInlineAsmOperands(unsigned Code,
161 bool HasMatching, unsigned MatchingIdx,
Bill Wendling651ad132009-12-22 01:25:10 +0000162 SelectionDAG &DAG, unsigned Order,
163 std::vector<SDValue> &Ops) const;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000164 };
165}
166
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000167/// getCopyFromParts - Create a value that contains the specified legal parts
168/// combined into the value they represent. If the parts combine to a type
169/// larger then ValueVT then AssertOp can be used to specify whether the extra
170/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
171/// (ISD::AssertSext).
Bill Wendling3ea3c242009-12-22 02:10:19 +0000172static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl, unsigned Order,
Dale Johannesen66978ee2009-01-31 02:22:37 +0000173 const SDValue *Parts,
Owen Andersone50ed302009-08-10 22:56:29 +0000174 unsigned NumParts, EVT PartVT, EVT ValueVT,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000175 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000176 assert(NumParts > 0 && "No parts to assemble!");
Dan Gohmane9530ec2009-01-15 16:58:17 +0000177 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000178 SDValue Val = Parts[0];
179
180 if (NumParts > 1) {
181 // Assemble the value from multiple parts.
Eli Friedman2ac8b322009-05-20 06:02:09 +0000182 if (!ValueVT.isVector() && ValueVT.isInteger()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000183 unsigned PartBits = PartVT.getSizeInBits();
184 unsigned ValueBits = ValueVT.getSizeInBits();
185
186 // Assemble the power of 2 part.
187 unsigned RoundParts = NumParts & (NumParts - 1) ?
188 1 << Log2_32(NumParts) : NumParts;
189 unsigned RoundBits = PartBits * RoundParts;
Owen Andersone50ed302009-08-10 22:56:29 +0000190 EVT RoundVT = RoundBits == ValueBits ?
Owen Anderson23b9b192009-08-12 00:36:31 +0000191 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000192 SDValue Lo, Hi;
193
Owen Anderson23b9b192009-08-12 00:36:31 +0000194 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000195
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000196 if (RoundParts > 2) {
Bill Wendling3ea3c242009-12-22 02:10:19 +0000197 Lo = getCopyFromParts(DAG, dl, Order, Parts, RoundParts / 2,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000198 PartVT, HalfVT);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000199 Hi = getCopyFromParts(DAG, dl, Order, Parts + RoundParts / 2,
200 RoundParts / 2, PartVT, HalfVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000201 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000202 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
203 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000204 }
Bill Wendling3ea3c242009-12-22 02:10:19 +0000205
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000206 if (TLI.isBigEndian())
207 std::swap(Lo, Hi);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000208
Dale Johannesen66978ee2009-01-31 02:22:37 +0000209 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000210
211 if (RoundParts < NumParts) {
212 // Assemble the trailing non-power-of-2 part.
213 unsigned OddParts = NumParts - RoundParts;
Owen Anderson23b9b192009-08-12 00:36:31 +0000214 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000215 Hi = getCopyFromParts(DAG, dl, Order,
216 Parts + RoundParts, OddParts, PartVT, OddVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000217
218 // Combine the round and odd parts.
219 Lo = Val;
220 if (TLI.isBigEndian())
221 std::swap(Lo, Hi);
Owen Anderson23b9b192009-08-12 00:36:31 +0000222 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000223 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
224 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000225 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands92abc622009-01-31 15:50:11 +0000226 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000227 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
228 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000229 }
Eli Friedman2ac8b322009-05-20 06:02:09 +0000230 } else if (ValueVT.isVector()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000231 // Handle a multi-element vector.
Owen Andersone50ed302009-08-10 22:56:29 +0000232 EVT IntermediateVT, RegisterVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000233 unsigned NumIntermediates;
234 unsigned NumRegs =
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000235 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
Owen Anderson23b9b192009-08-12 00:36:31 +0000236 NumIntermediates, RegisterVT);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000237 assert(NumRegs == NumParts
238 && "Part count doesn't match vector breakdown!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000239 NumParts = NumRegs; // Silence a compiler warning.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000240 assert(RegisterVT == PartVT
241 && "Part type doesn't match vector breakdown!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000242 assert(RegisterVT == Parts[0].getValueType() &&
243 "Part type doesn't match part!");
244
245 // Assemble the parts into intermediate operands.
246 SmallVector<SDValue, 8> Ops(NumIntermediates);
247 if (NumIntermediates == NumParts) {
248 // If the register was not expanded, truncate or copy the value,
249 // as appropriate.
250 for (unsigned i = 0; i != NumParts; ++i)
Bill Wendling3ea3c242009-12-22 02:10:19 +0000251 Ops[i] = getCopyFromParts(DAG, dl, Order, &Parts[i], 1,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000252 PartVT, IntermediateVT);
253 } else if (NumParts > 0) {
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000254 // If the intermediate type was expanded, build the intermediate
255 // operands from the parts.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000256 assert(NumParts % NumIntermediates == 0 &&
257 "Must expand into a divisible number of parts!");
258 unsigned Factor = NumParts / NumIntermediates;
259 for (unsigned i = 0; i != NumIntermediates; ++i)
Bill Wendling3ea3c242009-12-22 02:10:19 +0000260 Ops[i] = getCopyFromParts(DAG, dl, Order, &Parts[i * Factor], Factor,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000261 PartVT, IntermediateVT);
262 }
263
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000264 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
265 // intermediate operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000266 Val = DAG.getNode(IntermediateVT.isVector() ?
Dale Johannesen66978ee2009-01-31 02:22:37 +0000267 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000268 ValueVT, &Ops[0], NumIntermediates);
Eli Friedman2ac8b322009-05-20 06:02:09 +0000269 } else if (PartVT.isFloatingPoint()) {
270 // FP split into multiple FP parts (for ppcf128)
Owen Anderson825b72b2009-08-11 20:47:22 +0000271 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
Eli Friedman2ac8b322009-05-20 06:02:09 +0000272 "Unexpected split");
273 SDValue Lo, Hi;
Owen Anderson825b72b2009-08-11 20:47:22 +0000274 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[0]);
275 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[1]);
Eli Friedman2ac8b322009-05-20 06:02:09 +0000276 if (TLI.isBigEndian())
277 std::swap(Lo, Hi);
278 Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi);
279 } else {
280 // FP split into integer parts (soft fp)
281 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
282 !PartVT.isVector() && "Unexpected split");
Owen Anderson23b9b192009-08-12 00:36:31 +0000283 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
Bill Wendling3ea3c242009-12-22 02:10:19 +0000284 Val = getCopyFromParts(DAG, dl, Order, Parts, NumParts, PartVT, IntVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000285 }
286 }
287
288 // There is now one part, held in Val. Correct it to match ValueVT.
289 PartVT = Val.getValueType();
290
291 if (PartVT == ValueVT)
292 return Val;
293
294 if (PartVT.isVector()) {
295 assert(ValueVT.isVector() && "Unknown vector conversion!");
Bill Wendling4533cac2010-01-28 21:51:40 +0000296 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000297 }
298
299 if (ValueVT.isVector()) {
300 assert(ValueVT.getVectorElementType() == PartVT &&
301 ValueVT.getVectorNumElements() == 1 &&
302 "Only trivial scalar-to-vector conversions should get here!");
Bill Wendling4533cac2010-01-28 21:51:40 +0000303 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000304 }
305
306 if (PartVT.isInteger() &&
307 ValueVT.isInteger()) {
308 if (ValueVT.bitsLT(PartVT)) {
309 // For a truncate, see if we have any information to
310 // indicate whether the truncated bits will always be
311 // zero or sign-extension.
312 if (AssertOp != ISD::DELETED_NODE)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000313 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000314 DAG.getValueType(ValueVT));
Bill Wendling4533cac2010-01-28 21:51:40 +0000315 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000316 } else {
Bill Wendling4533cac2010-01-28 21:51:40 +0000317 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000318 }
319 }
320
321 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Bill Wendling3ea3c242009-12-22 02:10:19 +0000322 if (ValueVT.bitsLT(Val.getValueType())) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000323 // FP_ROUND's are always exact here.
Bill Wendling4533cac2010-01-28 21:51:40 +0000324 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
325 DAG.getIntPtrConstant(1));
Bill Wendling3ea3c242009-12-22 02:10:19 +0000326 }
327
Bill Wendling4533cac2010-01-28 21:51:40 +0000328 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000329 }
330
Bill Wendling4533cac2010-01-28 21:51:40 +0000331 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
332 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000333
Torok Edwinc23197a2009-07-14 16:55:14 +0000334 llvm_unreachable("Unknown mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000335 return SDValue();
336}
337
338/// getCopyToParts - Create a series of nodes that contain the specified value
339/// split into legal parts. If the parts contain more bits than Val, then, for
340/// integers, ExtendKind can be used to specify how to generate the extra bits.
Bill Wendling3ea3c242009-12-22 02:10:19 +0000341static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, unsigned Order,
342 SDValue Val, SDValue *Parts, unsigned NumParts,
343 EVT PartVT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000344 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohmane9530ec2009-01-15 16:58:17 +0000345 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Owen Andersone50ed302009-08-10 22:56:29 +0000346 EVT PtrVT = TLI.getPointerTy();
347 EVT ValueVT = Val.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000348 unsigned PartBits = PartVT.getSizeInBits();
Dale Johannesen8a36f502009-02-25 22:39:13 +0000349 unsigned OrigNumParts = NumParts;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000350 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
351
352 if (!NumParts)
353 return;
354
355 if (!ValueVT.isVector()) {
356 if (PartVT == ValueVT) {
357 assert(NumParts == 1 && "No-op copy with multiple parts!");
358 Parts[0] = Val;
359 return;
360 }
361
362 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
363 // If the parts cover more bits than the value has, promote the value.
364 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
365 assert(NumParts == 1 && "Do not know what to promote to!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000366 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000367 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
Owen Anderson23b9b192009-08-12 00:36:31 +0000368 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000369 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000370 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000371 llvm_unreachable("Unknown mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000372 }
373 } else if (PartBits == ValueVT.getSizeInBits()) {
374 // Different types of the same size.
375 assert(NumParts == 1 && PartVT != ValueVT);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000376 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000377 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
378 // If the parts cover less bits than value has, truncate the value.
379 if (PartVT.isInteger() && ValueVT.isInteger()) {
Owen Anderson23b9b192009-08-12 00:36:31 +0000380 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000381 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000382 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000383 llvm_unreachable("Unknown mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000384 }
385 }
386
387 // The value may have changed - recompute ValueVT.
388 ValueVT = Val.getValueType();
389 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
390 "Failed to tile the value with PartVT!");
391
392 if (NumParts == 1) {
393 assert(PartVT == ValueVT && "Type conversion failed!");
394 Parts[0] = Val;
395 return;
396 }
397
398 // Expand the value into multiple parts.
399 if (NumParts & (NumParts - 1)) {
400 // The number of parts is not a power of 2. Split off and copy the tail.
401 assert(PartVT.isInteger() && ValueVT.isInteger() &&
402 "Do not know what to expand to!");
403 unsigned RoundParts = 1 << Log2_32(NumParts);
404 unsigned RoundBits = RoundParts * PartBits;
405 unsigned OddParts = NumParts - RoundParts;
Dale Johannesen66978ee2009-01-31 02:22:37 +0000406 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000407 DAG.getConstant(RoundBits,
Duncan Sands92abc622009-01-31 15:50:11 +0000408 TLI.getPointerTy()));
Bill Wendling3ea3c242009-12-22 02:10:19 +0000409 getCopyToParts(DAG, dl, Order, OddVal, Parts + RoundParts,
410 OddParts, PartVT);
411
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000412 if (TLI.isBigEndian())
413 // The odd parts were reversed by getCopyToParts - unreverse them.
414 std::reverse(Parts + RoundParts, Parts + NumParts);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000415
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000416 NumParts = RoundParts;
Owen Anderson23b9b192009-08-12 00:36:31 +0000417 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000418 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000419 }
420
421 // The number of parts is a power of 2. Repeatedly bisect the value using
422 // EXTRACT_ELEMENT.
Scott Michelfdc40a02009-02-17 22:15:04 +0000423 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
Chris Lattnerf031e8a2010-01-01 03:32:16 +0000424 EVT::getIntegerVT(*DAG.getContext(),
425 ValueVT.getSizeInBits()),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000426 Val);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000427
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000428 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
429 for (unsigned i = 0; i < NumParts; i += StepSize) {
430 unsigned ThisBits = StepSize * PartBits / 2;
Owen Anderson23b9b192009-08-12 00:36:31 +0000431 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000432 SDValue &Part0 = Parts[i];
433 SDValue &Part1 = Parts[i+StepSize/2];
434
Scott Michelfdc40a02009-02-17 22:15:04 +0000435 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000436 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000437 DAG.getConstant(1, PtrVT));
Scott Michelfdc40a02009-02-17 22:15:04 +0000438 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000439 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000440 DAG.getConstant(0, PtrVT));
441
442 if (ThisBits == PartBits && ThisVT != PartVT) {
Scott Michelfdc40a02009-02-17 22:15:04 +0000443 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000444 PartVT, Part0);
Scott Michelfdc40a02009-02-17 22:15:04 +0000445 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000446 PartVT, Part1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000447 }
448 }
449 }
450
451 if (TLI.isBigEndian())
Dale Johannesen8a36f502009-02-25 22:39:13 +0000452 std::reverse(Parts, Parts + OrigNumParts);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000453
454 return;
455 }
456
457 // Vector ValueVT.
458 if (NumParts == 1) {
459 if (PartVT != ValueVT) {
Bob Wilson5afffae2009-12-18 01:03:29 +0000460 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000461 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000462 } else {
463 assert(ValueVT.getVectorElementType() == PartVT &&
464 ValueVT.getVectorNumElements() == 1 &&
465 "Only trivial vector-to-scalar conversions should get here!");
Scott Michelfdc40a02009-02-17 22:15:04 +0000466 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000467 PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000468 DAG.getConstant(0, PtrVT));
469 }
470 }
471
472 Parts[0] = Val;
473 return;
474 }
475
476 // Handle a multi-element vector.
Owen Andersone50ed302009-08-10 22:56:29 +0000477 EVT IntermediateVT, RegisterVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000478 unsigned NumIntermediates;
Owen Anderson23b9b192009-08-12 00:36:31 +0000479 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
480 IntermediateVT, NumIntermediates, RegisterVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000481 unsigned NumElements = ValueVT.getVectorNumElements();
482
483 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
484 NumParts = NumRegs; // Silence a compiler warning.
485 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
486
487 // Split the vector into intermediate operands.
488 SmallVector<SDValue, 8> Ops(NumIntermediates);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000489 for (unsigned i = 0; i != NumIntermediates; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000490 if (IntermediateVT.isVector())
Scott Michelfdc40a02009-02-17 22:15:04 +0000491 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000492 IntermediateVT, Val,
493 DAG.getConstant(i * (NumElements / NumIntermediates),
494 PtrVT));
495 else
Scott Michelfdc40a02009-02-17 22:15:04 +0000496 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000497 IntermediateVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000498 DAG.getConstant(i, PtrVT));
Bill Wendling3ea3c242009-12-22 02:10:19 +0000499 }
500
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000501 // Split the intermediate operands into legal parts.
502 if (NumParts == NumIntermediates) {
503 // If the register was not expanded, promote or copy the value,
504 // as appropriate.
505 for (unsigned i = 0; i != NumParts; ++i)
Bill Wendling3ea3c242009-12-22 02:10:19 +0000506 getCopyToParts(DAG, dl, Order, Ops[i], &Parts[i], 1, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000507 } else if (NumParts > 0) {
508 // If the intermediate type was expanded, split each the value into
509 // legal parts.
510 assert(NumParts % NumIntermediates == 0 &&
511 "Must expand into a divisible number of parts!");
512 unsigned Factor = NumParts / NumIntermediates;
513 for (unsigned i = 0; i != NumIntermediates; ++i)
Bill Wendling3ea3c242009-12-22 02:10:19 +0000514 getCopyToParts(DAG, dl, Order, Ops[i], &Parts[i*Factor], Factor, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000515 }
516}
517
518
Dan Gohman2048b852009-11-23 18:04:58 +0000519void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000520 AA = &aa;
521 GFI = gfi;
522 TD = DAG.getTarget().getTargetData();
523}
524
525/// clear - Clear out the curret SelectionDAG and the associated
Dan Gohman2048b852009-11-23 18:04:58 +0000526/// state and prepare this SelectionDAGBuilder object to be used
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000527/// for a new block. This doesn't clear out information about
528/// additional blocks that are needed to complete switch lowering
529/// or PHI node updating; that information is cleared out as it is
530/// consumed.
Dan Gohman2048b852009-11-23 18:04:58 +0000531void SelectionDAGBuilder::clear() {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000532 NodeMap.clear();
533 PendingLoads.clear();
534 PendingExports.clear();
Evan Chengfb2e7522009-09-18 21:02:19 +0000535 EdgeMapping.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000536 DAG.clear();
Bill Wendling8fcf1702009-02-06 21:36:23 +0000537 CurDebugLoc = DebugLoc::getUnknownLoc();
Dan Gohman98ca4f22009-08-05 01:29:28 +0000538 HasTailCall = false;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000539}
540
541/// getRoot - Return the current virtual root of the Selection DAG,
542/// flushing any PendingLoad items. This must be done before emitting
543/// a store or any other node that may need to be ordered after any
544/// prior load instructions.
545///
Dan Gohman2048b852009-11-23 18:04:58 +0000546SDValue SelectionDAGBuilder::getRoot() {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000547 if (PendingLoads.empty())
548 return DAG.getRoot();
549
550 if (PendingLoads.size() == 1) {
551 SDValue Root = PendingLoads[0];
552 DAG.setRoot(Root);
553 PendingLoads.clear();
554 return Root;
555 }
556
557 // Otherwise, we have to make a token factor node.
Owen Anderson825b72b2009-08-11 20:47:22 +0000558 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000559 &PendingLoads[0], PendingLoads.size());
560 PendingLoads.clear();
561 DAG.setRoot(Root);
562 return Root;
563}
564
565/// getControlRoot - Similar to getRoot, but instead of flushing all the
566/// PendingLoad items, flush all the PendingExports items. It is necessary
567/// to do this before emitting a terminator instruction.
568///
Dan Gohman2048b852009-11-23 18:04:58 +0000569SDValue SelectionDAGBuilder::getControlRoot() {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000570 SDValue Root = DAG.getRoot();
571
572 if (PendingExports.empty())
573 return Root;
574
575 // Turn all of the CopyToReg chains into one factored node.
576 if (Root.getOpcode() != ISD::EntryToken) {
577 unsigned i = 0, e = PendingExports.size();
578 for (; i != e; ++i) {
579 assert(PendingExports[i].getNode()->getNumOperands() > 1);
580 if (PendingExports[i].getNode()->getOperand(0) == Root)
581 break; // Don't add the root if we already indirectly depend on it.
582 }
583
584 if (i == e)
585 PendingExports.push_back(Root);
586 }
587
Owen Anderson825b72b2009-08-11 20:47:22 +0000588 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000589 &PendingExports[0],
590 PendingExports.size());
591 PendingExports.clear();
592 DAG.setRoot(Root);
593 return Root;
594}
595
Bill Wendling4533cac2010-01-28 21:51:40 +0000596void SelectionDAGBuilder::AssignOrderingToNode(const SDNode *Node) {
597 if (DAG.GetOrdering(Node) != 0) return; // Already has ordering.
598 DAG.AssignOrdering(Node, SDNodeOrder);
599
600 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)
601 AssignOrderingToNode(Node->getOperand(I).getNode());
602}
603
Dan Gohman2048b852009-11-23 18:04:58 +0000604void SelectionDAGBuilder::visit(Instruction &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000605 visit(I.getOpcode(), I);
606}
607
Dan Gohman2048b852009-11-23 18:04:58 +0000608void SelectionDAGBuilder::visit(unsigned Opcode, User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000609 // Note: this doesn't use InstVisitor, because it has to work with
610 // ConstantExpr's in addition to instructions.
611 switch (Opcode) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000612 default: llvm_unreachable("Unknown instruction type encountered!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000613 // Build the switch statement using the Instruction.def file.
614#define HANDLE_INST(NUM, OPCODE, CLASS) \
Bill Wendling4533cac2010-01-28 21:51:40 +0000615 case Instruction::OPCODE: visit##OPCODE((CLASS&)I); break;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000616#include "llvm/Instruction.def"
617 }
Bill Wendling4533cac2010-01-28 21:51:40 +0000618
619 // Assign the ordering to the freshly created DAG nodes.
620 if (NodeMap.count(&I)) {
621 ++SDNodeOrder;
622 AssignOrderingToNode(getValue(&I).getNode());
623 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000624}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000625
Dan Gohman2048b852009-11-23 18:04:58 +0000626SDValue SelectionDAGBuilder::getValue(const Value *V) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000627 SDValue &N = NodeMap[V];
628 if (N.getNode()) return N;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000629
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000630 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
Owen Andersone50ed302009-08-10 22:56:29 +0000631 EVT VT = TLI.getValueType(V->getType(), true);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000632
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000633 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000634 return N = DAG.getConstant(*CI, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000635
636 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
637 return N = DAG.getGlobalAddress(GV, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000638
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000639 if (isa<ConstantPointerNull>(C))
640 return N = DAG.getConstant(0, TLI.getPointerTy());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000641
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000642 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000643 return N = DAG.getConstantFP(*CFP, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000644
Nate Begeman9008ca62009-04-27 18:41:29 +0000645 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
Dale Johannesene8d72302009-02-06 23:05:02 +0000646 return N = DAG.getUNDEF(VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000647
648 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
649 visit(CE->getOpcode(), *CE);
650 SDValue N1 = NodeMap[V];
651 assert(N1.getNode() && "visit didn't populate the ValueMap!");
652 return N1;
653 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000654
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000655 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
656 SmallVector<SDValue, 4> Constants;
657 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
658 OI != OE; ++OI) {
659 SDNode *Val = getValue(*OI).getNode();
Dan Gohmaned48caf2009-09-08 01:44:02 +0000660 // If the operand is an empty aggregate, there are no values.
661 if (!Val) continue;
662 // Add each leaf value from the operand to the Constants list
663 // to form a flattened list of all the values.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000664 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
665 Constants.push_back(SDValue(Val, i));
666 }
Bill Wendling87710f02009-12-21 23:47:40 +0000667
Bill Wendling4533cac2010-01-28 21:51:40 +0000668 return DAG.getMergeValues(&Constants[0], Constants.size(),
669 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000670 }
671
672 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
673 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
674 "Unknown struct or array constant!");
675
Owen Andersone50ed302009-08-10 22:56:29 +0000676 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000677 ComputeValueVTs(TLI, C->getType(), ValueVTs);
678 unsigned NumElts = ValueVTs.size();
679 if (NumElts == 0)
680 return SDValue(); // empty struct
681 SmallVector<SDValue, 4> Constants(NumElts);
682 for (unsigned i = 0; i != NumElts; ++i) {
Owen Andersone50ed302009-08-10 22:56:29 +0000683 EVT EltVT = ValueVTs[i];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000684 if (isa<UndefValue>(C))
Dale Johannesene8d72302009-02-06 23:05:02 +0000685 Constants[i] = DAG.getUNDEF(EltVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000686 else if (EltVT.isFloatingPoint())
687 Constants[i] = DAG.getConstantFP(0, EltVT);
688 else
689 Constants[i] = DAG.getConstant(0, EltVT);
690 }
Bill Wendling87710f02009-12-21 23:47:40 +0000691
Bill Wendling4533cac2010-01-28 21:51:40 +0000692 return DAG.getMergeValues(&Constants[0], NumElts,
693 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000694 }
695
Dan Gohman8c2b5252009-10-30 01:27:03 +0000696 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
Dan Gohman29cbade2009-11-20 23:18:13 +0000697 return DAG.getBlockAddress(BA, VT);
Dan Gohman8c2b5252009-10-30 01:27:03 +0000698
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000699 const VectorType *VecTy = cast<VectorType>(V->getType());
700 unsigned NumElements = VecTy->getNumElements();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000701
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000702 // Now that we know the number and type of the elements, get that number of
703 // elements into the Ops array based on what kind of constant it is.
704 SmallVector<SDValue, 16> Ops;
705 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
706 for (unsigned i = 0; i != NumElements; ++i)
707 Ops.push_back(getValue(CP->getOperand(i)));
708 } else {
Nate Begeman9008ca62009-04-27 18:41:29 +0000709 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
Owen Andersone50ed302009-08-10 22:56:29 +0000710 EVT EltVT = TLI.getValueType(VecTy->getElementType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000711
712 SDValue Op;
Nate Begeman9008ca62009-04-27 18:41:29 +0000713 if (EltVT.isFloatingPoint())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000714 Op = DAG.getConstantFP(0, EltVT);
715 else
716 Op = DAG.getConstant(0, EltVT);
717 Ops.assign(NumElements, Op);
718 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000719
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000720 // Create a BUILD_VECTOR node.
Bill Wendling4533cac2010-01-28 21:51:40 +0000721 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
722 VT, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000723 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000724
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000725 // If this is a static alloca, generate it as the frameindex instead of
726 // computation.
727 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
728 DenseMap<const AllocaInst*, int>::iterator SI =
729 FuncInfo.StaticAllocaMap.find(AI);
730 if (SI != FuncInfo.StaticAllocaMap.end())
731 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
732 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000733
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000734 unsigned InReg = FuncInfo.ValueMap[V];
735 assert(InReg && "Value not in map!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000736
Owen Anderson23b9b192009-08-12 00:36:31 +0000737 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000738 SDValue Chain = DAG.getEntryNode();
Bill Wendlingec72e322009-12-22 01:11:43 +0000739 return RFV.getCopyFromRegs(DAG, getCurDebugLoc(),
740 SDNodeOrder, Chain, NULL);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000741}
742
Kenneth Uildriks93ae4072010-01-16 23:37:33 +0000743/// Get the EVTs and ArgFlags collections that represent the legalized return
744/// type of the given function. This does not require a DAG or a return value,
745/// and is suitable for use before any DAGs for the function are constructed.
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000746static void getReturnInfo(const Type* ReturnType,
747 Attributes attr, SmallVectorImpl<EVT> &OutVTs,
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000748 SmallVectorImpl<ISD::ArgFlagsTy> &OutFlags,
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000749 TargetLowering &TLI,
750 SmallVectorImpl<uint64_t> *Offsets = 0) {
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000751 SmallVector<EVT, 4> ValueVTs;
Kenneth Uildriks93ae4072010-01-16 23:37:33 +0000752 ComputeValueVTs(TLI, ReturnType, ValueVTs);
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000753 unsigned NumValues = ValueVTs.size();
Kenneth Uildriks93ae4072010-01-16 23:37:33 +0000754 if (NumValues == 0) return;
755 unsigned Offset = 0;
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000756
757 for (unsigned j = 0, f = NumValues; j != f; ++j) {
758 EVT VT = ValueVTs[j];
759 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000760
761 if (attr & Attribute::SExt)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000762 ExtendKind = ISD::SIGN_EXTEND;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000763 else if (attr & Attribute::ZExt)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000764 ExtendKind = ISD::ZERO_EXTEND;
765
766 // FIXME: C calling convention requires the return type to be promoted to
767 // at least 32-bit. But this is not necessary for non-C calling
768 // conventions. The frontend should mark functions whose return values
769 // require promoting with signext or zeroext attributes.
770 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000771 EVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000772 if (VT.bitsLT(MinVT))
773 VT = MinVT;
774 }
775
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000776 unsigned NumParts = TLI.getNumRegisters(ReturnType->getContext(), VT);
777 EVT PartVT = TLI.getRegisterType(ReturnType->getContext(), VT);
Kenneth Uildriks93ae4072010-01-16 23:37:33 +0000778 unsigned PartSize = TLI.getTargetData()->getTypeAllocSize(
779 PartVT.getTypeForEVT(ReturnType->getContext()));
780
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000781 // 'inreg' on function refers to return value
782 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000783 if (attr & Attribute::InReg)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000784 Flags.setInReg();
785
786 // Propagate extension type if any
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000787 if (attr & Attribute::SExt)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000788 Flags.setSExt();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000789 else if (attr & Attribute::ZExt)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000790 Flags.setZExt();
791
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000792 for (unsigned i = 0; i < NumParts; ++i) {
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000793 OutVTs.push_back(PartVT);
794 OutFlags.push_back(Flags);
Kenneth Uildriks93ae4072010-01-16 23:37:33 +0000795 if (Offsets)
796 {
797 Offsets->push_back(Offset);
798 Offset += PartSize;
799 }
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000800 }
801 }
802}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000803
Dan Gohman2048b852009-11-23 18:04:58 +0000804void SelectionDAGBuilder::visitRet(ReturnInst &I) {
Dan Gohman98ca4f22009-08-05 01:29:28 +0000805 SDValue Chain = getControlRoot();
806 SmallVector<ISD::OutputArg, 8> Outs;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000807 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000808
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000809 if (!FLI.CanLowerReturn) {
810 unsigned DemoteReg = FLI.DemoteRegister;
811 const Function *F = I.getParent()->getParent();
812
813 // Emit a store of the return value through the virtual register.
814 // Leave Outs empty so that LowerReturn won't try to load return
815 // registers the usual way.
816 SmallVector<EVT, 1> PtrValueVTs;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000817 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000818 PtrValueVTs);
819
820 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
821 SDValue RetOp = getValue(I.getOperand(0));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000822
Owen Andersone50ed302009-08-10 22:56:29 +0000823 SmallVector<EVT, 4> ValueVTs;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000824 SmallVector<uint64_t, 4> Offsets;
825 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
Dan Gohman7ea1ca62008-10-21 20:00:42 +0000826 unsigned NumValues = ValueVTs.size();
Dan Gohman7ea1ca62008-10-21 20:00:42 +0000827
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000828 SmallVector<SDValue, 4> Chains(NumValues);
829 EVT PtrVT = PtrValueVTs[0];
Bill Wendling87710f02009-12-21 23:47:40 +0000830 for (unsigned i = 0; i != NumValues; ++i) {
831 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, RetPtr,
832 DAG.getConstant(Offsets[i], PtrVT));
833 Chains[i] =
834 DAG.getStore(Chain, getCurDebugLoc(),
835 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
836 Add, NULL, Offsets[i], false, 0);
Bill Wendling87710f02009-12-21 23:47:40 +0000837 }
838
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000839 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
840 MVT::Other, &Chains[0], NumValues);
Bill Wendling87710f02009-12-21 23:47:40 +0000841 } else {
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000842 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
843 SmallVector<EVT, 4> ValueVTs;
844 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
845 unsigned NumValues = ValueVTs.size();
846 if (NumValues == 0) continue;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000847
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000848 SDValue RetOp = getValue(I.getOperand(i));
849 for (unsigned j = 0, f = NumValues; j != f; ++j) {
850 EVT VT = ValueVTs[j];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000851
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000852 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000853
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000854 const Function *F = I.getParent()->getParent();
855 if (F->paramHasAttr(0, Attribute::SExt))
856 ExtendKind = ISD::SIGN_EXTEND;
857 else if (F->paramHasAttr(0, Attribute::ZExt))
858 ExtendKind = ISD::ZERO_EXTEND;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000859
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000860 // FIXME: C calling convention requires the return type to be promoted
861 // to at least 32-bit. But this is not necessary for non-C calling
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000862 // conventions. The frontend should mark functions whose return values
863 // require promoting with signext or zeroext attributes.
864 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
865 EVT MinVT = TLI.getRegisterType(*DAG.getContext(), MVT::i32);
866 if (VT.bitsLT(MinVT))
867 VT = MinVT;
868 }
869
870 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
871 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
872 SmallVector<SDValue, 4> Parts(NumParts);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000873 getCopyToParts(DAG, getCurDebugLoc(), SDNodeOrder,
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000874 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
875 &Parts[0], NumParts, PartVT, ExtendKind);
876
877 // 'inreg' on function refers to return value
878 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
879 if (F->paramHasAttr(0, Attribute::InReg))
880 Flags.setInReg();
881
882 // Propagate extension type if any
883 if (F->paramHasAttr(0, Attribute::SExt))
884 Flags.setSExt();
885 else if (F->paramHasAttr(0, Attribute::ZExt))
886 Flags.setZExt();
887
888 for (unsigned i = 0; i < NumParts; ++i)
889 Outs.push_back(ISD::OutputArg(Flags, Parts[i], /*isfixed=*/true));
Evan Cheng3927f432009-03-25 20:20:11 +0000890 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000891 }
892 }
Dan Gohman98ca4f22009-08-05 01:29:28 +0000893
894 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +0000895 CallingConv::ID CallConv =
896 DAG.getMachineFunction().getFunction()->getCallingConv();
Dan Gohman98ca4f22009-08-05 01:29:28 +0000897 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
898 Outs, getCurDebugLoc(), DAG);
Dan Gohman5e866062009-08-06 15:37:27 +0000899
900 // Verify that the target's LowerReturn behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +0000901 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +0000902 "LowerReturn didn't return a valid chain!");
903
904 // Update the DAG with the new chain value resulting from return lowering.
Dan Gohman98ca4f22009-08-05 01:29:28 +0000905 DAG.setRoot(Chain);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000906}
907
Dan Gohmanad62f532009-04-23 23:13:24 +0000908/// CopyToExportRegsIfNeeded - If the given value has virtual registers
909/// created for it, emit nodes to copy the value into the virtual
910/// registers.
Dan Gohman2048b852009-11-23 18:04:58 +0000911void SelectionDAGBuilder::CopyToExportRegsIfNeeded(Value *V) {
Dan Gohmanad62f532009-04-23 23:13:24 +0000912 if (!V->use_empty()) {
913 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
914 if (VMI != FuncInfo.ValueMap.end())
915 CopyValueToVirtualRegister(V, VMI->second);
916 }
917}
918
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000919/// ExportFromCurrentBlock - If this condition isn't known to be exported from
920/// the current basic block, add it to ValueMap now so that we'll get a
921/// CopyTo/FromReg.
Dan Gohman2048b852009-11-23 18:04:58 +0000922void SelectionDAGBuilder::ExportFromCurrentBlock(Value *V) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000923 // No need to export constants.
924 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000925
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000926 // Already exported?
927 if (FuncInfo.isExportedInst(V)) return;
928
929 unsigned Reg = FuncInfo.InitializeRegForValue(V);
930 CopyValueToVirtualRegister(V, Reg);
931}
932
Dan Gohman2048b852009-11-23 18:04:58 +0000933bool SelectionDAGBuilder::isExportableFromCurrentBlock(Value *V,
934 const BasicBlock *FromBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000935 // The operands of the setcc have to be in this block. We don't know
936 // how to export them from some other block.
937 if (Instruction *VI = dyn_cast<Instruction>(V)) {
938 // Can export from current BB.
939 if (VI->getParent() == FromBB)
940 return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000941
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000942 // Is already exported, noop.
943 return FuncInfo.isExportedInst(V);
944 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000945
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000946 // If this is an argument, we can export it if the BB is the entry block or
947 // if it is already exported.
948 if (isa<Argument>(V)) {
949 if (FromBB == &FromBB->getParent()->getEntryBlock())
950 return true;
951
952 // Otherwise, can only export this if it is already exported.
953 return FuncInfo.isExportedInst(V);
954 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000955
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000956 // Otherwise, constants can always be exported.
957 return true;
958}
959
960static bool InBlock(const Value *V, const BasicBlock *BB) {
961 if (const Instruction *I = dyn_cast<Instruction>(V))
962 return I->getParent() == BB;
963 return true;
964}
965
Dan Gohman8c1a6ca2008-10-17 18:18:45 +0000966/// getFCmpCondCode - Return the ISD condition code corresponding to
967/// the given LLVM IR floating-point condition code. This includes
968/// consideration of global floating-point math flags.
969///
970static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
971 ISD::CondCode FPC, FOC;
972 switch (Pred) {
973 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
974 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
975 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
976 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
977 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
978 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
979 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
980 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
981 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
982 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
983 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
984 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
985 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
986 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
987 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
988 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
989 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000990 llvm_unreachable("Invalid FCmp predicate opcode!");
Dan Gohman8c1a6ca2008-10-17 18:18:45 +0000991 FOC = FPC = ISD::SETFALSE;
992 break;
993 }
994 if (FiniteOnlyFPMath())
995 return FOC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000996 else
Dan Gohman8c1a6ca2008-10-17 18:18:45 +0000997 return FPC;
998}
999
1000/// getICmpCondCode - Return the ISD condition code corresponding to
1001/// the given LLVM IR integer condition code.
1002///
1003static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1004 switch (Pred) {
1005 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1006 case ICmpInst::ICMP_NE: return ISD::SETNE;
1007 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1008 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1009 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1010 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1011 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1012 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1013 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1014 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1015 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001016 llvm_unreachable("Invalid ICmp predicate opcode!");
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001017 return ISD::SETNE;
1018 }
1019}
1020
Dan Gohmanc2277342008-10-17 21:16:08 +00001021/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1022/// This function emits a branch and is used at the leaves of an OR or an
1023/// AND operator tree.
1024///
1025void
Dan Gohman2048b852009-11-23 18:04:58 +00001026SelectionDAGBuilder::EmitBranchForMergedCondition(Value *Cond,
1027 MachineBasicBlock *TBB,
1028 MachineBasicBlock *FBB,
1029 MachineBasicBlock *CurBB) {
Dan Gohmanc2277342008-10-17 21:16:08 +00001030 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001031
Dan Gohmanc2277342008-10-17 21:16:08 +00001032 // If the leaf of the tree is a comparison, merge the condition into
1033 // the caseblock.
1034 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1035 // The operands of the cmp have to be in this block. We don't know
1036 // how to export them from some other block. If this is the first block
1037 // of the sequence, no exporting is needed.
1038 if (CurBB == CurMBB ||
1039 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1040 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001041 ISD::CondCode Condition;
1042 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001043 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001044 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001045 Condition = getFCmpCondCode(FC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001046 } else {
1047 Condition = ISD::SETEQ; // silence warning.
Torok Edwinc23197a2009-07-14 16:55:14 +00001048 llvm_unreachable("Unknown compare instruction");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001049 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001050
1051 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001052 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1053 SwitchCases.push_back(CB);
1054 return;
1055 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001056 }
1057
1058 // Create a CaseBlock record representing this branch.
Owen Anderson5defacc2009-07-31 17:39:07 +00001059 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
Dan Gohmanc2277342008-10-17 21:16:08 +00001060 NULL, TBB, FBB, CurBB);
1061 SwitchCases.push_back(CB);
1062}
1063
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001064/// FindMergedConditions - If Cond is an expression like
Dan Gohman2048b852009-11-23 18:04:58 +00001065void SelectionDAGBuilder::FindMergedConditions(Value *Cond,
1066 MachineBasicBlock *TBB,
1067 MachineBasicBlock *FBB,
1068 MachineBasicBlock *CurBB,
1069 unsigned Opc) {
Dan Gohmanc2277342008-10-17 21:16:08 +00001070 // If this node is not part of the or/and tree, emit it as a branch.
1071 Instruction *BOp = dyn_cast<Instruction>(Cond);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001072 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohmanc2277342008-10-17 21:16:08 +00001073 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1074 BOp->getParent() != CurBB->getBasicBlock() ||
1075 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1076 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1077 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001078 return;
1079 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001080
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001081 // Create TmpBB after CurBB.
1082 MachineFunction::iterator BBI = CurBB;
1083 MachineFunction &MF = DAG.getMachineFunction();
1084 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1085 CurBB->getParent()->insert(++BBI, TmpBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001086
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001087 if (Opc == Instruction::Or) {
1088 // Codegen X | Y as:
1089 // jmp_if_X TBB
1090 // jmp TmpBB
1091 // TmpBB:
1092 // jmp_if_Y TBB
1093 // jmp FBB
1094 //
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001095
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001096 // Emit the LHS condition.
1097 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001098
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001099 // Emit the RHS condition into TmpBB.
1100 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1101 } else {
1102 assert(Opc == Instruction::And && "Unknown merge op!");
1103 // Codegen X & Y as:
1104 // jmp_if_X TmpBB
1105 // jmp FBB
1106 // TmpBB:
1107 // jmp_if_Y TBB
1108 // jmp FBB
1109 //
1110 // This requires creation of TmpBB after CurBB.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001111
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001112 // Emit the LHS condition.
1113 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001114
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001115 // Emit the RHS condition into TmpBB.
1116 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1117 }
1118}
1119
1120/// If the set of cases should be emitted as a series of branches, return true.
1121/// If we should emit this as a bunch of and/or'd together conditions, return
1122/// false.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001123bool
Dan Gohman2048b852009-11-23 18:04:58 +00001124SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001125 if (Cases.size() != 2) return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001126
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001127 // If this is two comparisons of the same values or'd or and'd together, they
1128 // will get folded into a single comparison, so don't emit two blocks.
1129 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1130 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1131 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1132 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1133 return false;
1134 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001135
Chris Lattner133ce872010-01-02 00:00:03 +00001136 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1137 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1138 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1139 Cases[0].CC == Cases[1].CC &&
1140 isa<Constant>(Cases[0].CmpRHS) &&
1141 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1142 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1143 return false;
1144 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1145 return false;
1146 }
1147
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001148 return true;
1149}
1150
Dan Gohman2048b852009-11-23 18:04:58 +00001151void SelectionDAGBuilder::visitBr(BranchInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001152 // Update machine-CFG edges.
1153 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1154
1155 // Figure out which block is immediately after the current one.
1156 MachineBasicBlock *NextBlock = 0;
1157 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001158 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001159 NextBlock = BBI;
1160
1161 if (I.isUnconditional()) {
1162 // Update machine-CFG edges.
1163 CurMBB->addSuccessor(Succ0MBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001164
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001165 // If this is not a fall-through branch, emit the branch.
Bill Wendling4533cac2010-01-28 21:51:40 +00001166 if (Succ0MBB != NextBlock)
1167 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001168 MVT::Other, getControlRoot(),
Bill Wendling4533cac2010-01-28 21:51:40 +00001169 DAG.getBasicBlock(Succ0MBB)));
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001170
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001171 return;
1172 }
1173
1174 // If this condition is one of the special cases we handle, do special stuff
1175 // now.
1176 Value *CondVal = I.getCondition();
1177 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1178
1179 // If this is a series of conditions that are or'd or and'd together, emit
1180 // this as a sequence of branches instead of setcc's with and/or operations.
1181 // For example, instead of something like:
1182 // cmp A, B
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001183 // C = seteq
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001184 // cmp D, E
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001185 // F = setle
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001186 // or C, F
1187 // jnz foo
1188 // Emit:
1189 // cmp A, B
1190 // je foo
1191 // cmp D, E
1192 // jle foo
1193 //
1194 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001195 if (BOp->hasOneUse() &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001196 (BOp->getOpcode() == Instruction::And ||
1197 BOp->getOpcode() == Instruction::Or)) {
1198 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1199 // If the compares in later blocks need to use values not currently
1200 // exported from this block, export them now. This block should always
1201 // be the first entry.
1202 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001203
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001204 // Allow some cases to be rejected.
1205 if (ShouldEmitAsBranches(SwitchCases)) {
1206 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1207 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1208 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1209 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001210
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001211 // Emit the branch for this block.
1212 visitSwitchCase(SwitchCases[0]);
1213 SwitchCases.erase(SwitchCases.begin());
1214 return;
1215 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001216
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001217 // Okay, we decided not to do this, remove any inserted MBB's and clear
1218 // SwitchCases.
1219 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001220 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001221
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001222 SwitchCases.clear();
1223 }
1224 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001225
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001226 // Create a CaseBlock record representing this branch.
Owen Anderson5defacc2009-07-31 17:39:07 +00001227 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001228 NULL, Succ0MBB, Succ1MBB, CurMBB);
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001229
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001230 // Use visitSwitchCase to actually insert the fast branch sequence for this
1231 // cond branch.
1232 visitSwitchCase(CB);
1233}
1234
1235/// visitSwitchCase - Emits the necessary code to represent a single node in
1236/// the binary search tree resulting from lowering a switch instruction.
Dan Gohman2048b852009-11-23 18:04:58 +00001237void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001238 SDValue Cond;
1239 SDValue CondLHS = getValue(CB.CmpLHS);
Dale Johannesenf5d97892009-02-04 01:48:28 +00001240 DebugLoc dl = getCurDebugLoc();
Anton Korobeynikov23218582008-12-23 22:25:27 +00001241
1242 // Build the setcc now.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001243 if (CB.CmpMHS == NULL) {
1244 // Fold "(X == true)" to X and "(X == false)" to !X to
1245 // handle common cases produced by branch lowering.
Owen Anderson5defacc2009-07-31 17:39:07 +00001246 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
Owen Andersonf53c3712009-07-21 02:47:59 +00001247 CB.CC == ISD::SETEQ)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001248 Cond = CondLHS;
Owen Anderson5defacc2009-07-31 17:39:07 +00001249 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
Owen Andersonf53c3712009-07-21 02:47:59 +00001250 CB.CC == ISD::SETEQ) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001251 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001252 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001253 } else
Owen Anderson825b72b2009-08-11 20:47:22 +00001254 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001255 } else {
1256 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1257
Anton Korobeynikov23218582008-12-23 22:25:27 +00001258 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1259 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001260
1261 SDValue CmpOp = getValue(CB.CmpMHS);
Owen Andersone50ed302009-08-10 22:56:29 +00001262 EVT VT = CmpOp.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001263
1264 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001265 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
Dale Johannesenf5d97892009-02-04 01:48:28 +00001266 ISD::SETLE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001267 } else {
Dale Johannesenf5d97892009-02-04 01:48:28 +00001268 SDValue SUB = DAG.getNode(ISD::SUB, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001269 VT, CmpOp, DAG.getConstant(Low, VT));
Owen Anderson825b72b2009-08-11 20:47:22 +00001270 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001271 DAG.getConstant(High-Low, VT), ISD::SETULE);
1272 }
1273 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001274
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001275 // Update successor info
1276 CurMBB->addSuccessor(CB.TrueBB);
1277 CurMBB->addSuccessor(CB.FalseBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001278
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001279 // Set NextBlock to be the MBB immediately after the current one, if any.
1280 // This is used to avoid emitting unnecessary branches to the next block.
1281 MachineBasicBlock *NextBlock = 0;
1282 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001283 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001284 NextBlock = BBI;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001285
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001286 // If the lhs block is the next block, invert the condition so that we can
1287 // fall through to the lhs instead of the rhs block.
1288 if (CB.TrueBB == NextBlock) {
1289 std::swap(CB.TrueBB, CB.FalseBB);
1290 SDValue True = DAG.getConstant(1, Cond.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001291 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001292 }
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001293
Dale Johannesenf5d97892009-02-04 01:48:28 +00001294 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00001295 MVT::Other, getControlRoot(), Cond,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001296 DAG.getBasicBlock(CB.TrueBB));
Bill Wendling87710f02009-12-21 23:47:40 +00001297
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001298 // If the branch was constant folded, fix up the CFG.
1299 if (BrCond.getOpcode() == ISD::BR) {
1300 CurMBB->removeSuccessor(CB.FalseBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001301 } else {
1302 // Otherwise, go ahead and insert the false branch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001303 if (BrCond == getControlRoot())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001304 CurMBB->removeSuccessor(CB.TrueBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001305
Bill Wendling4533cac2010-01-28 21:51:40 +00001306 if (CB.FalseBB != NextBlock)
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001307 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1308 DAG.getBasicBlock(CB.FalseBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001309 }
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001310
1311 DAG.setRoot(BrCond);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001312}
1313
1314/// visitJumpTable - Emit JumpTable node in the current MBB
Dan Gohman2048b852009-11-23 18:04:58 +00001315void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001316 // Emit the code for the jump table
1317 assert(JT.Reg != -1U && "Should lower JT Header first!");
Owen Andersone50ed302009-08-10 22:56:29 +00001318 EVT PTy = TLI.getPointerTy();
Dale Johannesena04b7572009-02-03 23:04:43 +00001319 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1320 JT.Reg, PTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001321 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001322 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1323 MVT::Other, Index.getValue(1),
1324 Table, Index);
1325 DAG.setRoot(BrJumpTable);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001326}
1327
1328/// visitJumpTableHeader - This function emits necessary code to produce index
1329/// in the JumpTable from switch case.
Dan Gohman2048b852009-11-23 18:04:58 +00001330void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1331 JumpTableHeader &JTH) {
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001332 // Subtract the lowest switch case value from the value being switched on and
1333 // conditional branch to default mbb if the result is greater than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001334 // difference between smallest and largest cases.
1335 SDValue SwitchOp = getValue(JTH.SValue);
Owen Andersone50ed302009-08-10 22:56:29 +00001336 EVT VT = SwitchOp.getValueType();
Bill Wendling87710f02009-12-21 23:47:40 +00001337 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001338 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001339
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001340 // The SDNode we just created, which holds the value being switched on minus
1341 // the the smallest case value, needs to be copied to a virtual register so it
1342 // can be used as an index into the jump table in a subsequent basic block.
1343 // This value may be smaller or larger than the target's pointer type, and
1344 // therefore require extension or truncating.
Bill Wendling87710f02009-12-21 23:47:40 +00001345 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001346
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001347 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001348 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1349 JumpTableReg, SwitchOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001350 JT.Reg = JumpTableReg;
1351
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001352 // Emit the range check for the jump table, and branch to the default block
1353 // for the switch statement if the value being switched on exceeds the largest
1354 // case in the switch.
Dale Johannesenf5d97892009-02-04 01:48:28 +00001355 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00001356 TLI.getSetCCResultType(Sub.getValueType()), Sub,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001357 DAG.getConstant(JTH.Last-JTH.First,VT),
1358 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001359
1360 // Set NextBlock to be the MBB immediately after the current one, if any.
1361 // This is used to avoid emitting unnecessary branches to the next block.
1362 MachineBasicBlock *NextBlock = 0;
1363 MachineFunction::iterator BBI = CurMBB;
Bill Wendling87710f02009-12-21 23:47:40 +00001364
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001365 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001366 NextBlock = BBI;
1367
Dale Johannesen66978ee2009-01-31 02:22:37 +00001368 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001369 MVT::Other, CopyTo, CMP,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001370 DAG.getBasicBlock(JT.Default));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001371
Bill Wendling4533cac2010-01-28 21:51:40 +00001372 if (JT.MBB != NextBlock)
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001373 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1374 DAG.getBasicBlock(JT.MBB));
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001375
Bill Wendling87710f02009-12-21 23:47:40 +00001376 DAG.setRoot(BrCond);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001377}
1378
1379/// visitBitTestHeader - This function emits necessary code to produce value
1380/// suitable for "bit tests"
Dan Gohman2048b852009-11-23 18:04:58 +00001381void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001382 // Subtract the minimum value
1383 SDValue SwitchOp = getValue(B.SValue);
Owen Andersone50ed302009-08-10 22:56:29 +00001384 EVT VT = SwitchOp.getValueType();
Bill Wendling87710f02009-12-21 23:47:40 +00001385 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001386 DAG.getConstant(B.First, VT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001387
1388 // Check range
Dale Johannesenf5d97892009-02-04 01:48:28 +00001389 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00001390 TLI.getSetCCResultType(Sub.getValueType()),
1391 Sub, DAG.getConstant(B.Range, VT),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001392 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001393
Bill Wendling87710f02009-12-21 23:47:40 +00001394 SDValue ShiftOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(),
1395 TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001396
Duncan Sands92abc622009-01-31 15:50:11 +00001397 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001398 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1399 B.Reg, ShiftOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001400
1401 // Set NextBlock to be the MBB immediately after the current one, if any.
1402 // This is used to avoid emitting unnecessary branches to the next block.
1403 MachineBasicBlock *NextBlock = 0;
1404 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001405 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001406 NextBlock = BBI;
1407
1408 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1409
1410 CurMBB->addSuccessor(B.Default);
1411 CurMBB->addSuccessor(MBB);
1412
Dale Johannesen66978ee2009-01-31 02:22:37 +00001413 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001414 MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001415 DAG.getBasicBlock(B.Default));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001416
Bill Wendling4533cac2010-01-28 21:51:40 +00001417 if (MBB != NextBlock)
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001418 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1419 DAG.getBasicBlock(MBB));
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001420
Bill Wendling87710f02009-12-21 23:47:40 +00001421 DAG.setRoot(BrRange);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001422}
1423
1424/// visitBitTestCase - this function produces one "bit test"
Dan Gohman2048b852009-11-23 18:04:58 +00001425void SelectionDAGBuilder::visitBitTestCase(MachineBasicBlock* NextMBB,
1426 unsigned Reg,
1427 BitTestCase &B) {
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001428 // Make desired shift
Dale Johannesena04b7572009-02-03 23:04:43 +00001429 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
Duncan Sands92abc622009-01-31 15:50:11 +00001430 TLI.getPointerTy());
Scott Michelfdc40a02009-02-17 22:15:04 +00001431 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001432 TLI.getPointerTy(),
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001433 DAG.getConstant(1, TLI.getPointerTy()),
1434 ShiftOp);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001435
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001436 // Emit bit tests and jumps
Scott Michelfdc40a02009-02-17 22:15:04 +00001437 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001438 TLI.getPointerTy(), SwitchVal,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001439 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Dale Johannesenf5d97892009-02-04 01:48:28 +00001440 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1441 TLI.getSetCCResultType(AndOp.getValueType()),
Duncan Sands5480c042009-01-01 15:52:00 +00001442 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001443 ISD::SETNE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001444
1445 CurMBB->addSuccessor(B.TargetBB);
1446 CurMBB->addSuccessor(NextMBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001447
Dale Johannesen66978ee2009-01-31 02:22:37 +00001448 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001449 MVT::Other, getControlRoot(),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001450 AndCmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001451
1452 // Set NextBlock to be the MBB immediately after the current one, if any.
1453 // This is used to avoid emitting unnecessary branches to the next block.
1454 MachineBasicBlock *NextBlock = 0;
1455 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001456 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001457 NextBlock = BBI;
1458
Bill Wendling4533cac2010-01-28 21:51:40 +00001459 if (NextMBB != NextBlock)
Bill Wendling0777e922009-12-21 21:59:52 +00001460 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1461 DAG.getBasicBlock(NextMBB));
Bill Wendling0777e922009-12-21 21:59:52 +00001462
Bill Wendling87710f02009-12-21 23:47:40 +00001463 DAG.setRoot(BrAnd);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001464}
1465
Dan Gohman2048b852009-11-23 18:04:58 +00001466void SelectionDAGBuilder::visitInvoke(InvokeInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001467 // Retrieve successors.
1468 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1469 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1470
Gabor Greifb67e6b32009-01-15 11:10:44 +00001471 const Value *Callee(I.getCalledValue());
1472 if (isa<InlineAsm>(Callee))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001473 visitInlineAsm(&I);
1474 else
Gabor Greifb67e6b32009-01-15 11:10:44 +00001475 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001476
1477 // If the value of the invoke is used outside of its defining block, make it
1478 // available as a virtual register.
Dan Gohmanad62f532009-04-23 23:13:24 +00001479 CopyToExportRegsIfNeeded(&I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001480
1481 // Update successor info
1482 CurMBB->addSuccessor(Return);
1483 CurMBB->addSuccessor(LandingPad);
1484
1485 // Drop into normal successor.
Bill Wendling4533cac2010-01-28 21:51:40 +00001486 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1487 MVT::Other, getControlRoot(),
1488 DAG.getBasicBlock(Return)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001489}
1490
Dan Gohman2048b852009-11-23 18:04:58 +00001491void SelectionDAGBuilder::visitUnwind(UnwindInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001492}
1493
1494/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1495/// small case ranges).
Dan Gohman2048b852009-11-23 18:04:58 +00001496bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
1497 CaseRecVector& WorkList,
1498 Value* SV,
1499 MachineBasicBlock* Default) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001500 Case& BackCase = *(CR.Range.second-1);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001501
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001502 // Size is the number of Cases represented by this range.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001503 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001504 if (Size > 3)
Anton Korobeynikov23218582008-12-23 22:25:27 +00001505 return false;
1506
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001507 // Get the MachineFunction which holds the current MBB. This is used when
1508 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001509 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001510
1511 // Figure out which block is immediately after the current one.
1512 MachineBasicBlock *NextBlock = 0;
1513 MachineFunction::iterator BBI = CR.CaseBB;
1514
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001515 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001516 NextBlock = BBI;
1517
1518 // TODO: If any two of the cases has the same destination, and if one value
1519 // is the same as the other, but has one bit unset that the other has set,
1520 // use bit manipulation to do two compares at once. For example:
1521 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Anton Korobeynikov23218582008-12-23 22:25:27 +00001522
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001523 // Rearrange the case blocks so that the last one falls through if possible.
1524 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1525 // The last case block won't fall through into 'NextBlock' if we emit the
1526 // branches in this order. See if rearranging a case value would help.
1527 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1528 if (I->BB == NextBlock) {
1529 std::swap(*I, BackCase);
1530 break;
1531 }
1532 }
1533 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001534
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001535 // Create a CaseBlock record representing a conditional branch to
1536 // the Case's target mbb if the value being switched on SV is equal
1537 // to C.
1538 MachineBasicBlock *CurBlock = CR.CaseBB;
1539 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1540 MachineBasicBlock *FallThrough;
1541 if (I != E-1) {
1542 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1543 CurMF->insert(BBI, FallThrough);
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001544
1545 // Put SV in a virtual register to make it available from the new blocks.
1546 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001547 } else {
1548 // If the last case doesn't match, go to the default block.
1549 FallThrough = Default;
1550 }
1551
1552 Value *RHS, *LHS, *MHS;
1553 ISD::CondCode CC;
1554 if (I->High == I->Low) {
1555 // This is just small small case range :) containing exactly 1 case
1556 CC = ISD::SETEQ;
1557 LHS = SV; RHS = I->High; MHS = NULL;
1558 } else {
1559 CC = ISD::SETLE;
1560 LHS = I->Low; MHS = SV; RHS = I->High;
1561 }
1562 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001563
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001564 // If emitting the first comparison, just call visitSwitchCase to emit the
1565 // code into the current block. Otherwise, push the CaseBlock onto the
1566 // vector to be later processed by SDISel, and insert the node's MBB
1567 // before the next MBB.
1568 if (CurBlock == CurMBB)
1569 visitSwitchCase(CB);
1570 else
1571 SwitchCases.push_back(CB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001572
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001573 CurBlock = FallThrough;
1574 }
1575
1576 return true;
1577}
1578
1579static inline bool areJTsAllowed(const TargetLowering &TLI) {
1580 return !DisableJumpTables &&
Owen Anderson825b72b2009-08-11 20:47:22 +00001581 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1582 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001583}
Anton Korobeynikov23218582008-12-23 22:25:27 +00001584
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001585static APInt ComputeRange(const APInt &First, const APInt &Last) {
1586 APInt LastExt(Last), FirstExt(First);
1587 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1588 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1589 return (LastExt - FirstExt + 1ULL);
1590}
1591
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001592/// handleJTSwitchCase - Emit jumptable for current switch case range
Dan Gohman2048b852009-11-23 18:04:58 +00001593bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR,
1594 CaseRecVector& WorkList,
1595 Value* SV,
1596 MachineBasicBlock* Default) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001597 Case& FrontCase = *CR.Range.first;
1598 Case& BackCase = *(CR.Range.second-1);
1599
Chris Lattnere880efe2009-11-07 07:50:34 +00001600 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1601 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001602
Chris Lattnere880efe2009-11-07 07:50:34 +00001603 APInt TSize(First.getBitWidth(), 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001604 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1605 I!=E; ++I)
1606 TSize += I->size();
1607
Chris Lattnere880efe2009-11-07 07:50:34 +00001608 if (!areJTsAllowed(TLI) || TSize.ult(APInt(First.getBitWidth(), 4)))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001609 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001610
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001611 APInt Range = ComputeRange(First, Last);
Chris Lattnere880efe2009-11-07 07:50:34 +00001612 double Density = TSize.roundToDouble() / Range.roundToDouble();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001613 if (Density < 0.4)
1614 return false;
1615
David Greene4b69d992010-01-05 01:24:57 +00001616 DEBUG(dbgs() << "Lowering jump table\n"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001617 << "First entry: " << First << ". Last entry: " << Last << '\n'
1618 << "Range: " << Range
1619 << "Size: " << TSize << ". Density: " << Density << "\n\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001620
1621 // Get the MachineFunction which holds the current MBB. This is used when
1622 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001623 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001624
1625 // Figure out which block is immediately after the current one.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001626 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands51498522009-09-06 18:03:32 +00001627 ++BBI;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001628
1629 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1630
1631 // Create a new basic block to hold the code for loading the address
1632 // of the jump table, and jumping to it. Update successor information;
1633 // we will either branch to the default case for the switch, or the jump
1634 // table.
1635 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1636 CurMF->insert(BBI, JumpTableBB);
1637 CR.CaseBB->addSuccessor(Default);
1638 CR.CaseBB->addSuccessor(JumpTableBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001639
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001640 // Build a vector of destination BBs, corresponding to each target
1641 // of the jump table. If the value of the jump table slot corresponds to
1642 // a case statement, push the case's BB onto the vector, otherwise, push
1643 // the default BB.
1644 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001645 APInt TEI = First;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001646 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Chris Lattner071c62f2010-01-25 23:26:13 +00001647 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
1648 const APInt &High = cast<ConstantInt>(I->High)->getValue();
Anton Korobeynikov23218582008-12-23 22:25:27 +00001649
1650 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001651 DestBBs.push_back(I->BB);
1652 if (TEI==High)
1653 ++I;
1654 } else {
1655 DestBBs.push_back(Default);
1656 }
1657 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001658
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001659 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001660 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1661 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001662 E = DestBBs.end(); I != E; ++I) {
1663 if (!SuccsHandled[(*I)->getNumber()]) {
1664 SuccsHandled[(*I)->getNumber()] = true;
1665 JumpTableBB->addSuccessor(*I);
1666 }
1667 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001668
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001669 // Create a jump table index for this jump table, or return an existing
1670 // one.
Chris Lattner071c62f2010-01-25 23:26:13 +00001671 unsigned JTEncoding = TLI.getJumpTableEncoding();
1672 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
1673 ->getJumpTableIndex(DestBBs);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001674
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001675 // Set the jump table information so that we can codegen it as a second
1676 // MachineBasicBlock
1677 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1678 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1679 if (CR.CaseBB == CurMBB)
1680 visitJumpTableHeader(JT, JTH);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001681
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001682 JTCases.push_back(JumpTableBlock(JTH, JT));
1683
1684 return true;
1685}
1686
1687/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1688/// 2 subtrees.
Dan Gohman2048b852009-11-23 18:04:58 +00001689bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
1690 CaseRecVector& WorkList,
1691 Value* SV,
1692 MachineBasicBlock* Default) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001693 // Get the MachineFunction which holds the current MBB. This is used when
1694 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001695 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001696
1697 // Figure out which block is immediately after the current one.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001698 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands51498522009-09-06 18:03:32 +00001699 ++BBI;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001700
1701 Case& FrontCase = *CR.Range.first;
1702 Case& BackCase = *(CR.Range.second-1);
1703 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1704
1705 // Size is the number of Cases represented by this range.
1706 unsigned Size = CR.Range.second - CR.Range.first;
1707
Chris Lattnere880efe2009-11-07 07:50:34 +00001708 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1709 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001710 double FMetric = 0;
1711 CaseItr Pivot = CR.Range.first + Size/2;
1712
1713 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1714 // (heuristically) allow us to emit JumpTable's later.
Chris Lattnere880efe2009-11-07 07:50:34 +00001715 APInt TSize(First.getBitWidth(), 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001716 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1717 I!=E; ++I)
1718 TSize += I->size();
1719
Chris Lattnere880efe2009-11-07 07:50:34 +00001720 APInt LSize = FrontCase.size();
1721 APInt RSize = TSize-LSize;
David Greene4b69d992010-01-05 01:24:57 +00001722 DEBUG(dbgs() << "Selecting best pivot: \n"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001723 << "First: " << First << ", Last: " << Last <<'\n'
1724 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001725 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1726 J!=E; ++I, ++J) {
Chris Lattnere880efe2009-11-07 07:50:34 +00001727 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
1728 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001729 APInt Range = ComputeRange(LEnd, RBegin);
1730 assert((Range - 2ULL).isNonNegative() &&
1731 "Invalid case distance");
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00001732 double LDensity = (double)LSize.roundToDouble() /
Chris Lattnere880efe2009-11-07 07:50:34 +00001733 (LEnd - First + 1ULL).roundToDouble();
1734 double RDensity = (double)RSize.roundToDouble() /
1735 (Last - RBegin + 1ULL).roundToDouble();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001736 double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001737 // Should always split in some non-trivial place
David Greene4b69d992010-01-05 01:24:57 +00001738 DEBUG(dbgs() <<"=>Step\n"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001739 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1740 << "LDensity: " << LDensity
1741 << ", RDensity: " << RDensity << '\n'
1742 << "Metric: " << Metric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001743 if (FMetric < Metric) {
1744 Pivot = J;
1745 FMetric = Metric;
David Greene4b69d992010-01-05 01:24:57 +00001746 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001747 }
1748
1749 LSize += J->size();
1750 RSize -= J->size();
1751 }
1752 if (areJTsAllowed(TLI)) {
1753 // If our case is dense we *really* should handle it earlier!
1754 assert((FMetric > 0) && "Should handle dense range earlier!");
1755 } else {
1756 Pivot = CR.Range.first + Size/2;
1757 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001758
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001759 CaseRange LHSR(CR.Range.first, Pivot);
1760 CaseRange RHSR(Pivot, CR.Range.second);
1761 Constant *C = Pivot->Low;
1762 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001763
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001764 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001765 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001766 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001767 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001768 // Pivot's Value, then we can branch directly to the LHS's Target,
1769 // rather than creating a leaf node for it.
1770 if ((LHSR.second - LHSR.first) == 1 &&
1771 LHSR.first->High == CR.GE &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001772 cast<ConstantInt>(C)->getValue() ==
1773 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001774 TrueBB = LHSR.first->BB;
1775 } else {
1776 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1777 CurMF->insert(BBI, TrueBB);
1778 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001779
1780 // Put SV in a virtual register to make it available from the new blocks.
1781 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001782 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001783
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001784 // Similar to the optimization above, if the Value being switched on is
1785 // known to be less than the Constant CR.LT, and the current Case Value
1786 // is CR.LT - 1, then we can branch directly to the target block for
1787 // the current Case Value, rather than emitting a RHS leaf node for it.
1788 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001789 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1790 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001791 FalseBB = RHSR.first->BB;
1792 } else {
1793 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1794 CurMF->insert(BBI, FalseBB);
1795 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001796
1797 // Put SV in a virtual register to make it available from the new blocks.
1798 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001799 }
1800
1801 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001802 // the LHS node if the value being switched on SV is less than C.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001803 // Otherwise, branch to LHS.
1804 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1805
1806 if (CR.CaseBB == CurMBB)
1807 visitSwitchCase(CB);
1808 else
1809 SwitchCases.push_back(CB);
1810
1811 return true;
1812}
1813
1814/// handleBitTestsSwitchCase - if current case range has few destination and
1815/// range span less, than machine word bitwidth, encode case range into series
1816/// of masks and emit bit tests with these masks.
Dan Gohman2048b852009-11-23 18:04:58 +00001817bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
1818 CaseRecVector& WorkList,
1819 Value* SV,
1820 MachineBasicBlock* Default){
Owen Andersone50ed302009-08-10 22:56:29 +00001821 EVT PTy = TLI.getPointerTy();
Owen Anderson77547be2009-08-10 18:56:59 +00001822 unsigned IntPtrBits = PTy.getSizeInBits();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001823
1824 Case& FrontCase = *CR.Range.first;
1825 Case& BackCase = *(CR.Range.second-1);
1826
1827 // Get the MachineFunction which holds the current MBB. This is used when
1828 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001829 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001830
Anton Korobeynikovd34167a2009-05-08 18:51:34 +00001831 // If target does not have legal shift left, do not emit bit tests at all.
1832 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
1833 return false;
1834
Anton Korobeynikov23218582008-12-23 22:25:27 +00001835 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001836 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1837 I!=E; ++I) {
1838 // Single case counts one, case range - two.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001839 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001840 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001841
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001842 // Count unique destinations
1843 SmallSet<MachineBasicBlock*, 4> Dests;
1844 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1845 Dests.insert(I->BB);
1846 if (Dests.size() > 3)
1847 // Don't bother the code below, if there are too much unique destinations
1848 return false;
1849 }
David Greene4b69d992010-01-05 01:24:57 +00001850 DEBUG(dbgs() << "Total number of unique destinations: "
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00001851 << Dests.size() << '\n'
1852 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001853
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001854 // Compute span of values.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001855 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1856 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001857 APInt cmpRange = maxValue - minValue;
1858
David Greene4b69d992010-01-05 01:24:57 +00001859 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001860 << "Low bound: " << minValue << '\n'
1861 << "High bound: " << maxValue << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001862
1863 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001864 (!(Dests.size() == 1 && numCmps >= 3) &&
1865 !(Dests.size() == 2 && numCmps >= 5) &&
1866 !(Dests.size() >= 3 && numCmps >= 6)))
1867 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001868
David Greene4b69d992010-01-05 01:24:57 +00001869 DEBUG(dbgs() << "Emitting bit tests\n");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001870 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1871
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001872 // Optimize the case where all the case values fit in a
1873 // word without having to subtract minValue. In this case,
1874 // we can optimize away the subtraction.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001875 if (minValue.isNonNegative() &&
1876 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1877 cmpRange = maxValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001878 } else {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001879 lowBound = minValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001880 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001881
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001882 CaseBitsVector CasesBits;
1883 unsigned i, count = 0;
1884
1885 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1886 MachineBasicBlock* Dest = I->BB;
1887 for (i = 0; i < count; ++i)
1888 if (Dest == CasesBits[i].BB)
1889 break;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001890
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001891 if (i == count) {
1892 assert((count < 3) && "Too much destinations to test!");
1893 CasesBits.push_back(CaseBits(0, Dest, 0));
1894 count++;
1895 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001896
1897 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1898 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1899
1900 uint64_t lo = (lowValue - lowBound).getZExtValue();
1901 uint64_t hi = (highValue - lowBound).getZExtValue();
1902
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001903 for (uint64_t j = lo; j <= hi; j++) {
1904 CasesBits[i].Mask |= 1ULL << j;
1905 CasesBits[i].Bits++;
1906 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001907
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001908 }
1909 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001910
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001911 BitTestInfo BTC;
1912
1913 // Figure out which block is immediately after the current one.
1914 MachineFunction::iterator BBI = CR.CaseBB;
1915 ++BBI;
1916
1917 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1918
David Greene4b69d992010-01-05 01:24:57 +00001919 DEBUG(dbgs() << "Cases:\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001920 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
David Greene4b69d992010-01-05 01:24:57 +00001921 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001922 << ", Bits: " << CasesBits[i].Bits
1923 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001924
1925 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1926 CurMF->insert(BBI, CaseBB);
1927 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1928 CaseBB,
1929 CasesBits[i].BB));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001930
1931 // Put SV in a virtual register to make it available from the new blocks.
1932 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001933 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001934
1935 BitTestBlock BTB(lowBound, cmpRange, SV,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001936 -1U, (CR.CaseBB == CurMBB),
1937 CR.CaseBB, Default, BTC);
1938
1939 if (CR.CaseBB == CurMBB)
1940 visitBitTestHeader(BTB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001941
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001942 BitTestCases.push_back(BTB);
1943
1944 return true;
1945}
1946
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001947/// Clusterify - Transform simple list of Cases into list of CaseRange's
Dan Gohman2048b852009-11-23 18:04:58 +00001948size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
1949 const SwitchInst& SI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001950 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001951
1952 // Start with "simple" cases
Anton Korobeynikov23218582008-12-23 22:25:27 +00001953 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001954 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1955 Cases.push_back(Case(SI.getSuccessorValue(i),
1956 SI.getSuccessorValue(i),
1957 SMBB));
1958 }
1959 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1960
1961 // Merge case into clusters
Anton Korobeynikov23218582008-12-23 22:25:27 +00001962 if (Cases.size() >= 2)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001963 // Must recompute end() each iteration because it may be
1964 // invalidated by erase if we hold on to it
Anton Korobeynikov23218582008-12-23 22:25:27 +00001965 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
1966 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
1967 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001968 MachineBasicBlock* nextBB = J->BB;
1969 MachineBasicBlock* currentBB = I->BB;
1970
1971 // If the two neighboring cases go to the same destination, merge them
1972 // into a single case.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001973 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001974 I->High = J->High;
1975 J = Cases.erase(J);
1976 } else {
1977 I = J++;
1978 }
1979 }
1980
1981 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1982 if (I->Low != I->High)
1983 // A range counts double, since it requires two compares.
1984 ++numCmps;
1985 }
1986
1987 return numCmps;
1988}
1989
Dan Gohman2048b852009-11-23 18:04:58 +00001990void SelectionDAGBuilder::visitSwitch(SwitchInst &SI) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001991 // Figure out which block is immediately after the current one.
1992 MachineBasicBlock *NextBlock = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001993 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1994
1995 // If there is only the default destination, branch to it if it is not the
1996 // next basic block. Otherwise, just fall through.
1997 if (SI.getNumOperands() == 2) {
1998 // Update machine-CFG edges.
1999
2000 // If this is not a fall-through branch, emit the branch.
2001 CurMBB->addSuccessor(Default);
Bill Wendling4533cac2010-01-28 21:51:40 +00002002 if (Default != NextBlock)
2003 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
2004 MVT::Other, getControlRoot(),
2005 DAG.getBasicBlock(Default)));
Bill Wendling49fcff82009-12-21 22:30:11 +00002006
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002007 return;
2008 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002009
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002010 // If there are any non-default case statements, create a vector of Cases
2011 // representing each one, and sort the vector so that we can efficiently
2012 // create a binary search tree from them.
2013 CaseVector Cases;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002014 size_t numCmps = Clusterify(Cases, SI);
David Greene4b69d992010-01-05 01:24:57 +00002015 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002016 << ". Total compares: " << numCmps << '\n');
Devang Patel8a84e442009-01-05 17:31:22 +00002017 numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002018
2019 // Get the Value to be switched on and default basic blocks, which will be
2020 // inserted into CaseBlock records, representing basic blocks in the binary
2021 // search tree.
2022 Value *SV = SI.getOperand(0);
2023
2024 // Push the initial CaseRec onto the worklist
2025 CaseRecVector WorkList;
2026 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2027
2028 while (!WorkList.empty()) {
2029 // Grab a record representing a case range to process off the worklist
2030 CaseRec CR = WorkList.back();
2031 WorkList.pop_back();
2032
2033 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2034 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002035
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002036 // If the range has few cases (two or less) emit a series of specific
2037 // tests.
2038 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2039 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002040
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002041 // If the switch has more than 5 blocks, and at least 40% dense, and the
2042 // target supports indirect branches, then emit a jump table rather than
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002043 // lowering the switch to a binary tree of conditional branches.
2044 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2045 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002046
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002047 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2048 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2049 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2050 }
2051}
2052
Dan Gohman2048b852009-11-23 18:04:58 +00002053void SelectionDAGBuilder::visitIndirectBr(IndirectBrInst &I) {
Dan Gohmaneef55dc2009-10-27 22:10:34 +00002054 // Update machine-CFG edges.
2055 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
2056 CurMBB->addSuccessor(FuncInfo.MBBMap[I.getSuccessor(i)]);
2057
Bill Wendling4533cac2010-01-28 21:51:40 +00002058 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2059 MVT::Other, getControlRoot(),
2060 getValue(I.getAddress())));
Bill Wendling49fcff82009-12-21 22:30:11 +00002061}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002062
Dan Gohman2048b852009-11-23 18:04:58 +00002063void SelectionDAGBuilder::visitFSub(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002064 // -0.0 - X --> fneg
2065 const Type *Ty = I.getType();
2066 if (isa<VectorType>(Ty)) {
2067 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2068 const VectorType *DestTy = cast<VectorType>(I.getType());
2069 const Type *ElTy = DestTy->getElementType();
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002070 unsigned VL = DestTy->getNumElements();
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002071 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00002072 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002073 if (CV == CNZ) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002074 SDValue Op2 = getValue(I.getOperand(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00002075 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2076 Op2.getValueType(), Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002077 return;
2078 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002079 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002080 }
Bill Wendling49fcff82009-12-21 22:30:11 +00002081
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002082 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002083 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002084 SDValue Op2 = getValue(I.getOperand(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00002085 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2086 Op2.getValueType(), Op2));
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002087 return;
2088 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002089
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002090 visitBinary(I, ISD::FSUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002091}
2092
Dan Gohman2048b852009-11-23 18:04:58 +00002093void SelectionDAGBuilder::visitBinary(User &I, unsigned OpCode) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002094 SDValue Op1 = getValue(I.getOperand(0));
2095 SDValue Op2 = getValue(I.getOperand(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00002096 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2097 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002098}
2099
Dan Gohman2048b852009-11-23 18:04:58 +00002100void SelectionDAGBuilder::visitShift(User &I, unsigned Opcode) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002101 SDValue Op1 = getValue(I.getOperand(0));
2102 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman57fc82d2009-04-09 03:51:29 +00002103 if (!isa<VectorType>(I.getType()) &&
2104 Op2.getValueType() != TLI.getShiftAmountTy()) {
2105 // If the operand is smaller than the shift count type, promote it.
Owen Andersone50ed302009-08-10 22:56:29 +00002106 EVT PTy = TLI.getPointerTy();
2107 EVT STy = TLI.getShiftAmountTy();
Owen Anderson77547be2009-08-10 18:56:59 +00002108 if (STy.bitsGT(Op2.getValueType()))
Dan Gohman57fc82d2009-04-09 03:51:29 +00002109 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2110 TLI.getShiftAmountTy(), Op2);
2111 // If the operand is larger than the shift count type but the shift
2112 // count type has enough bits to represent any shift value, truncate
2113 // it now. This is a common case and it exposes the truncate to
2114 // optimization early.
Owen Anderson77547be2009-08-10 18:56:59 +00002115 else if (STy.getSizeInBits() >=
Dan Gohman57fc82d2009-04-09 03:51:29 +00002116 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2117 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2118 TLI.getShiftAmountTy(), Op2);
2119 // Otherwise we'll need to temporarily settle for some other
2120 // convenient type; type legalization will make adjustments as
2121 // needed.
Owen Anderson77547be2009-08-10 18:56:59 +00002122 else if (PTy.bitsLT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002123 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002124 TLI.getPointerTy(), Op2);
Owen Anderson77547be2009-08-10 18:56:59 +00002125 else if (PTy.bitsGT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002126 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002127 TLI.getPointerTy(), Op2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002128 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002129
Bill Wendling4533cac2010-01-28 21:51:40 +00002130 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2131 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002132}
2133
Dan Gohman2048b852009-11-23 18:04:58 +00002134void SelectionDAGBuilder::visitICmp(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002135 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2136 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2137 predicate = IC->getPredicate();
2138 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2139 predicate = ICmpInst::Predicate(IC->getPredicate());
2140 SDValue Op1 = getValue(I.getOperand(0));
2141 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002142 ISD::CondCode Opcode = getICmpCondCode(predicate);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002143
Owen Andersone50ed302009-08-10 22:56:29 +00002144 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002145 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002146}
2147
Dan Gohman2048b852009-11-23 18:04:58 +00002148void SelectionDAGBuilder::visitFCmp(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002149 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2150 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2151 predicate = FC->getPredicate();
2152 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2153 predicate = FCmpInst::Predicate(FC->getPredicate());
2154 SDValue Op1 = getValue(I.getOperand(0));
2155 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002156 ISD::CondCode Condition = getFCmpCondCode(predicate);
Owen Andersone50ed302009-08-10 22:56:29 +00002157 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002158 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002159}
2160
Dan Gohman2048b852009-11-23 18:04:58 +00002161void SelectionDAGBuilder::visitSelect(User &I) {
Owen Andersone50ed302009-08-10 22:56:29 +00002162 SmallVector<EVT, 4> ValueVTs;
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002163 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2164 unsigned NumValues = ValueVTs.size();
Bill Wendling49fcff82009-12-21 22:30:11 +00002165 if (NumValues == 0) return;
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002166
Bill Wendling49fcff82009-12-21 22:30:11 +00002167 SmallVector<SDValue, 4> Values(NumValues);
2168 SDValue Cond = getValue(I.getOperand(0));
2169 SDValue TrueVal = getValue(I.getOperand(1));
2170 SDValue FalseVal = getValue(I.getOperand(2));
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002171
Bill Wendling4533cac2010-01-28 21:51:40 +00002172 for (unsigned i = 0; i != NumValues; ++i)
Bill Wendling49fcff82009-12-21 22:30:11 +00002173 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2174 TrueVal.getNode()->getValueType(i), Cond,
2175 SDValue(TrueVal.getNode(),
2176 TrueVal.getResNo() + i),
2177 SDValue(FalseVal.getNode(),
2178 FalseVal.getResNo() + i));
2179
Bill Wendling4533cac2010-01-28 21:51:40 +00002180 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2181 DAG.getVTList(&ValueVTs[0], NumValues),
2182 &Values[0], NumValues));
Bill Wendling49fcff82009-12-21 22:30:11 +00002183}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002184
Dan Gohman2048b852009-11-23 18:04:58 +00002185void SelectionDAGBuilder::visitTrunc(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002186 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2187 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002188 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002189 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002190}
2191
Dan Gohman2048b852009-11-23 18:04:58 +00002192void SelectionDAGBuilder::visitZExt(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002193 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2194 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2195 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002196 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002197 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002198}
2199
Dan Gohman2048b852009-11-23 18:04:58 +00002200void SelectionDAGBuilder::visitSExt(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002201 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2202 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2203 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002204 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002205 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002206}
2207
Dan Gohman2048b852009-11-23 18:04:58 +00002208void SelectionDAGBuilder::visitFPTrunc(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002209 // FPTrunc is never a no-op cast, no need to check
2210 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002211 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002212 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2213 DestVT, N, DAG.getIntPtrConstant(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002214}
2215
Dan Gohman2048b852009-11-23 18:04:58 +00002216void SelectionDAGBuilder::visitFPExt(User &I){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002217 // FPTrunc is never a no-op cast, no need to check
2218 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002219 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002220 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002221}
2222
Dan Gohman2048b852009-11-23 18:04:58 +00002223void SelectionDAGBuilder::visitFPToUI(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002224 // FPToUI is never a no-op cast, no need to check
2225 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002226 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002227 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002228}
2229
Dan Gohman2048b852009-11-23 18:04:58 +00002230void SelectionDAGBuilder::visitFPToSI(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002231 // FPToSI is never a no-op cast, no need to check
2232 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002233 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002234 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002235}
2236
Dan Gohman2048b852009-11-23 18:04:58 +00002237void SelectionDAGBuilder::visitUIToFP(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002238 // UIToFP is never a no-op cast, no need to check
2239 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002240 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002241 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002242}
2243
Dan Gohman2048b852009-11-23 18:04:58 +00002244void SelectionDAGBuilder::visitSIToFP(User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002245 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002246 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002247 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002248 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002249}
2250
Dan Gohman2048b852009-11-23 18:04:58 +00002251void SelectionDAGBuilder::visitPtrToInt(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002252 // What to do depends on the size of the integer and the size of the pointer.
2253 // We can either truncate, zero extend, or no-op, accordingly.
2254 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002255 EVT SrcVT = N.getValueType();
2256 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002257 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002258}
2259
Dan Gohman2048b852009-11-23 18:04:58 +00002260void SelectionDAGBuilder::visitIntToPtr(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002261 // What to do depends on the size of the integer and the size of the pointer.
2262 // We can either truncate, zero extend, or no-op, accordingly.
2263 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002264 EVT SrcVT = N.getValueType();
2265 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002266 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002267}
2268
Dan Gohman2048b852009-11-23 18:04:58 +00002269void SelectionDAGBuilder::visitBitCast(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002270 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002271 EVT DestVT = TLI.getValueType(I.getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002272
Bill Wendling49fcff82009-12-21 22:30:11 +00002273 // BitCast assures us that source and destination are the same size so this is
2274 // either a BIT_CONVERT or a no-op.
Bill Wendling4533cac2010-01-28 21:51:40 +00002275 if (DestVT != N.getValueType())
2276 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
2277 DestVT, N)); // convert types.
2278 else
Bill Wendling49fcff82009-12-21 22:30:11 +00002279 setValue(&I, N); // noop cast.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002280}
2281
Dan Gohman2048b852009-11-23 18:04:58 +00002282void SelectionDAGBuilder::visitInsertElement(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002283 SDValue InVec = getValue(I.getOperand(0));
2284 SDValue InVal = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002285 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00002286 TLI.getPointerTy(),
2287 getValue(I.getOperand(2)));
Bill Wendling4533cac2010-01-28 21:51:40 +00002288 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2289 TLI.getValueType(I.getType()),
2290 InVec, InVal, InIdx));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002291}
2292
Dan Gohman2048b852009-11-23 18:04:58 +00002293void SelectionDAGBuilder::visitExtractElement(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002294 SDValue InVec = getValue(I.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00002295 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00002296 TLI.getPointerTy(),
2297 getValue(I.getOperand(1)));
Bill Wendling4533cac2010-01-28 21:51:40 +00002298 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2299 TLI.getValueType(I.getType()), InVec, InIdx));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002300}
2301
Mon P Wangaeb06d22008-11-10 04:46:22 +00002302// Utility for visitShuffleVector - Returns true if the mask is mask starting
2303// from SIndx and increasing to the element length (undefs are allowed).
Nate Begeman5a5ca152009-04-29 05:20:52 +00002304static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2305 unsigned MaskNumElts = Mask.size();
2306 for (unsigned i = 0; i != MaskNumElts; ++i)
2307 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
Nate Begeman9008ca62009-04-27 18:41:29 +00002308 return false;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002309 return true;
2310}
2311
Dan Gohman2048b852009-11-23 18:04:58 +00002312void SelectionDAGBuilder::visitShuffleVector(User &I) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002313 SmallVector<int, 8> Mask;
Mon P Wang230e4fa2008-11-21 04:25:21 +00002314 SDValue Src1 = getValue(I.getOperand(0));
2315 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002316
Nate Begeman9008ca62009-04-27 18:41:29 +00002317 // Convert the ConstantVector mask operand into an array of ints, with -1
2318 // representing undef values.
2319 SmallVector<Constant*, 8> MaskElts;
Chris Lattnerb29d5962010-02-01 20:48:08 +00002320 cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
Nate Begeman5a5ca152009-04-29 05:20:52 +00002321 unsigned MaskNumElts = MaskElts.size();
2322 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002323 if (isa<UndefValue>(MaskElts[i]))
2324 Mask.push_back(-1);
2325 else
2326 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2327 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002328
Owen Andersone50ed302009-08-10 22:56:29 +00002329 EVT VT = TLI.getValueType(I.getType());
2330 EVT SrcVT = Src1.getValueType();
Nate Begeman5a5ca152009-04-29 05:20:52 +00002331 unsigned SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002332
Mon P Wangc7849c22008-11-16 05:06:27 +00002333 if (SrcNumElts == MaskNumElts) {
Bill Wendling4533cac2010-01-28 21:51:40 +00002334 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2335 &Mask[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002336 return;
2337 }
2338
2339 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002340 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2341 // Mask is longer than the source vectors and is a multiple of the source
2342 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang230e4fa2008-11-21 04:25:21 +00002343 // lengths match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002344 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2345 // The shuffle is concatenating two vectors together.
Bill Wendling4533cac2010-01-28 21:51:40 +00002346 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2347 VT, Src1, Src2));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002348 return;
2349 }
2350
Mon P Wangc7849c22008-11-16 05:06:27 +00002351 // Pad both vectors with undefs to make them the same length as the mask.
2352 unsigned NumConcat = MaskNumElts / SrcNumElts;
Nate Begeman9008ca62009-04-27 18:41:29 +00002353 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2354 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
Dale Johannesene8d72302009-02-06 23:05:02 +00002355 SDValue UndefVal = DAG.getUNDEF(SrcVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002356
Nate Begeman9008ca62009-04-27 18:41:29 +00002357 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2358 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002359 MOps1[0] = Src1;
2360 MOps2[0] = Src2;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002361
2362 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2363 getCurDebugLoc(), VT,
Nate Begeman9008ca62009-04-27 18:41:29 +00002364 &MOps1[0], NumConcat);
2365 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002366 getCurDebugLoc(), VT,
Nate Begeman9008ca62009-04-27 18:41:29 +00002367 &MOps2[0], NumConcat);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002368
Mon P Wangaeb06d22008-11-10 04:46:22 +00002369 // Readjust mask for new input vector length.
Nate Begeman9008ca62009-04-27 18:41:29 +00002370 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002371 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002372 int Idx = Mask[i];
Nate Begeman5a5ca152009-04-29 05:20:52 +00002373 if (Idx < (int)SrcNumElts)
Nate Begeman9008ca62009-04-27 18:41:29 +00002374 MappedOps.push_back(Idx);
2375 else
2376 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002377 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002378
Bill Wendling4533cac2010-01-28 21:51:40 +00002379 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2380 &MappedOps[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002381 return;
2382 }
2383
Mon P Wangc7849c22008-11-16 05:06:27 +00002384 if (SrcNumElts > MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002385 // Analyze the access pattern of the vector to see if we can extract
2386 // two subvectors and do the shuffle. The analysis is done by calculating
2387 // the range of elements the mask access on both vectors.
2388 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2389 int MaxRange[2] = {-1, -1};
2390
Nate Begeman5a5ca152009-04-29 05:20:52 +00002391 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002392 int Idx = Mask[i];
2393 int Input = 0;
2394 if (Idx < 0)
2395 continue;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002396
Nate Begeman5a5ca152009-04-29 05:20:52 +00002397 if (Idx >= (int)SrcNumElts) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002398 Input = 1;
2399 Idx -= SrcNumElts;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002400 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002401 if (Idx > MaxRange[Input])
2402 MaxRange[Input] = Idx;
2403 if (Idx < MinRange[Input])
2404 MinRange[Input] = Idx;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002405 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002406
Mon P Wangc7849c22008-11-16 05:06:27 +00002407 // Check if the access is smaller than the vector size and can we find
2408 // a reasonable extract index.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002409 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not
2410 // Extract.
Mon P Wangc7849c22008-11-16 05:06:27 +00002411 int StartIdx[2]; // StartIdx to extract from
2412 for (int Input=0; Input < 2; ++Input) {
Nate Begeman5a5ca152009-04-29 05:20:52 +00002413 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002414 RangeUse[Input] = 0; // Unused
2415 StartIdx[Input] = 0;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002416 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002417 // Fits within range but we should see if we can find a good
Mon P Wang230e4fa2008-11-21 04:25:21 +00002418 // start index that is a multiple of the mask length.
Nate Begeman5a5ca152009-04-29 05:20:52 +00002419 if (MaxRange[Input] < (int)MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002420 RangeUse[Input] = 1; // Extract from beginning of the vector
2421 StartIdx[Input] = 0;
2422 } else {
2423 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002424 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002425 StartIdx[Input] + MaskNumElts < SrcNumElts)
Mon P Wangc7849c22008-11-16 05:06:27 +00002426 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002427 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002428 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002429 }
2430
Bill Wendling636e2582009-08-21 18:16:06 +00002431 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
Bill Wendling4533cac2010-01-28 21:51:40 +00002432 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
Mon P Wangc7849c22008-11-16 05:06:27 +00002433 return;
2434 }
2435 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2436 // Extract appropriate subvector and generate a vector shuffle
2437 for (int Input=0; Input < 2; ++Input) {
Bill Wendling87710f02009-12-21 23:47:40 +00002438 SDValue &Src = Input == 0 ? Src1 : Src2;
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002439 if (RangeUse[Input] == 0)
Dale Johannesene8d72302009-02-06 23:05:02 +00002440 Src = DAG.getUNDEF(VT);
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002441 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00002442 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002443 Src, DAG.getIntPtrConstant(StartIdx[Input]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002444 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002445
Mon P Wangc7849c22008-11-16 05:06:27 +00002446 // Calculate new mask.
Nate Begeman9008ca62009-04-27 18:41:29 +00002447 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002448 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002449 int Idx = Mask[i];
2450 if (Idx < 0)
2451 MappedOps.push_back(Idx);
Nate Begeman5a5ca152009-04-29 05:20:52 +00002452 else if (Idx < (int)SrcNumElts)
Nate Begeman9008ca62009-04-27 18:41:29 +00002453 MappedOps.push_back(Idx - StartIdx[0]);
2454 else
2455 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
Mon P Wangc7849c22008-11-16 05:06:27 +00002456 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002457
Bill Wendling4533cac2010-01-28 21:51:40 +00002458 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2459 &MappedOps[0]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002460 return;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002461 }
2462 }
2463
Mon P Wangc7849c22008-11-16 05:06:27 +00002464 // We can't use either concat vectors or extract subvectors so fall back to
2465 // replacing the shuffle with extract and build vector.
2466 // to insert and build vector.
Owen Andersone50ed302009-08-10 22:56:29 +00002467 EVT EltVT = VT.getVectorElementType();
2468 EVT PtrVT = TLI.getPointerTy();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002469 SmallVector<SDValue,8> Ops;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002470 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002471 if (Mask[i] < 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002472 Ops.push_back(DAG.getUNDEF(EltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002473 } else {
Nate Begeman9008ca62009-04-27 18:41:29 +00002474 int Idx = Mask[i];
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002475 SDValue Res;
2476
Nate Begeman5a5ca152009-04-29 05:20:52 +00002477 if (Idx < (int)SrcNumElts)
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002478 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2479 EltVT, Src1, DAG.getConstant(Idx, PtrVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002480 else
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002481 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2482 EltVT, Src2,
2483 DAG.getConstant(Idx - SrcNumElts, PtrVT));
2484
2485 Ops.push_back(Res);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002486 }
2487 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002488
Bill Wendling4533cac2010-01-28 21:51:40 +00002489 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2490 VT, &Ops[0], Ops.size()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002491}
2492
Dan Gohman2048b852009-11-23 18:04:58 +00002493void SelectionDAGBuilder::visitInsertValue(InsertValueInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002494 const Value *Op0 = I.getOperand(0);
2495 const Value *Op1 = I.getOperand(1);
2496 const Type *AggTy = I.getType();
2497 const Type *ValTy = Op1->getType();
2498 bool IntoUndef = isa<UndefValue>(Op0);
2499 bool FromUndef = isa<UndefValue>(Op1);
2500
2501 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2502 I.idx_begin(), I.idx_end());
2503
Owen Andersone50ed302009-08-10 22:56:29 +00002504 SmallVector<EVT, 4> AggValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002505 ComputeValueVTs(TLI, AggTy, AggValueVTs);
Owen Andersone50ed302009-08-10 22:56:29 +00002506 SmallVector<EVT, 4> ValValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002507 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2508
2509 unsigned NumAggValues = AggValueVTs.size();
2510 unsigned NumValValues = ValValueVTs.size();
2511 SmallVector<SDValue, 4> Values(NumAggValues);
2512
2513 SDValue Agg = getValue(Op0);
2514 SDValue Val = getValue(Op1);
2515 unsigned i = 0;
2516 // Copy the beginning value(s) from the original aggregate.
2517 for (; i != LinearIndex; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002518 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002519 SDValue(Agg.getNode(), Agg.getResNo() + i);
2520 // Copy values from the inserted value(s).
2521 for (; i != LinearIndex + NumValValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002522 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002523 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2524 // Copy remaining value(s) from the original aggregate.
2525 for (; i != NumAggValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002526 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002527 SDValue(Agg.getNode(), Agg.getResNo() + i);
2528
Bill Wendling4533cac2010-01-28 21:51:40 +00002529 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2530 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2531 &Values[0], NumAggValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002532}
2533
Dan Gohman2048b852009-11-23 18:04:58 +00002534void SelectionDAGBuilder::visitExtractValue(ExtractValueInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002535 const Value *Op0 = I.getOperand(0);
2536 const Type *AggTy = Op0->getType();
2537 const Type *ValTy = I.getType();
2538 bool OutOfUndef = isa<UndefValue>(Op0);
2539
2540 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2541 I.idx_begin(), I.idx_end());
2542
Owen Andersone50ed302009-08-10 22:56:29 +00002543 SmallVector<EVT, 4> ValValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002544 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2545
2546 unsigned NumValValues = ValValueVTs.size();
2547 SmallVector<SDValue, 4> Values(NumValValues);
2548
2549 SDValue Agg = getValue(Op0);
2550 // Copy out the selected value(s).
2551 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2552 Values[i - LinearIndex] =
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002553 OutOfUndef ?
Dale Johannesene8d72302009-02-06 23:05:02 +00002554 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002555 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002556
Bill Wendling4533cac2010-01-28 21:51:40 +00002557 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2558 DAG.getVTList(&ValValueVTs[0], NumValValues),
2559 &Values[0], NumValValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002560}
2561
Dan Gohman2048b852009-11-23 18:04:58 +00002562void SelectionDAGBuilder::visitGetElementPtr(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002563 SDValue N = getValue(I.getOperand(0));
2564 const Type *Ty = I.getOperand(0)->getType();
2565
2566 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2567 OI != E; ++OI) {
2568 Value *Idx = *OI;
2569 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2570 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2571 if (Field) {
2572 // N = N + Offset
2573 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002574 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002575 DAG.getIntPtrConstant(Offset));
2576 }
Bill Wendlinge1a90422009-12-21 23:10:19 +00002577
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002578 Ty = StTy->getElementType(Field);
2579 } else {
2580 Ty = cast<SequentialType>(Ty)->getElementType();
2581
2582 // If this is a constant subscript, handle it quickly.
2583 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2584 if (CI->getZExtValue() == 0) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002585 uint64_t Offs =
Duncan Sands777d2302009-05-09 07:06:46 +00002586 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Evan Cheng65b52df2009-02-09 21:01:06 +00002587 SDValue OffsVal;
Owen Andersone50ed302009-08-10 22:56:29 +00002588 EVT PTy = TLI.getPointerTy();
Owen Anderson77547be2009-08-10 18:56:59 +00002589 unsigned PtrBits = PTy.getSizeInBits();
Bill Wendlinge1a90422009-12-21 23:10:19 +00002590 if (PtrBits < 64)
Evan Cheng65b52df2009-02-09 21:01:06 +00002591 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2592 TLI.getPointerTy(),
Owen Anderson825b72b2009-08-11 20:47:22 +00002593 DAG.getConstant(Offs, MVT::i64));
Bill Wendlinge1a90422009-12-21 23:10:19 +00002594 else
Evan Chengb1032a82009-02-09 20:54:38 +00002595 OffsVal = DAG.getIntPtrConstant(Offs);
Bill Wendlinge1a90422009-12-21 23:10:19 +00002596
Dale Johannesen66978ee2009-01-31 02:22:37 +00002597 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Evan Chengb1032a82009-02-09 20:54:38 +00002598 OffsVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002599 continue;
2600 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002601
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002602 // N = N + Idx * ElementSize;
Dan Gohman7abbd042009-10-23 17:57:43 +00002603 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
2604 TD->getTypeAllocSize(Ty));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002605 SDValue IdxN = getValue(Idx);
2606
2607 // If the index is smaller or larger than intptr_t, truncate or extend
2608 // it.
Duncan Sands3a66a682009-10-13 21:04:12 +00002609 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002610
2611 // If this is a multiply by a power of two, turn it into a shl
2612 // immediately. This is a very common case.
2613 if (ElementSize != 1) {
Dan Gohman7abbd042009-10-23 17:57:43 +00002614 if (ElementSize.isPowerOf2()) {
2615 unsigned Amt = ElementSize.logBase2();
Scott Michelfdc40a02009-02-17 22:15:04 +00002616 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002617 N.getValueType(), IdxN,
Duncan Sands92abc622009-01-31 15:50:11 +00002618 DAG.getConstant(Amt, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002619 } else {
Dan Gohman7abbd042009-10-23 17:57:43 +00002620 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
Scott Michelfdc40a02009-02-17 22:15:04 +00002621 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002622 N.getValueType(), IdxN, Scale);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002623 }
2624 }
2625
Scott Michelfdc40a02009-02-17 22:15:04 +00002626 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002627 N.getValueType(), N, IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002628 }
2629 }
Bill Wendlinge1a90422009-12-21 23:10:19 +00002630
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002631 setValue(&I, N);
2632}
2633
Dan Gohman2048b852009-11-23 18:04:58 +00002634void SelectionDAGBuilder::visitAlloca(AllocaInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002635 // If this is a fixed sized alloca in the entry block of the function,
2636 // allocate it statically on the stack.
2637 if (FuncInfo.StaticAllocaMap.count(&I))
2638 return; // getValue will auto-populate this.
2639
2640 const Type *Ty = I.getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002641 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002642 unsigned Align =
2643 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2644 I.getAlignment());
2645
2646 SDValue AllocSize = getValue(I.getArraySize());
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002647
Chris Lattner0b18e592009-03-17 19:36:00 +00002648 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2649 AllocSize,
2650 DAG.getConstant(TySize, AllocSize.getValueType()));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002651
Owen Andersone50ed302009-08-10 22:56:29 +00002652 EVT IntPtr = TLI.getPointerTy();
Duncan Sands3a66a682009-10-13 21:04:12 +00002653 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002654
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002655 // Handle alignment. If the requested alignment is less than or equal to
2656 // the stack alignment, ignore it. If the size is greater than or equal to
2657 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2658 unsigned StackAlign =
2659 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2660 if (Align <= StackAlign)
2661 Align = 0;
2662
2663 // Round the size of the allocation up to the stack alignment size
2664 // by add SA-1 to the size.
Scott Michelfdc40a02009-02-17 22:15:04 +00002665 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002666 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002667 DAG.getIntPtrConstant(StackAlign-1));
Bill Wendling856ff412009-12-22 00:12:37 +00002668
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002669 // Mask out the low bits for alignment purposes.
Scott Michelfdc40a02009-02-17 22:15:04 +00002670 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002671 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002672 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2673
2674 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Owen Anderson825b72b2009-08-11 20:47:22 +00002675 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
Scott Michelfdc40a02009-02-17 22:15:04 +00002676 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002677 VTs, Ops, 3);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002678 setValue(&I, DSA);
2679 DAG.setRoot(DSA.getValue(1));
Bill Wendling856ff412009-12-22 00:12:37 +00002680
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002681 // Inform the Frame Information that we have just allocated a variable-sized
2682 // object.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00002683 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002684}
2685
Dan Gohman2048b852009-11-23 18:04:58 +00002686void SelectionDAGBuilder::visitLoad(LoadInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002687 const Value *SV = I.getOperand(0);
2688 SDValue Ptr = getValue(SV);
2689
2690 const Type *Ty = I.getType();
2691 bool isVolatile = I.isVolatile();
2692 unsigned Alignment = I.getAlignment();
2693
Owen Andersone50ed302009-08-10 22:56:29 +00002694 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002695 SmallVector<uint64_t, 4> Offsets;
2696 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2697 unsigned NumValues = ValueVTs.size();
2698 if (NumValues == 0)
2699 return;
2700
2701 SDValue Root;
2702 bool ConstantMemory = false;
2703 if (I.isVolatile())
2704 // Serialize volatile loads with other side effects.
2705 Root = getRoot();
2706 else if (AA->pointsToConstantMemory(SV)) {
2707 // Do not serialize (non-volatile) loads of constant memory with anything.
2708 Root = DAG.getEntryNode();
2709 ConstantMemory = true;
2710 } else {
2711 // Do not serialize non-volatile loads against each other.
2712 Root = DAG.getRoot();
2713 }
2714
2715 SmallVector<SDValue, 4> Values(NumValues);
2716 SmallVector<SDValue, 4> Chains(NumValues);
Owen Andersone50ed302009-08-10 22:56:29 +00002717 EVT PtrVT = Ptr.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002718 for (unsigned i = 0; i != NumValues; ++i) {
Bill Wendling856ff412009-12-22 00:12:37 +00002719 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2720 PtrVT, Ptr,
2721 DAG.getConstant(Offsets[i], PtrVT));
Dale Johannesen66978ee2009-01-31 02:22:37 +00002722 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
Bill Wendling856ff412009-12-22 00:12:37 +00002723 A, SV, Offsets[i], isVolatile, Alignment);
2724
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002725 Values[i] = L;
2726 Chains[i] = L.getValue(1);
2727 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002728
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002729 if (!ConstantMemory) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002730 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Bill Wendling856ff412009-12-22 00:12:37 +00002731 MVT::Other, &Chains[0], NumValues);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002732 if (isVolatile)
2733 DAG.setRoot(Chain);
2734 else
2735 PendingLoads.push_back(Chain);
2736 }
2737
Bill Wendling4533cac2010-01-28 21:51:40 +00002738 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2739 DAG.getVTList(&ValueVTs[0], NumValues),
2740 &Values[0], NumValues));
Bill Wendling856ff412009-12-22 00:12:37 +00002741}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002742
Dan Gohman2048b852009-11-23 18:04:58 +00002743void SelectionDAGBuilder::visitStore(StoreInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002744 Value *SrcV = I.getOperand(0);
2745 Value *PtrV = I.getOperand(1);
2746
Owen Andersone50ed302009-08-10 22:56:29 +00002747 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002748 SmallVector<uint64_t, 4> Offsets;
2749 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2750 unsigned NumValues = ValueVTs.size();
2751 if (NumValues == 0)
2752 return;
2753
2754 // Get the lowered operands. Note that we do this after
2755 // checking if NumResults is zero, because with zero results
2756 // the operands won't have values in the map.
2757 SDValue Src = getValue(SrcV);
2758 SDValue Ptr = getValue(PtrV);
2759
2760 SDValue Root = getRoot();
2761 SmallVector<SDValue, 4> Chains(NumValues);
Owen Andersone50ed302009-08-10 22:56:29 +00002762 EVT PtrVT = Ptr.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002763 bool isVolatile = I.isVolatile();
2764 unsigned Alignment = I.getAlignment();
Bill Wendling856ff412009-12-22 00:12:37 +00002765
2766 for (unsigned i = 0; i != NumValues; ++i) {
2767 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
2768 DAG.getConstant(Offsets[i], PtrVT));
Dale Johannesen66978ee2009-01-31 02:22:37 +00002769 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002770 SDValue(Src.getNode(), Src.getResNo() + i),
Bill Wendling856ff412009-12-22 00:12:37 +00002771 Add, PtrV, Offsets[i], isVolatile, Alignment);
Bill Wendling856ff412009-12-22 00:12:37 +00002772 }
2773
Bill Wendling4533cac2010-01-28 21:51:40 +00002774 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2775 MVT::Other, &Chains[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002776}
2777
2778/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2779/// node.
Dan Gohman2048b852009-11-23 18:04:58 +00002780void SelectionDAGBuilder::visitTargetIntrinsic(CallInst &I,
2781 unsigned Intrinsic) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002782 bool HasChain = !I.doesNotAccessMemory();
2783 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2784
2785 // Build the operand list.
2786 SmallVector<SDValue, 8> Ops;
2787 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2788 if (OnlyLoad) {
2789 // We don't need to serialize loads against other loads.
2790 Ops.push_back(DAG.getRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002791 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002792 Ops.push_back(getRoot());
2793 }
2794 }
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002795
2796 // Info is set by getTgtMemInstrinsic
2797 TargetLowering::IntrinsicInfo Info;
2798 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2799
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002800 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002801 if (!IsTgtIntrinsic)
2802 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002803
2804 // Add all operands of the call to the operand list.
2805 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2806 SDValue Op = getValue(I.getOperand(i));
2807 assert(TLI.isTypeLegal(Op.getValueType()) &&
2808 "Intrinsic uses a non-legal type?");
2809 Ops.push_back(Op);
2810 }
2811
Owen Andersone50ed302009-08-10 22:56:29 +00002812 SmallVector<EVT, 4> ValueVTs;
Bob Wilson8d919552009-07-31 22:41:21 +00002813 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2814#ifndef NDEBUG
2815 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
2816 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
2817 "Intrinsic uses a non-legal type?");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002818 }
Bob Wilson8d919552009-07-31 22:41:21 +00002819#endif // NDEBUG
Bill Wendling856ff412009-12-22 00:12:37 +00002820
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002821 if (HasChain)
Owen Anderson825b72b2009-08-11 20:47:22 +00002822 ValueVTs.push_back(MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002823
Bob Wilson8d919552009-07-31 22:41:21 +00002824 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002825
2826 // Create the node.
2827 SDValue Result;
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002828 if (IsTgtIntrinsic) {
2829 // This is target intrinsic that touches memory
Dale Johannesen66978ee2009-01-31 02:22:37 +00002830 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002831 VTs, &Ops[0], Ops.size(),
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002832 Info.memVT, Info.ptrVal, Info.offset,
2833 Info.align, Info.vol,
2834 Info.readMem, Info.writeMem);
Bill Wendling856ff412009-12-22 00:12:37 +00002835 } else if (!HasChain) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002836 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002837 VTs, &Ops[0], Ops.size());
Benjamin Kramerf0127052010-01-05 13:12:22 +00002838 } else if (!I.getType()->isVoidTy()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002839 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002840 VTs, &Ops[0], Ops.size());
Bill Wendling856ff412009-12-22 00:12:37 +00002841 } else {
Scott Michelfdc40a02009-02-17 22:15:04 +00002842 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002843 VTs, &Ops[0], Ops.size());
Bill Wendling856ff412009-12-22 00:12:37 +00002844 }
2845
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002846 if (HasChain) {
2847 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2848 if (OnlyLoad)
2849 PendingLoads.push_back(Chain);
2850 else
2851 DAG.setRoot(Chain);
2852 }
Bill Wendling856ff412009-12-22 00:12:37 +00002853
Benjamin Kramerf0127052010-01-05 13:12:22 +00002854 if (!I.getType()->isVoidTy()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002855 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Owen Andersone50ed302009-08-10 22:56:29 +00002856 EVT VT = TLI.getValueType(PTy);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002857 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002858 }
Bill Wendling856ff412009-12-22 00:12:37 +00002859
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002860 setValue(&I, Result);
2861 }
2862}
2863
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002864/// GetSignificand - Get the significand and build it into a floating-point
2865/// number with exponent of 1:
2866///
2867/// Op = (Op & 0x007fffff) | 0x3f800000;
2868///
2869/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002870static SDValue
Bill Wendling856ff412009-12-22 00:12:37 +00002871GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl, unsigned Order) {
Owen Anderson825b72b2009-08-11 20:47:22 +00002872 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
2873 DAG.getConstant(0x007fffff, MVT::i32));
2874 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
2875 DAG.getConstant(0x3f800000, MVT::i32));
Bill Wendling4533cac2010-01-28 21:51:40 +00002876 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00002877}
2878
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002879/// GetExponent - Get the exponent:
2880///
Bill Wendlinge9a72862009-01-20 21:17:57 +00002881/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002882///
2883/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002884static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00002885GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
Bill Wendling856ff412009-12-22 00:12:37 +00002886 DebugLoc dl, unsigned Order) {
Owen Anderson825b72b2009-08-11 20:47:22 +00002887 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
2888 DAG.getConstant(0x7f800000, MVT::i32));
2889 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
Duncan Sands92abc622009-01-31 15:50:11 +00002890 DAG.getConstant(23, TLI.getPointerTy()));
Owen Anderson825b72b2009-08-11 20:47:22 +00002891 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
2892 DAG.getConstant(127, MVT::i32));
Bill Wendling4533cac2010-01-28 21:51:40 +00002893 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00002894}
2895
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002896/// getF32Constant - Get 32-bit floating point constant.
2897static SDValue
2898getF32Constant(SelectionDAG &DAG, unsigned Flt) {
Owen Anderson825b72b2009-08-11 20:47:22 +00002899 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002900}
2901
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002902/// Inlined utility function to implement binary input atomic intrinsics for
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002903/// visitIntrinsicCall: I is a call instruction
2904/// Op is the associated NodeType for I
2905const char *
Dan Gohman2048b852009-11-23 18:04:58 +00002906SelectionDAGBuilder::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002907 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00002908 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00002909 DAG.getAtomic(Op, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002910 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00002911 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002912 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00002913 getValue(I.getOperand(2)),
2914 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002915 setValue(&I, L);
2916 DAG.setRoot(L.getValue(1));
2917 return 0;
2918}
2919
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002920// implVisitAluOverflow - Lower arithmetic overflow instrinsics.
Bill Wendling74c37652008-12-09 22:08:41 +00002921const char *
Dan Gohman2048b852009-11-23 18:04:58 +00002922SelectionDAGBuilder::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002923 SDValue Op1 = getValue(I.getOperand(1));
2924 SDValue Op2 = getValue(I.getOperand(2));
Bill Wendling74c37652008-12-09 22:08:41 +00002925
Owen Anderson825b72b2009-08-11 20:47:22 +00002926 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
Bill Wendling4533cac2010-01-28 21:51:40 +00002927 setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2));
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002928 return 0;
2929}
Bill Wendling74c37652008-12-09 22:08:41 +00002930
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002931/// visitExp - Lower an exp intrinsic. Handles the special sequences for
2932/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00002933void
Dan Gohman2048b852009-11-23 18:04:58 +00002934SelectionDAGBuilder::visitExp(CallInst &I) {
Dale Johannesen59e577f2008-09-05 18:38:42 +00002935 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00002936 DebugLoc dl = getCurDebugLoc();
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002937
Owen Anderson825b72b2009-08-11 20:47:22 +00002938 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002939 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2940 SDValue Op = getValue(I.getOperand(1));
2941
2942 // Put the exponent in the right bit position for later addition to the
2943 // final result:
2944 //
2945 // #define LOG2OFe 1.4426950f
2946 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
Owen Anderson825b72b2009-08-11 20:47:22 +00002947 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002948 getF32Constant(DAG, 0x3fb8aa3b));
Owen Anderson825b72b2009-08-11 20:47:22 +00002949 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002950
2951 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00002952 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
2953 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002954
2955 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00002956 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00002957 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendling856ff412009-12-22 00:12:37 +00002958
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002959 if (LimitFloatPrecision <= 6) {
2960 // For floating-point precision of 6:
2961 //
2962 // TwoToFractionalPartOfX =
2963 // 0.997535578f +
2964 // (0.735607626f + 0.252464424f * x) * x;
2965 //
2966 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00002967 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002968 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00002969 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002970 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00002971 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
2972 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002973 getF32Constant(DAG, 0x3f7f5e7e));
Owen Anderson825b72b2009-08-11 20:47:22 +00002974 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002975
2976 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00002977 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002978 TwoToFracPartOfX, IntegerPartOfX);
2979
Owen Anderson825b72b2009-08-11 20:47:22 +00002980 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002981 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
2982 // For floating-point precision of 12:
2983 //
2984 // TwoToFractionalPartOfX =
2985 // 0.999892986f +
2986 // (0.696457318f +
2987 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
2988 //
2989 // 0.000107046256 error, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00002990 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002991 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00002992 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002993 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00002994 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
2995 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002996 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00002997 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
2998 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002999 getF32Constant(DAG, 0x3f7ff8fd));
Owen Anderson825b72b2009-08-11 20:47:22 +00003000 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003001
3002 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00003003 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003004 TwoToFracPartOfX, IntegerPartOfX);
3005
Owen Anderson825b72b2009-08-11 20:47:22 +00003006 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003007 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3008 // For floating-point precision of 18:
3009 //
3010 // TwoToFractionalPartOfX =
3011 // 0.999999982f +
3012 // (0.693148872f +
3013 // (0.240227044f +
3014 // (0.554906021e-1f +
3015 // (0.961591928e-2f +
3016 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3017 //
3018 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003019 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003020 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003021 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003022 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003023 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3024 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003025 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003026 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3027 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003028 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003029 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3030 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003031 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003032 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3033 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003034 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003035 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3036 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003037 getF32Constant(DAG, 0x3f800000));
Scott Michelfdc40a02009-02-17 22:15:04 +00003038 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003039 MVT::i32, t13);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003040
3041 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00003042 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003043 TwoToFracPartOfX, IntegerPartOfX);
3044
Owen Anderson825b72b2009-08-11 20:47:22 +00003045 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003046 }
3047 } else {
3048 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003049 result = DAG.getNode(ISD::FEXP, dl,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003050 getValue(I.getOperand(1)).getValueType(),
3051 getValue(I.getOperand(1)));
3052 }
3053
Dale Johannesen59e577f2008-09-05 18:38:42 +00003054 setValue(&I, result);
3055}
3056
Bill Wendling39150252008-09-09 20:39:27 +00003057/// visitLog - Lower a log intrinsic. Handles the special sequences for
3058/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003059void
Dan Gohman2048b852009-11-23 18:04:58 +00003060SelectionDAGBuilder::visitLog(CallInst &I) {
Dale Johannesen59e577f2008-09-05 18:38:42 +00003061 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003062 DebugLoc dl = getCurDebugLoc();
Bill Wendling39150252008-09-09 20:39:27 +00003063
Owen Anderson825b72b2009-08-11 20:47:22 +00003064 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling39150252008-09-09 20:39:27 +00003065 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3066 SDValue Op = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003067 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling39150252008-09-09 20:39:27 +00003068
3069 // Scale the exponent by log(2) [0.69314718f].
Bill Wendling856ff412009-12-22 00:12:37 +00003070 SDValue Exp = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
Owen Anderson825b72b2009-08-11 20:47:22 +00003071 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003072 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003073
3074 // Get the significand and build it into a floating-point number with
3075 // exponent of 1.
Bill Wendling856ff412009-12-22 00:12:37 +00003076 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
Bill Wendling39150252008-09-09 20:39:27 +00003077
3078 if (LimitFloatPrecision <= 6) {
3079 // For floating-point precision of 6:
3080 //
3081 // LogofMantissa =
3082 // -1.1609546f +
3083 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003084 //
Bill Wendling39150252008-09-09 20:39:27 +00003085 // error 0.0034276066, which is better than 8 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003086 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003087 getF32Constant(DAG, 0xbe74c456));
Owen Anderson825b72b2009-08-11 20:47:22 +00003088 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003089 getF32Constant(DAG, 0x3fb3a2b1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003090 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3091 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003092 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00003093
Scott Michelfdc40a02009-02-17 22:15:04 +00003094 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003095 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003096 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3097 // For floating-point precision of 12:
3098 //
3099 // LogOfMantissa =
3100 // -1.7417939f +
3101 // (2.8212026f +
3102 // (-1.4699568f +
3103 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3104 //
3105 // error 0.000061011436, which is 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003106 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003107 getF32Constant(DAG, 0xbd67b6d6));
Owen Anderson825b72b2009-08-11 20:47:22 +00003108 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003109 getF32Constant(DAG, 0x3ee4f4b8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003110 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3111 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003112 getF32Constant(DAG, 0x3fbc278b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003113 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3114 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003115 getF32Constant(DAG, 0x40348e95));
Owen Anderson825b72b2009-08-11 20:47:22 +00003116 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3117 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003118 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00003119
Scott Michelfdc40a02009-02-17 22:15:04 +00003120 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003121 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003122 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3123 // For floating-point precision of 18:
3124 //
3125 // LogOfMantissa =
3126 // -2.1072184f +
3127 // (4.2372794f +
3128 // (-3.7029485f +
3129 // (2.2781945f +
3130 // (-0.87823314f +
3131 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3132 //
3133 // error 0.0000023660568, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003134 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003135 getF32Constant(DAG, 0xbc91e5ac));
Owen Anderson825b72b2009-08-11 20:47:22 +00003136 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003137 getF32Constant(DAG, 0x3e4350aa));
Owen Anderson825b72b2009-08-11 20:47:22 +00003138 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3139 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003140 getF32Constant(DAG, 0x3f60d3e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003141 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3142 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003143 getF32Constant(DAG, 0x4011cdf0));
Owen Anderson825b72b2009-08-11 20:47:22 +00003144 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3145 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003146 getF32Constant(DAG, 0x406cfd1c));
Owen Anderson825b72b2009-08-11 20:47:22 +00003147 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3148 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003149 getF32Constant(DAG, 0x408797cb));
Owen Anderson825b72b2009-08-11 20:47:22 +00003150 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3151 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003152 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003153
Scott Michelfdc40a02009-02-17 22:15:04 +00003154 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003155 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003156 }
3157 } else {
3158 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003159 result = DAG.getNode(ISD::FLOG, dl,
Bill Wendling39150252008-09-09 20:39:27 +00003160 getValue(I.getOperand(1)).getValueType(),
3161 getValue(I.getOperand(1)));
3162 }
3163
Dale Johannesen59e577f2008-09-05 18:38:42 +00003164 setValue(&I, result);
3165}
3166
Bill Wendling3eb59402008-09-09 00:28:24 +00003167/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3168/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003169void
Dan Gohman2048b852009-11-23 18:04:58 +00003170SelectionDAGBuilder::visitLog2(CallInst &I) {
Dale Johannesen59e577f2008-09-05 18:38:42 +00003171 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003172 DebugLoc dl = getCurDebugLoc();
Bill Wendling3eb59402008-09-09 00:28:24 +00003173
Owen Anderson825b72b2009-08-11 20:47:22 +00003174 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003175 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3176 SDValue Op = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003177 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003178
Bill Wendling39150252008-09-09 20:39:27 +00003179 // Get the exponent.
Bill Wendling856ff412009-12-22 00:12:37 +00003180 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
3181
Bill Wendling3eb59402008-09-09 00:28:24 +00003182 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003183 // exponent of 1.
Bill Wendling856ff412009-12-22 00:12:37 +00003184 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003185
Bill Wendling3eb59402008-09-09 00:28:24 +00003186 // Different possible minimax approximations of significand in
3187 // floating-point for various degrees of accuracy over [1,2].
3188 if (LimitFloatPrecision <= 6) {
3189 // For floating-point precision of 6:
3190 //
3191 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3192 //
3193 // error 0.0049451742, which is more than 7 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003194 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003195 getF32Constant(DAG, 0xbeb08fe0));
Owen Anderson825b72b2009-08-11 20:47:22 +00003196 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003197 getF32Constant(DAG, 0x40019463));
Owen Anderson825b72b2009-08-11 20:47:22 +00003198 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3199 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003200 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003201
Scott Michelfdc40a02009-02-17 22:15:04 +00003202 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003203 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003204 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3205 // For floating-point precision of 12:
3206 //
3207 // Log2ofMantissa =
3208 // -2.51285454f +
3209 // (4.07009056f +
3210 // (-2.12067489f +
3211 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003212 //
Bill Wendling3eb59402008-09-09 00:28:24 +00003213 // error 0.0000876136000, which is better than 13 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003214 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003215 getF32Constant(DAG, 0xbda7262e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003216 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003217 getF32Constant(DAG, 0x3f25280b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003218 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3219 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003220 getF32Constant(DAG, 0x4007b923));
Owen Anderson825b72b2009-08-11 20:47:22 +00003221 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3222 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003223 getF32Constant(DAG, 0x40823e2f));
Owen Anderson825b72b2009-08-11 20:47:22 +00003224 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3225 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003226 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003227
Scott Michelfdc40a02009-02-17 22:15:04 +00003228 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003229 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003230 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3231 // For floating-point precision of 18:
3232 //
3233 // Log2ofMantissa =
3234 // -3.0400495f +
3235 // (6.1129976f +
3236 // (-5.3420409f +
3237 // (3.2865683f +
3238 // (-1.2669343f +
3239 // (0.27515199f -
3240 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3241 //
3242 // error 0.0000018516, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003243 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003244 getF32Constant(DAG, 0xbcd2769e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003245 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003246 getF32Constant(DAG, 0x3e8ce0b9));
Owen Anderson825b72b2009-08-11 20:47:22 +00003247 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3248 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003249 getF32Constant(DAG, 0x3fa22ae7));
Owen Anderson825b72b2009-08-11 20:47:22 +00003250 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3251 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003252 getF32Constant(DAG, 0x40525723));
Owen Anderson825b72b2009-08-11 20:47:22 +00003253 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3254 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003255 getF32Constant(DAG, 0x40aaf200));
Owen Anderson825b72b2009-08-11 20:47:22 +00003256 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3257 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003258 getF32Constant(DAG, 0x40c39dad));
Owen Anderson825b72b2009-08-11 20:47:22 +00003259 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3260 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003261 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003262
Scott Michelfdc40a02009-02-17 22:15:04 +00003263 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003264 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003265 }
Dale Johannesen853244f2008-09-05 23:49:37 +00003266 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003267 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003268 result = DAG.getNode(ISD::FLOG2, dl,
Dale Johannesen853244f2008-09-05 23:49:37 +00003269 getValue(I.getOperand(1)).getValueType(),
3270 getValue(I.getOperand(1)));
3271 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003272
Dale Johannesen59e577f2008-09-05 18:38:42 +00003273 setValue(&I, result);
3274}
3275
Bill Wendling3eb59402008-09-09 00:28:24 +00003276/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3277/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003278void
Dan Gohman2048b852009-11-23 18:04:58 +00003279SelectionDAGBuilder::visitLog10(CallInst &I) {
Dale Johannesen59e577f2008-09-05 18:38:42 +00003280 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003281 DebugLoc dl = getCurDebugLoc();
Bill Wendling181b6272008-10-19 20:34:04 +00003282
Owen Anderson825b72b2009-08-11 20:47:22 +00003283 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003284 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3285 SDValue Op = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003286 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003287
Bill Wendling39150252008-09-09 20:39:27 +00003288 // Scale the exponent by log10(2) [0.30102999f].
Bill Wendling856ff412009-12-22 00:12:37 +00003289 SDValue Exp = GetExponent(DAG, Op1, TLI, dl, SDNodeOrder);
Owen Anderson825b72b2009-08-11 20:47:22 +00003290 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003291 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003292
3293 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003294 // exponent of 1.
Bill Wendling856ff412009-12-22 00:12:37 +00003295 SDValue X = GetSignificand(DAG, Op1, dl, SDNodeOrder);
Bill Wendling3eb59402008-09-09 00:28:24 +00003296
3297 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003298 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003299 //
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003300 // Log10ofMantissa =
3301 // -0.50419619f +
3302 // (0.60948995f - 0.10380950f * x) * x;
3303 //
3304 // error 0.0014886165, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003305 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003306 getF32Constant(DAG, 0xbdd49a13));
Owen Anderson825b72b2009-08-11 20:47:22 +00003307 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003308 getF32Constant(DAG, 0x3f1c0789));
Owen Anderson825b72b2009-08-11 20:47:22 +00003309 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3310 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003311 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003312
Scott Michelfdc40a02009-02-17 22:15:04 +00003313 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003314 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003315 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3316 // For floating-point precision of 12:
3317 //
3318 // Log10ofMantissa =
3319 // -0.64831180f +
3320 // (0.91751397f +
3321 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3322 //
3323 // error 0.00019228036, which is better than 12 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003324 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003325 getF32Constant(DAG, 0x3d431f31));
Owen Anderson825b72b2009-08-11 20:47:22 +00003326 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003327 getF32Constant(DAG, 0x3ea21fb2));
Owen Anderson825b72b2009-08-11 20:47:22 +00003328 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3329 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003330 getF32Constant(DAG, 0x3f6ae232));
Owen Anderson825b72b2009-08-11 20:47:22 +00003331 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3332 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003333 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00003334
Scott Michelfdc40a02009-02-17 22:15:04 +00003335 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003336 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003337 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003338 // For floating-point precision of 18:
3339 //
3340 // Log10ofMantissa =
3341 // -0.84299375f +
3342 // (1.5327582f +
3343 // (-1.0688956f +
3344 // (0.49102474f +
3345 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3346 //
3347 // error 0.0000037995730, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003348 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003349 getF32Constant(DAG, 0x3c5d51ce));
Owen Anderson825b72b2009-08-11 20:47:22 +00003350 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003351 getF32Constant(DAG, 0x3e00685a));
Owen Anderson825b72b2009-08-11 20:47:22 +00003352 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3353 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003354 getF32Constant(DAG, 0x3efb6798));
Owen Anderson825b72b2009-08-11 20:47:22 +00003355 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3356 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003357 getF32Constant(DAG, 0x3f88d192));
Owen Anderson825b72b2009-08-11 20:47:22 +00003358 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3359 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003360 getF32Constant(DAG, 0x3fc4316c));
Owen Anderson825b72b2009-08-11 20:47:22 +00003361 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3362 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003363 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003364
Scott Michelfdc40a02009-02-17 22:15:04 +00003365 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003366 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003367 }
Dale Johannesen852680a2008-09-05 21:27:19 +00003368 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003369 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003370 result = DAG.getNode(ISD::FLOG10, dl,
Dale Johannesen852680a2008-09-05 21:27:19 +00003371 getValue(I.getOperand(1)).getValueType(),
3372 getValue(I.getOperand(1)));
3373 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003374
Dale Johannesen59e577f2008-09-05 18:38:42 +00003375 setValue(&I, result);
3376}
3377
Bill Wendlinge10c8142008-09-09 22:39:21 +00003378/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3379/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003380void
Dan Gohman2048b852009-11-23 18:04:58 +00003381SelectionDAGBuilder::visitExp2(CallInst &I) {
Dale Johannesen601d3c02008-09-05 01:48:15 +00003382 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003383 DebugLoc dl = getCurDebugLoc();
Bill Wendlinge10c8142008-09-09 22:39:21 +00003384
Owen Anderson825b72b2009-08-11 20:47:22 +00003385 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00003386 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3387 SDValue Op = getValue(I.getOperand(1));
3388
Owen Anderson825b72b2009-08-11 20:47:22 +00003389 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003390
3391 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00003392 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3393 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003394
3395 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00003396 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003397 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003398
3399 if (LimitFloatPrecision <= 6) {
3400 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003401 //
Bill Wendlinge10c8142008-09-09 22:39:21 +00003402 // TwoToFractionalPartOfX =
3403 // 0.997535578f +
3404 // (0.735607626f + 0.252464424f * x) * x;
3405 //
3406 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003407 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003408 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00003409 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003410 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003411 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3412 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003413 getF32Constant(DAG, 0x3f7f5e7e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003414 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003415 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003416 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003417
Scott Michelfdc40a02009-02-17 22:15:04 +00003418 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003419 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003420 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3421 // For floating-point precision of 12:
3422 //
3423 // TwoToFractionalPartOfX =
3424 // 0.999892986f +
3425 // (0.696457318f +
3426 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3427 //
3428 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003429 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003430 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003431 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003432 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003433 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3434 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003435 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00003436 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3437 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003438 getF32Constant(DAG, 0x3f7ff8fd));
Owen Anderson825b72b2009-08-11 20:47:22 +00003439 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003440 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003441 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003442
Scott Michelfdc40a02009-02-17 22:15:04 +00003443 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003444 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003445 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3446 // For floating-point precision of 18:
3447 //
3448 // TwoToFractionalPartOfX =
3449 // 0.999999982f +
3450 // (0.693148872f +
3451 // (0.240227044f +
3452 // (0.554906021e-1f +
3453 // (0.961591928e-2f +
3454 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3455 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003456 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003457 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003458 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003459 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003460 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3461 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003462 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003463 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3464 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003465 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003466 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3467 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003468 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003469 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3470 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003471 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003472 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3473 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003474 getF32Constant(DAG, 0x3f800000));
Owen Anderson825b72b2009-08-11 20:47:22 +00003475 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003476 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003477 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003478
Scott Michelfdc40a02009-02-17 22:15:04 +00003479 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003480 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003481 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00003482 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003483 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003484 result = DAG.getNode(ISD::FEXP2, dl,
Dale Johannesen601d3c02008-09-05 01:48:15 +00003485 getValue(I.getOperand(1)).getValueType(),
3486 getValue(I.getOperand(1)));
3487 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00003488
Dale Johannesen601d3c02008-09-05 01:48:15 +00003489 setValue(&I, result);
3490}
3491
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003492/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3493/// limited-precision mode with x == 10.0f.
3494void
Dan Gohman2048b852009-11-23 18:04:58 +00003495SelectionDAGBuilder::visitPow(CallInst &I) {
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003496 SDValue result;
3497 Value *Val = I.getOperand(1);
Dale Johannesen66978ee2009-01-31 02:22:37 +00003498 DebugLoc dl = getCurDebugLoc();
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003499 bool IsExp10 = false;
3500
Owen Anderson825b72b2009-08-11 20:47:22 +00003501 if (getValue(Val).getValueType() == MVT::f32 &&
3502 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003503 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3504 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3505 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3506 APFloat Ten(10.0f);
3507 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3508 }
3509 }
3510 }
3511
3512 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3513 SDValue Op = getValue(I.getOperand(2));
3514
3515 // Put the exponent in the right bit position for later addition to the
3516 // final result:
3517 //
3518 // #define LOG2OF10 3.3219281f
3519 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
Owen Anderson825b72b2009-08-11 20:47:22 +00003520 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003521 getF32Constant(DAG, 0x40549a78));
Owen Anderson825b72b2009-08-11 20:47:22 +00003522 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003523
3524 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00003525 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3526 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003527
3528 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00003529 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003530 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003531
3532 if (LimitFloatPrecision <= 6) {
3533 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003534 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003535 // twoToFractionalPartOfX =
3536 // 0.997535578f +
3537 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003538 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003539 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003540 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003541 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00003542 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003543 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003544 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3545 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003546 getF32Constant(DAG, 0x3f7f5e7e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003547 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003548 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003549 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003550
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003551 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003552 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003553 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3554 // For floating-point precision of 12:
3555 //
3556 // TwoToFractionalPartOfX =
3557 // 0.999892986f +
3558 // (0.696457318f +
3559 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3560 //
3561 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003562 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003563 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003564 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003565 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003566 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3567 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003568 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00003569 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3570 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003571 getF32Constant(DAG, 0x3f7ff8fd));
Owen Anderson825b72b2009-08-11 20:47:22 +00003572 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003573 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003574 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003575
Scott Michelfdc40a02009-02-17 22:15:04 +00003576 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003577 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003578 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3579 // For floating-point precision of 18:
3580 //
3581 // TwoToFractionalPartOfX =
3582 // 0.999999982f +
3583 // (0.693148872f +
3584 // (0.240227044f +
3585 // (0.554906021e-1f +
3586 // (0.961591928e-2f +
3587 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3588 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003589 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003590 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003591 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003592 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003593 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3594 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003595 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003596 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3597 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003598 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003599 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3600 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003601 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003602 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3603 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003604 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003605 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3606 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003607 getF32Constant(DAG, 0x3f800000));
Owen Anderson825b72b2009-08-11 20:47:22 +00003608 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003609 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003610 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003611
Scott Michelfdc40a02009-02-17 22:15:04 +00003612 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003613 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003614 }
3615 } else {
3616 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003617 result = DAG.getNode(ISD::FPOW, dl,
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003618 getValue(I.getOperand(1)).getValueType(),
3619 getValue(I.getOperand(1)),
3620 getValue(I.getOperand(2)));
3621 }
3622
3623 setValue(&I, result);
3624}
3625
Chris Lattnerf031e8a2010-01-01 03:32:16 +00003626
3627/// ExpandPowI - Expand a llvm.powi intrinsic.
3628static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS,
3629 SelectionDAG &DAG) {
3630 // If RHS is a constant, we can expand this out to a multiplication tree,
3631 // otherwise we end up lowering to a call to __powidf2 (for example). When
3632 // optimizing for size, we only want to do this if the expansion would produce
3633 // a small number of multiplies, otherwise we do the full expansion.
3634 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3635 // Get the exponent as a positive value.
3636 unsigned Val = RHSC->getSExtValue();
3637 if ((int)Val < 0) Val = -Val;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003638
Chris Lattnerf031e8a2010-01-01 03:32:16 +00003639 // powi(x, 0) -> 1.0
3640 if (Val == 0)
3641 return DAG.getConstantFP(1.0, LHS.getValueType());
3642
3643 Function *F = DAG.getMachineFunction().getFunction();
3644 if (!F->hasFnAttr(Attribute::OptimizeForSize) ||
3645 // If optimizing for size, don't insert too many multiplies. This
3646 // inserts up to 5 multiplies.
3647 CountPopulation_32(Val)+Log2_32(Val) < 7) {
3648 // We use the simple binary decomposition method to generate the multiply
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003649 // sequence. There are more optimal ways to do this (for example,
Chris Lattnerf031e8a2010-01-01 03:32:16 +00003650 // powi(x,15) generates one more multiply than it should), but this has
3651 // the benefit of being both really simple and much better than a libcall.
3652 SDValue Res; // Logically starts equal to 1.0
3653 SDValue CurSquare = LHS;
3654 while (Val) {
Mikhail Glushenkovbfdfea82010-01-01 04:41:36 +00003655 if (Val & 1) {
Chris Lattnerf031e8a2010-01-01 03:32:16 +00003656 if (Res.getNode())
3657 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
3658 else
3659 Res = CurSquare; // 1.0*CurSquare.
Mikhail Glushenkovbfdfea82010-01-01 04:41:36 +00003660 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003661
Chris Lattnerf031e8a2010-01-01 03:32:16 +00003662 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
3663 CurSquare, CurSquare);
3664 Val >>= 1;
3665 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003666
Chris Lattnerf031e8a2010-01-01 03:32:16 +00003667 // If the original was negative, invert the result, producing 1/(x*x*x).
3668 if (RHSC->getSExtValue() < 0)
3669 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
3670 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
3671 return Res;
3672 }
3673 }
3674
3675 // Otherwise, expand to a libcall.
3676 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
3677}
3678
3679
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003680/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3681/// we want to emit this as a call to a named external function, return the name
3682/// otherwise lower it and return null.
3683const char *
Dan Gohman2048b852009-11-23 18:04:58 +00003684SelectionDAGBuilder::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00003685 DebugLoc dl = getCurDebugLoc();
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003686 SDValue Res;
3687
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003688 switch (Intrinsic) {
3689 default:
3690 // By default, turn this into a target intrinsic node.
3691 visitTargetIntrinsic(I, Intrinsic);
3692 return 0;
3693 case Intrinsic::vastart: visitVAStart(I); return 0;
3694 case Intrinsic::vaend: visitVAEnd(I); return 0;
3695 case Intrinsic::vacopy: visitVACopy(I); return 0;
3696 case Intrinsic::returnaddress:
Bill Wendling4533cac2010-01-28 21:51:40 +00003697 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
3698 getValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003699 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00003700 case Intrinsic::frameaddress:
Bill Wendling4533cac2010-01-28 21:51:40 +00003701 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
3702 getValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003703 return 0;
3704 case Intrinsic::setjmp:
3705 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003706 case Intrinsic::longjmp:
3707 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattner824b9582008-11-21 16:42:48 +00003708 case Intrinsic::memcpy: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003709 SDValue Op1 = getValue(I.getOperand(1));
3710 SDValue Op2 = getValue(I.getOperand(2));
3711 SDValue Op3 = getValue(I.getOperand(3));
3712 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Bill Wendling4533cac2010-01-28 21:51:40 +00003713 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
3714 I.getOperand(1), 0, I.getOperand(2), 0));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003715 return 0;
3716 }
Chris Lattner824b9582008-11-21 16:42:48 +00003717 case Intrinsic::memset: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003718 SDValue Op1 = getValue(I.getOperand(1));
3719 SDValue Op2 = getValue(I.getOperand(2));
3720 SDValue Op3 = getValue(I.getOperand(3));
3721 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Bill Wendling4533cac2010-01-28 21:51:40 +00003722 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
3723 I.getOperand(1), 0));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003724 return 0;
3725 }
Chris Lattner824b9582008-11-21 16:42:48 +00003726 case Intrinsic::memmove: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003727 SDValue Op1 = getValue(I.getOperand(1));
3728 SDValue Op2 = getValue(I.getOperand(2));
3729 SDValue Op3 = getValue(I.getOperand(3));
3730 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3731
3732 // If the source and destination are known to not be aliases, we can
3733 // lower memmove as memcpy.
3734 uint64_t Size = -1ULL;
3735 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003736 Size = C->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003737 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3738 AliasAnalysis::NoAlias) {
Bill Wendling4533cac2010-01-28 21:51:40 +00003739 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
3740 I.getOperand(1), 0, I.getOperand(2), 0));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003741 return 0;
3742 }
3743
Bill Wendling4533cac2010-01-28 21:51:40 +00003744 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
3745 I.getOperand(1), 0, I.getOperand(2), 0));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003746 return 0;
3747 }
Bill Wendling92c1e122009-02-13 02:16:35 +00003748 case Intrinsic::dbg_declare: {
Dale Johannesen904c2fa2010-02-01 19:54:53 +00003749 // FIXME: currently, we get here only if OptLevel != CodeGenOpt::None.
3750 // The real handling of this intrinsic is in FastISel.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003751 if (OptLevel != CodeGenOpt::None)
Devang Patel7e1e31f2009-07-02 22:43:26 +00003752 // FIXME: Variable debug info is not supported here.
3753 return 0;
Devang Patel24f20e02009-08-22 17:12:53 +00003754 DwarfWriter *DW = DAG.getDwarfWriter();
3755 if (!DW)
3756 return 0;
Devang Patel7e1e31f2009-07-02 22:43:26 +00003757 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Chris Lattnerbf0ca2b2009-12-29 09:32:19 +00003758 if (!DIDescriptor::ValidDebugInfo(DI.getVariable(), CodeGenOpt::None))
Devang Patel7e1e31f2009-07-02 22:43:26 +00003759 return 0;
3760
Devang Patelac1ceb32009-10-09 22:42:28 +00003761 MDNode *Variable = DI.getVariable();
Devang Patel24f20e02009-08-22 17:12:53 +00003762 Value *Address = DI.getAddress();
Dale Johannesen8ac38f22010-02-08 21:53:27 +00003763 if (!Address)
3764 return 0;
Devang Patel24f20e02009-08-22 17:12:53 +00003765 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
3766 Address = BCI->getOperand(0);
3767 AllocaInst *AI = dyn_cast<AllocaInst>(Address);
3768 // Don't handle byval struct arguments or VLAs, for example.
3769 if (!AI)
3770 return 0;
Devang Patelbd1d6a82009-09-05 00:34:14 +00003771 DenseMap<const AllocaInst*, int>::iterator SI =
3772 FuncInfo.StaticAllocaMap.find(AI);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003773 if (SI == FuncInfo.StaticAllocaMap.end())
Devang Patelbd1d6a82009-09-05 00:34:14 +00003774 return 0; // VLAs.
3775 int FI = SI->second;
Devang Patel70d75ca2009-11-12 19:02:56 +00003776
Chris Lattner3990b122009-12-28 23:41:32 +00003777 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo())
3778 if (MDNode *Dbg = DI.getMetadata("dbg"))
Chris Lattner0eb41982009-12-28 20:45:51 +00003779 MMI->setVariableDbgInfo(Variable, FI, Dbg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003780 return 0;
Bill Wendling92c1e122009-02-13 02:16:35 +00003781 }
Dale Johannesen904c2fa2010-02-01 19:54:53 +00003782 case Intrinsic::dbg_value: {
3783 // FIXME: currently, we get here only if OptLevel != CodeGenOpt::None.
3784 // The real handling of this intrinsic is in FastISel.
3785 if (OptLevel != CodeGenOpt::None)
3786 // FIXME: Variable debug info is not supported here.
3787 return 0;
3788 DwarfWriter *DW = DAG.getDwarfWriter();
3789 if (!DW)
3790 return 0;
3791 DbgValueInst &DI = cast<DbgValueInst>(I);
3792 if (!DIDescriptor::ValidDebugInfo(DI.getVariable(), CodeGenOpt::None))
3793 return 0;
3794
3795 MDNode *Variable = DI.getVariable();
3796 Value *V = DI.getValue();
3797 if (!V)
3798 return 0;
3799 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
3800 V = BCI->getOperand(0);
3801 AllocaInst *AI = dyn_cast<AllocaInst>(V);
3802 // Don't handle byval struct arguments or VLAs, for example.
3803 if (!AI)
3804 return 0;
3805 DenseMap<const AllocaInst*, int>::iterator SI =
3806 FuncInfo.StaticAllocaMap.find(AI);
3807 if (SI == FuncInfo.StaticAllocaMap.end())
3808 return 0; // VLAs.
3809 int FI = SI->second;
3810 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo())
3811 if (MDNode *Dbg = DI.getMetadata("dbg"))
3812 MMI->setVariableDbgInfo(Variable, FI, Dbg);
3813 return 0;
3814 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003815 case Intrinsic::eh_exception: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003816 // Insert the EXCEPTIONADDR instruction.
Duncan Sandsb0f1e172009-05-22 20:36:31 +00003817 assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!");
Owen Anderson825b72b2009-08-11 20:47:22 +00003818 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003819 SDValue Ops[1];
3820 Ops[0] = DAG.getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003821 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003822 setValue(&I, Op);
3823 DAG.setRoot(Op.getValue(1));
3824 return 0;
3825 }
3826
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00003827 case Intrinsic::eh_selector: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003828 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003829
Chris Lattner3a5815f2009-09-17 23:54:54 +00003830 if (CurMBB->isLandingPad())
3831 AddCatchInfo(I, MMI, CurMBB);
3832 else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003833#ifndef NDEBUG
Chris Lattner3a5815f2009-09-17 23:54:54 +00003834 FuncInfo.CatchInfoLost.insert(&I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003835#endif
Chris Lattner3a5815f2009-09-17 23:54:54 +00003836 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3837 unsigned Reg = TLI.getExceptionSelectorRegister();
3838 if (Reg) CurMBB->addLiveIn(Reg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003839 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003840
Chris Lattner3a5815f2009-09-17 23:54:54 +00003841 // Insert the EHSELECTION instruction.
3842 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3843 SDValue Ops[2];
3844 Ops[0] = getValue(I.getOperand(1));
3845 Ops[1] = getRoot();
3846 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
Chris Lattner3a5815f2009-09-17 23:54:54 +00003847 DAG.setRoot(Op.getValue(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00003848 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003849 return 0;
3850 }
3851
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00003852 case Intrinsic::eh_typeid_for: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003853 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003854
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003855 if (MMI) {
3856 // Find the type id for the given typeinfo.
3857 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003858 unsigned TypeID = MMI->getTypeIDFor(GV);
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003859 Res = DAG.getConstant(TypeID, MVT::i32);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003860 } else {
3861 // Return something different to eh_selector.
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003862 Res = DAG.getConstant(1, MVT::i32);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003863 }
3864
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003865 setValue(&I, Res);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003866 return 0;
3867 }
3868
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003869 case Intrinsic::eh_return_i32:
3870 case Intrinsic::eh_return_i64:
3871 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003872 MMI->setCallsEHReturn(true);
Bill Wendling4533cac2010-01-28 21:51:40 +00003873 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
3874 MVT::Other,
3875 getControlRoot(),
3876 getValue(I.getOperand(1)),
3877 getValue(I.getOperand(2))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003878 } else {
3879 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3880 }
3881
3882 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003883 case Intrinsic::eh_unwind_init:
3884 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3885 MMI->setCallsUnwindInit(true);
3886 }
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003887 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003888 case Intrinsic::eh_dwarf_cfa: {
Owen Andersone50ed302009-08-10 22:56:29 +00003889 EVT VT = getValue(I.getOperand(1)).getValueType();
Duncan Sands3a66a682009-10-13 21:04:12 +00003890 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), dl,
3891 TLI.getPointerTy());
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003892 SDValue Offset = DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003893 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003894 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003895 TLI.getPointerTy()),
3896 CfaArg);
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003897 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003898 TLI.getPointerTy(),
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003899 DAG.getConstant(0, TLI.getPointerTy()));
Bill Wendling4533cac2010-01-28 21:51:40 +00003900 setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
3901 FA, Offset));
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003902 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003903 }
Jim Grosbachca752c92010-01-28 01:45:32 +00003904 case Intrinsic::eh_sjlj_callsite: {
3905 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3906 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
3907 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
3908 assert(MMI->getCurrentCallSite() == 0 && "Overlapping call sites!");
3909
3910 MMI->setCurrentCallSite(CI->getZExtValue());
3911 return 0;
3912 }
3913
Mon P Wang77cdf302008-11-10 20:54:11 +00003914 case Intrinsic::convertff:
3915 case Intrinsic::convertfsi:
3916 case Intrinsic::convertfui:
3917 case Intrinsic::convertsif:
3918 case Intrinsic::convertuif:
3919 case Intrinsic::convertss:
3920 case Intrinsic::convertsu:
3921 case Intrinsic::convertus:
3922 case Intrinsic::convertuu: {
3923 ISD::CvtCode Code = ISD::CVT_INVALID;
3924 switch (Intrinsic) {
3925 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
3926 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
3927 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
3928 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
3929 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
3930 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
3931 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
3932 case Intrinsic::convertus: Code = ISD::CVT_US; break;
3933 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
3934 }
Owen Andersone50ed302009-08-10 22:56:29 +00003935 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003936 Value *Op1 = I.getOperand(1);
3937 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
3938 DAG.getValueType(DestVT),
3939 DAG.getValueType(getValue(Op1).getValueType()),
3940 getValue(I.getOperand(2)),
3941 getValue(I.getOperand(3)),
3942 Code);
3943 setValue(&I, Res);
Mon P Wang77cdf302008-11-10 20:54:11 +00003944 return 0;
3945 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003946 case Intrinsic::sqrt:
Bill Wendling4533cac2010-01-28 21:51:40 +00003947 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
3948 getValue(I.getOperand(1)).getValueType(),
3949 getValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003950 return 0;
3951 case Intrinsic::powi:
Bill Wendling4533cac2010-01-28 21:51:40 +00003952 setValue(&I, ExpandPowI(dl, getValue(I.getOperand(1)),
3953 getValue(I.getOperand(2)), DAG));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003954 return 0;
3955 case Intrinsic::sin:
Bill Wendling4533cac2010-01-28 21:51:40 +00003956 setValue(&I, DAG.getNode(ISD::FSIN, dl,
3957 getValue(I.getOperand(1)).getValueType(),
3958 getValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003959 return 0;
3960 case Intrinsic::cos:
Bill Wendling4533cac2010-01-28 21:51:40 +00003961 setValue(&I, DAG.getNode(ISD::FCOS, dl,
3962 getValue(I.getOperand(1)).getValueType(),
3963 getValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003964 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003965 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003966 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003967 return 0;
3968 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003969 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003970 return 0;
3971 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003972 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003973 return 0;
3974 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003975 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003976 return 0;
3977 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00003978 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003979 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003980 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003981 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003982 return 0;
3983 case Intrinsic::pcmarker: {
3984 SDValue Tmp = getValue(I.getOperand(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00003985 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003986 return 0;
3987 }
3988 case Intrinsic::readcyclecounter: {
3989 SDValue Op = getRoot();
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003990 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
3991 DAG.getVTList(MVT::i64, MVT::Other),
3992 &Op, 1);
3993 setValue(&I, Res);
3994 DAG.setRoot(Res.getValue(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003995 return 0;
3996 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003997 case Intrinsic::bswap:
Bill Wendling4533cac2010-01-28 21:51:40 +00003998 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
3999 getValue(I.getOperand(1)).getValueType(),
4000 getValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004001 return 0;
4002 case Intrinsic::cttz: {
4003 SDValue Arg = getValue(I.getOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00004004 EVT Ty = Arg.getValueType();
Bill Wendling4533cac2010-01-28 21:51:40 +00004005 setValue(&I, DAG.getNode(ISD::CTTZ, dl, Ty, Arg));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004006 return 0;
4007 }
4008 case Intrinsic::ctlz: {
4009 SDValue Arg = getValue(I.getOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00004010 EVT Ty = Arg.getValueType();
Bill Wendling4533cac2010-01-28 21:51:40 +00004011 setValue(&I, DAG.getNode(ISD::CTLZ, dl, Ty, Arg));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004012 return 0;
4013 }
4014 case Intrinsic::ctpop: {
4015 SDValue Arg = getValue(I.getOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00004016 EVT Ty = Arg.getValueType();
Bill Wendling4533cac2010-01-28 21:51:40 +00004017 setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004018 return 0;
4019 }
4020 case Intrinsic::stacksave: {
4021 SDValue Op = getRoot();
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004022 Res = DAG.getNode(ISD::STACKSAVE, dl,
4023 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4024 setValue(&I, Res);
4025 DAG.setRoot(Res.getValue(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004026 return 0;
4027 }
4028 case Intrinsic::stackrestore: {
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004029 Res = getValue(I.getOperand(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00004030 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004031 return 0;
4032 }
Bill Wendling57344502008-11-18 11:01:33 +00004033 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00004034 // Emit code into the DAG to store the stack guard onto the stack.
4035 MachineFunction &MF = DAG.getMachineFunction();
4036 MachineFrameInfo *MFI = MF.getFrameInfo();
Owen Andersone50ed302009-08-10 22:56:29 +00004037 EVT PtrTy = TLI.getPointerTy();
Bill Wendlingb2a42982008-11-06 02:29:10 +00004038
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004039 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4040 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
Bill Wendlingb2a42982008-11-06 02:29:10 +00004041
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004042 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00004043 MFI->setStackProtectorIndex(FI);
4044
4045 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4046
4047 // Store the stack protector onto the stack.
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004048 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4049 PseudoSourceValue::getFixedStack(FI),
4050 0, true);
4051 setValue(&I, Res);
4052 DAG.setRoot(Res);
Bill Wendlingb2a42982008-11-06 02:29:10 +00004053 return 0;
4054 }
Eric Christopher7b5e6172009-10-27 00:52:25 +00004055 case Intrinsic::objectsize: {
4056 // If we don't know by now, we're never going to know.
4057 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2));
4058
4059 assert(CI && "Non-constant type in __builtin_object_size?");
4060
Eric Christopher7e5d2ff2009-10-28 21:32:16 +00004061 SDValue Arg = getValue(I.getOperand(0));
4062 EVT Ty = Arg.getValueType();
4063
Eric Christopherd060b252009-12-23 02:51:48 +00004064 if (CI->getZExtValue() == 0)
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004065 Res = DAG.getConstant(-1ULL, Ty);
Eric Christopher7b5e6172009-10-27 00:52:25 +00004066 else
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004067 Res = DAG.getConstant(0, Ty);
4068
4069 setValue(&I, Res);
Eric Christopher7b5e6172009-10-27 00:52:25 +00004070 return 0;
4071 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004072 case Intrinsic::var_annotation:
4073 // Discard annotate attributes
4074 return 0;
4075
4076 case Intrinsic::init_trampoline: {
4077 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4078
4079 SDValue Ops[6];
4080 Ops[0] = getRoot();
4081 Ops[1] = getValue(I.getOperand(1));
4082 Ops[2] = getValue(I.getOperand(2));
4083 Ops[3] = getValue(I.getOperand(3));
4084 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4085 Ops[5] = DAG.getSrcValue(F);
4086
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004087 Res = DAG.getNode(ISD::TRAMPOLINE, dl,
4088 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4089 Ops, 6);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004090
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004091 setValue(&I, Res);
4092 DAG.setRoot(Res.getValue(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004093 return 0;
4094 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004095 case Intrinsic::gcroot:
4096 if (GFI) {
4097 Value *Alloca = I.getOperand(1);
4098 Constant *TypeMap = cast<Constant>(I.getOperand(2));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004099
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004100 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4101 GFI->addStackRoot(FI->getIndex(), TypeMap);
4102 }
4103 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004104 case Intrinsic::gcread:
4105 case Intrinsic::gcwrite:
Torok Edwinc23197a2009-07-14 16:55:14 +00004106 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004107 return 0;
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004108 case Intrinsic::flt_rounds:
Bill Wendling4533cac2010-01-28 21:51:40 +00004109 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004110 return 0;
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004111 case Intrinsic::trap:
Bill Wendling4533cac2010-01-28 21:51:40 +00004112 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004113 return 0;
Bill Wendlingef375462008-11-21 02:38:44 +00004114 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00004115 return implVisitAluOverflow(I, ISD::UADDO);
4116 case Intrinsic::sadd_with_overflow:
4117 return implVisitAluOverflow(I, ISD::SADDO);
4118 case Intrinsic::usub_with_overflow:
4119 return implVisitAluOverflow(I, ISD::USUBO);
4120 case Intrinsic::ssub_with_overflow:
4121 return implVisitAluOverflow(I, ISD::SSUBO);
4122 case Intrinsic::umul_with_overflow:
4123 return implVisitAluOverflow(I, ISD::UMULO);
4124 case Intrinsic::smul_with_overflow:
4125 return implVisitAluOverflow(I, ISD::SMULO);
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004126
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004127 case Intrinsic::prefetch: {
4128 SDValue Ops[4];
4129 Ops[0] = getRoot();
4130 Ops[1] = getValue(I.getOperand(1));
4131 Ops[2] = getValue(I.getOperand(2));
4132 Ops[3] = getValue(I.getOperand(3));
Bill Wendling4533cac2010-01-28 21:51:40 +00004133 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004134 return 0;
4135 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004136
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004137 case Intrinsic::memory_barrier: {
4138 SDValue Ops[6];
4139 Ops[0] = getRoot();
4140 for (int x = 1; x < 6; ++x)
4141 Ops[x] = getValue(I.getOperand(x));
4142
Bill Wendling4533cac2010-01-28 21:51:40 +00004143 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004144 return 0;
4145 }
4146 case Intrinsic::atomic_cmp_swap: {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004147 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004148 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00004149 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004150 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4151 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004152 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004153 getValue(I.getOperand(2)),
4154 getValue(I.getOperand(3)),
4155 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004156 setValue(&I, L);
4157 DAG.setRoot(L.getValue(1));
4158 return 0;
4159 }
4160 case Intrinsic::atomic_load_add:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004161 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004162 case Intrinsic::atomic_load_sub:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004163 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004164 case Intrinsic::atomic_load_or:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004165 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004166 case Intrinsic::atomic_load_xor:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004167 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004168 case Intrinsic::atomic_load_and:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004169 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004170 case Intrinsic::atomic_load_nand:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004171 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004172 case Intrinsic::atomic_load_max:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004173 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004174 case Intrinsic::atomic_load_min:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004175 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004176 case Intrinsic::atomic_load_umin:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004177 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004178 case Intrinsic::atomic_load_umax:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004179 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004180 case Intrinsic::atomic_swap:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004181 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Duncan Sandsf07c9492009-11-10 09:08:09 +00004182
4183 case Intrinsic::invariant_start:
4184 case Intrinsic::lifetime_start:
4185 // Discard region information.
Bill Wendling4533cac2010-01-28 21:51:40 +00004186 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
Duncan Sandsf07c9492009-11-10 09:08:09 +00004187 return 0;
4188 case Intrinsic::invariant_end:
4189 case Intrinsic::lifetime_end:
4190 // Discard region information.
4191 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004192 }
4193}
4194
Dan Gohman98ca4f22009-08-05 01:29:28 +00004195/// Test if the given instruction is in a position to be optimized
4196/// with a tail-call. This roughly means that it's in a block with
4197/// a return and there's nothing that needs to be scheduled
4198/// between it and the return.
4199///
4200/// This function only tests target-independent requirements.
Dan Gohman98ca4f22009-08-05 01:29:28 +00004201static bool
Evan Cheng86809cc2010-02-03 03:28:02 +00004202isInTailCallPosition(CallSite CS, Attributes CalleeRetAttr,
Dan Gohman98ca4f22009-08-05 01:29:28 +00004203 const TargetLowering &TLI) {
Evan Cheng86809cc2010-02-03 03:28:02 +00004204 const Instruction *I = CS.getInstruction();
Dan Gohman98ca4f22009-08-05 01:29:28 +00004205 const BasicBlock *ExitBB = I->getParent();
4206 const TerminatorInst *Term = ExitBB->getTerminator();
4207 const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
4208 const Function *F = ExitBB->getParent();
4209
Dan Gohmanc2e93b22010-02-08 20:34:14 +00004210 // The block must end in a return statement or unreachable.
4211 //
4212 // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
4213 // an unreachable, for now. The way tailcall optimization is currently
4214 // implemented means it will add an epilogue followed by a jump. That is
4215 // not profitable. Also, if the callee is a special function (e.g.
4216 // longjmp on x86), it can end up causing miscompilation that has not
4217 // been fully understood.
4218 if (!Ret &&
4219 (!GuaranteedTailCallOpt || !isa<UnreachableInst>(Term))) return false;
Dan Gohman98ca4f22009-08-05 01:29:28 +00004220
4221 // If I will have a chain, make sure no other instruction that will have a
4222 // chain interposes between I and the return.
4223 if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
4224 !I->isSafeToSpeculativelyExecute())
4225 for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
4226 --BBI) {
4227 if (&*BBI == I)
4228 break;
4229 if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
4230 !BBI->isSafeToSpeculativelyExecute())
4231 return false;
4232 }
4233
4234 // If the block ends with a void return or unreachable, it doesn't matter
4235 // what the call's return type is.
4236 if (!Ret || Ret->getNumOperands() == 0) return true;
4237
Dan Gohmaned9bab32009-11-14 02:06:30 +00004238 // If the return value is undef, it doesn't matter what the call's
4239 // return type is.
4240 if (isa<UndefValue>(Ret->getOperand(0))) return true;
4241
Dan Gohman98ca4f22009-08-05 01:29:28 +00004242 // Conservatively require the attributes of the call to match those of
Dan Gohman01205a82009-11-13 18:49:38 +00004243 // the return. Ignore noalias because it doesn't affect the call sequence.
4244 unsigned CallerRetAttr = F->getAttributes().getRetAttributes();
4245 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
Dan Gohman98ca4f22009-08-05 01:29:28 +00004246 return false;
4247
Evan Cheng6fdce652010-02-04 19:07:06 +00004248 // It's not safe to eliminate the sign / zero extension of the return value.
Evan Cheng446bc102010-02-04 02:45:02 +00004249 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
4250 return false;
4251
Dan Gohman98ca4f22009-08-05 01:29:28 +00004252 // Otherwise, make sure the unmodified return value of I is the return value.
4253 for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ;
4254 U = dyn_cast<Instruction>(U->getOperand(0))) {
4255 if (!U)
4256 return false;
4257 if (!U->hasOneUse())
4258 return false;
4259 if (U == I)
4260 break;
4261 // Check for a truly no-op truncate.
4262 if (isa<TruncInst>(U) &&
4263 TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType()))
4264 continue;
4265 // Check for a truly no-op bitcast.
4266 if (isa<BitCastInst>(U) &&
4267 (U->getOperand(0)->getType() == U->getType() ||
4268 (isa<PointerType>(U->getOperand(0)->getType()) &&
4269 isa<PointerType>(U->getType()))))
4270 continue;
4271 // Otherwise it's not a true no-op.
4272 return false;
4273 }
4274
4275 return true;
4276}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004277
Dan Gohman2048b852009-11-23 18:04:58 +00004278void SelectionDAGBuilder::LowerCallTo(CallSite CS, SDValue Callee,
4279 bool isTailCall,
4280 MachineBasicBlock *LandingPad) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004281 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4282 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004283 const Type *RetTy = FTy->getReturnType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004284 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4285 unsigned BeginLabel = 0, EndLabel = 0;
4286
4287 TargetLowering::ArgListTy Args;
4288 TargetLowering::ArgListEntry Entry;
4289 Args.reserve(CS.arg_size());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004290
4291 // Check whether the function can return without sret-demotion.
4292 SmallVector<EVT, 4> OutVTs;
4293 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
4294 SmallVector<uint64_t, 4> Offsets;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004295 getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
Bill Wendlinge80ae832009-12-22 00:50:32 +00004296 OutVTs, OutsFlags, TLI, &Offsets);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004297
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004298 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004299 FTy->isVarArg(), OutVTs, OutsFlags, DAG);
4300
4301 SDValue DemoteStackSlot;
4302
4303 if (!CanLowerReturn) {
4304 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
4305 FTy->getReturnType());
4306 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
4307 FTy->getReturnType());
4308 MachineFunction &MF = DAG.getMachineFunction();
David Greene3f2bf852009-11-12 20:49:22 +00004309 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004310 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
4311
4312 DemoteStackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4313 Entry.Node = DemoteStackSlot;
4314 Entry.Ty = StackSlotPtrType;
4315 Entry.isSExt = false;
4316 Entry.isZExt = false;
4317 Entry.isInReg = false;
4318 Entry.isSRet = true;
4319 Entry.isNest = false;
4320 Entry.isByVal = false;
4321 Entry.Alignment = Align;
4322 Args.push_back(Entry);
4323 RetTy = Type::getVoidTy(FTy->getContext());
4324 }
4325
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004326 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004327 i != e; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004328 SDValue ArgNode = getValue(*i);
4329 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4330
4331 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00004332 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4333 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4334 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4335 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4336 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4337 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004338 Entry.Alignment = CS.getParamAlignment(attrInd);
4339 Args.push_back(Entry);
4340 }
4341
4342 if (LandingPad && MMI) {
4343 // Insert a label before the invoke call to mark the try range. This can be
4344 // used to detect deletion of the invoke via the MachineModuleInfo.
4345 BeginLabel = MMI->NextLabelID();
Jim Grosbach1b747ad2009-08-11 00:09:57 +00004346
Jim Grosbachca752c92010-01-28 01:45:32 +00004347 // For SjLj, keep track of which landing pads go with which invokes
4348 // so as to maintain the ordering of pads in the LSDA.
4349 unsigned CallSiteIndex = MMI->getCurrentCallSite();
4350 if (CallSiteIndex) {
4351 MMI->setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
4352 // Now that the call site is handled, stop tracking it.
4353 MMI->setCurrentCallSite(0);
4354 }
4355
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004356 // Both PendingLoads and PendingExports must be flushed here;
4357 // this call might not return.
4358 (void)getRoot();
Bill Wendling0d580132009-12-23 01:28:19 +00004359 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4360 getControlRoot(), BeginLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004361 }
4362
Dan Gohman98ca4f22009-08-05 01:29:28 +00004363 // Check if target-independent constraints permit a tail call here.
4364 // Target-dependent constraints are checked within TLI.LowerCallTo.
4365 if (isTailCall &&
Evan Cheng86809cc2010-02-03 03:28:02 +00004366 !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI))
Dan Gohman98ca4f22009-08-05 01:29:28 +00004367 isTailCall = false;
4368
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004369 std::pair<SDValue,SDValue> Result =
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004370 TLI.LowerCallTo(getRoot(), RetTy,
Devang Patel05988662008-09-25 21:00:45 +00004371 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004372 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
Tilmann Scheller6b61cd12009-07-03 06:44:53 +00004373 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004374 CS.getCallingConv(),
Dan Gohman98ca4f22009-08-05 01:29:28 +00004375 isTailCall,
4376 !CS.getInstruction()->use_empty(),
Bill Wendling3ea3c242009-12-22 02:10:19 +00004377 Callee, Args, DAG, getCurDebugLoc(), SDNodeOrder);
Dan Gohman98ca4f22009-08-05 01:29:28 +00004378 assert((isTailCall || Result.second.getNode()) &&
4379 "Non-null chain expected with non-tail call!");
4380 assert((Result.second.getNode() || !Result.first.getNode()) &&
4381 "Null value expected with tail call!");
Bill Wendlinge80ae832009-12-22 00:50:32 +00004382 if (Result.first.getNode()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004383 setValue(CS.getInstruction(), Result.first);
Bill Wendlinge80ae832009-12-22 00:50:32 +00004384 } else if (!CanLowerReturn && Result.second.getNode()) {
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004385 // The instruction result is the result of loading from the
4386 // hidden sret parameter.
4387 SmallVector<EVT, 1> PVTs;
4388 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
4389
4390 ComputeValueVTs(TLI, PtrRetTy, PVTs);
4391 assert(PVTs.size() == 1 && "Pointers should fit in one register");
4392 EVT PtrVT = PVTs[0];
4393 unsigned NumValues = OutVTs.size();
4394 SmallVector<SDValue, 4> Values(NumValues);
4395 SmallVector<SDValue, 4> Chains(NumValues);
4396
4397 for (unsigned i = 0; i < NumValues; ++i) {
Bill Wendlinge80ae832009-12-22 00:50:32 +00004398 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
4399 DemoteStackSlot,
4400 DAG.getConstant(Offsets[i], PtrVT));
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004401 SDValue L = DAG.getLoad(OutVTs[i], getCurDebugLoc(), Result.second,
Bill Wendlinge80ae832009-12-22 00:50:32 +00004402 Add, NULL, Offsets[i], false, 1);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004403 Values[i] = L;
4404 Chains[i] = L.getValue(1);
4405 }
Bill Wendlinge80ae832009-12-22 00:50:32 +00004406
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004407 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
4408 MVT::Other, &Chains[0], NumValues);
4409 PendingLoads.push_back(Chain);
Kenneth Uildriks93ae4072010-01-16 23:37:33 +00004410
4411 // Collect the legal value parts into potentially illegal values
4412 // that correspond to the original function's return values.
4413 SmallVector<EVT, 4> RetTys;
4414 RetTy = FTy->getReturnType();
4415 ComputeValueVTs(TLI, RetTy, RetTys);
4416 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4417 SmallVector<SDValue, 4> ReturnValues;
4418 unsigned CurReg = 0;
4419 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4420 EVT VT = RetTys[I];
4421 EVT RegisterVT = TLI.getRegisterType(RetTy->getContext(), VT);
4422 unsigned NumRegs = TLI.getNumRegisters(RetTy->getContext(), VT);
4423
4424 SDValue ReturnValue =
4425 getCopyFromParts(DAG, getCurDebugLoc(), SDNodeOrder, &Values[CurReg], NumRegs,
4426 RegisterVT, VT, AssertOp);
4427 ReturnValues.push_back(ReturnValue);
Kenneth Uildriks93ae4072010-01-16 23:37:33 +00004428 CurReg += NumRegs;
4429 }
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004430
Bill Wendling4533cac2010-01-28 21:51:40 +00004431 setValue(CS.getInstruction(),
4432 DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
4433 DAG.getVTList(&RetTys[0], RetTys.size()),
4434 &ReturnValues[0], ReturnValues.size()));
Bill Wendlinge80ae832009-12-22 00:50:32 +00004435
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004436 }
Bill Wendlinge80ae832009-12-22 00:50:32 +00004437
4438 // As a special case, a null chain means that a tail call has been emitted and
4439 // the DAG root is already updated.
Bill Wendling4533cac2010-01-28 21:51:40 +00004440 if (Result.second.getNode())
Dan Gohman98ca4f22009-08-05 01:29:28 +00004441 DAG.setRoot(Result.second);
Bill Wendling4533cac2010-01-28 21:51:40 +00004442 else
Dan Gohman98ca4f22009-08-05 01:29:28 +00004443 HasTailCall = true;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004444
4445 if (LandingPad && MMI) {
4446 // Insert a label at the end of the invoke call to mark the try range. This
4447 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4448 EndLabel = MMI->NextLabelID();
Bill Wendling0d580132009-12-23 01:28:19 +00004449 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4450 getRoot(), EndLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004451
4452 // Inform MachineModuleInfo of range.
4453 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4454 }
4455}
4456
Chris Lattner8047d9a2009-12-24 00:37:38 +00004457/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
4458/// value is equal or not-equal to zero.
4459static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
4460 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
4461 UI != E; ++UI) {
4462 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
4463 if (IC->isEquality())
4464 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
4465 if (C->isNullValue())
4466 continue;
4467 // Unknown instruction.
4468 return false;
4469 }
4470 return true;
4471}
4472
Chris Lattner04b091a2009-12-24 01:07:17 +00004473static SDValue getMemCmpLoad(Value *PtrVal, MVT LoadVT, const Type *LoadTy,
Chris Lattner8047d9a2009-12-24 00:37:38 +00004474 SelectionDAGBuilder &Builder) {
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004475
Chris Lattner8047d9a2009-12-24 00:37:38 +00004476 // Check to see if this load can be trivially constant folded, e.g. if the
4477 // input is from a string literal.
4478 if (Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
4479 // Cast pointer to the type we really want to load.
4480 LoadInput = ConstantExpr::getBitCast(LoadInput,
4481 PointerType::getUnqual(LoadTy));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004482
Chris Lattner8047d9a2009-12-24 00:37:38 +00004483 if (Constant *LoadCst = ConstantFoldLoadFromConstPtr(LoadInput, Builder.TD))
4484 return Builder.getValue(LoadCst);
4485 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004486
Chris Lattner8047d9a2009-12-24 00:37:38 +00004487 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
4488 // still constant memory, the input chain can be the entry node.
4489 SDValue Root;
4490 bool ConstantMemory = false;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004491
Chris Lattner8047d9a2009-12-24 00:37:38 +00004492 // Do not serialize (non-volatile) loads of constant memory with anything.
4493 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
4494 Root = Builder.DAG.getEntryNode();
4495 ConstantMemory = true;
4496 } else {
4497 // Do not serialize non-volatile loads against each other.
4498 Root = Builder.DAG.getRoot();
4499 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004500
Chris Lattner8047d9a2009-12-24 00:37:38 +00004501 SDValue Ptr = Builder.getValue(PtrVal);
4502 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root,
4503 Ptr, PtrVal /*SrcValue*/, 0/*SVOffset*/,
4504 false /*volatile*/, 1 /* align=1 */);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004505
Chris Lattner8047d9a2009-12-24 00:37:38 +00004506 if (!ConstantMemory)
4507 Builder.PendingLoads.push_back(LoadVal.getValue(1));
4508 return LoadVal;
4509}
4510
4511
4512/// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
4513/// If so, return true and lower it, otherwise return false and it will be
4514/// lowered like a normal call.
4515bool SelectionDAGBuilder::visitMemCmpCall(CallInst &I) {
4516 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
4517 if (I.getNumOperands() != 4)
4518 return false;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004519
Chris Lattner8047d9a2009-12-24 00:37:38 +00004520 Value *LHS = I.getOperand(1), *RHS = I.getOperand(2);
4521 if (!isa<PointerType>(LHS->getType()) || !isa<PointerType>(RHS->getType()) ||
4522 !isa<IntegerType>(I.getOperand(3)->getType()) ||
4523 !isa<IntegerType>(I.getType()))
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004524 return false;
4525
Chris Lattner8047d9a2009-12-24 00:37:38 +00004526 ConstantInt *Size = dyn_cast<ConstantInt>(I.getOperand(3));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004527
Chris Lattner8047d9a2009-12-24 00:37:38 +00004528 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
4529 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
Chris Lattner04b091a2009-12-24 01:07:17 +00004530 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) {
4531 bool ActuallyDoIt = true;
4532 MVT LoadVT;
4533 const Type *LoadTy;
4534 switch (Size->getZExtValue()) {
4535 default:
4536 LoadVT = MVT::Other;
4537 LoadTy = 0;
4538 ActuallyDoIt = false;
4539 break;
4540 case 2:
4541 LoadVT = MVT::i16;
4542 LoadTy = Type::getInt16Ty(Size->getContext());
4543 break;
4544 case 4:
4545 LoadVT = MVT::i32;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004546 LoadTy = Type::getInt32Ty(Size->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00004547 break;
4548 case 8:
4549 LoadVT = MVT::i64;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004550 LoadTy = Type::getInt64Ty(Size->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00004551 break;
4552 /*
4553 case 16:
4554 LoadVT = MVT::v4i32;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004555 LoadTy = Type::getInt32Ty(Size->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00004556 LoadTy = VectorType::get(LoadTy, 4);
4557 break;
4558 */
4559 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004560
Chris Lattner04b091a2009-12-24 01:07:17 +00004561 // This turns into unaligned loads. We only do this if the target natively
4562 // supports the MVT we'll be loading or if it is small enough (<= 4) that
4563 // we'll only produce a small number of byte loads.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004564
Chris Lattner04b091a2009-12-24 01:07:17 +00004565 // Require that we can find a legal MVT, and only do this if the target
4566 // supports unaligned loads of that type. Expanding into byte loads would
4567 // bloat the code.
4568 if (ActuallyDoIt && Size->getZExtValue() > 4) {
4569 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
4570 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
4571 if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT))
4572 ActuallyDoIt = false;
4573 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004574
Chris Lattner04b091a2009-12-24 01:07:17 +00004575 if (ActuallyDoIt) {
4576 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
4577 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004578
Chris Lattner04b091a2009-12-24 01:07:17 +00004579 SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal,
4580 ISD::SETNE);
4581 EVT CallVT = TLI.getValueType(I.getType(), true);
4582 setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT));
4583 return true;
4584 }
Chris Lattner8047d9a2009-12-24 00:37:38 +00004585 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004586
4587
Chris Lattner8047d9a2009-12-24 00:37:38 +00004588 return false;
4589}
4590
4591
Dan Gohman2048b852009-11-23 18:04:58 +00004592void SelectionDAGBuilder::visitCall(CallInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004593 const char *RenameFn = 0;
4594 if (Function *F = I.getCalledFunction()) {
4595 if (F->isDeclaration()) {
Dale Johannesen49de9822009-02-05 01:49:45 +00004596 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4597 if (II) {
4598 if (unsigned IID = II->getIntrinsicID(F)) {
4599 RenameFn = visitIntrinsicCall(I, IID);
4600 if (!RenameFn)
4601 return;
4602 }
4603 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004604 if (unsigned IID = F->getIntrinsicID()) {
4605 RenameFn = visitIntrinsicCall(I, IID);
4606 if (!RenameFn)
4607 return;
4608 }
4609 }
4610
4611 // Check for well-known libc/libm calls. If the function is internal, it
4612 // can't be a library call.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004613 if (!F->hasLocalLinkage() && F->hasName()) {
4614 StringRef Name = F->getName();
4615 if (Name == "copysign" || Name == "copysignf") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004616 if (I.getNumOperands() == 3 && // Basic sanity checks.
4617 I.getOperand(1)->getType()->isFloatingPoint() &&
4618 I.getType() == I.getOperand(1)->getType() &&
4619 I.getType() == I.getOperand(2)->getType()) {
4620 SDValue LHS = getValue(I.getOperand(1));
4621 SDValue RHS = getValue(I.getOperand(2));
Bill Wendling0d580132009-12-23 01:28:19 +00004622 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
4623 LHS.getValueType(), LHS, RHS));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004624 return;
4625 }
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004626 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004627 if (I.getNumOperands() == 2 && // Basic sanity checks.
4628 I.getOperand(1)->getType()->isFloatingPoint() &&
4629 I.getType() == I.getOperand(1)->getType()) {
4630 SDValue Tmp = getValue(I.getOperand(1));
Bill Wendling0d580132009-12-23 01:28:19 +00004631 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
4632 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004633 return;
4634 }
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004635 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004636 if (I.getNumOperands() == 2 && // Basic sanity checks.
4637 I.getOperand(1)->getType()->isFloatingPoint() &&
Dale Johannesena45bfd32009-09-25 18:00:35 +00004638 I.getType() == I.getOperand(1)->getType() &&
4639 I.onlyReadsMemory()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004640 SDValue Tmp = getValue(I.getOperand(1));
Bill Wendling0d580132009-12-23 01:28:19 +00004641 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
4642 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004643 return;
4644 }
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004645 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004646 if (I.getNumOperands() == 2 && // Basic sanity checks.
4647 I.getOperand(1)->getType()->isFloatingPoint() &&
Dale Johannesena45bfd32009-09-25 18:00:35 +00004648 I.getType() == I.getOperand(1)->getType() &&
4649 I.onlyReadsMemory()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004650 SDValue Tmp = getValue(I.getOperand(1));
Bill Wendling0d580132009-12-23 01:28:19 +00004651 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
4652 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004653 return;
4654 }
Dale Johannesen52fb79b2009-09-25 17:23:22 +00004655 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
4656 if (I.getNumOperands() == 2 && // Basic sanity checks.
4657 I.getOperand(1)->getType()->isFloatingPoint() &&
Dale Johannesena45bfd32009-09-25 18:00:35 +00004658 I.getType() == I.getOperand(1)->getType() &&
4659 I.onlyReadsMemory()) {
Dale Johannesen52fb79b2009-09-25 17:23:22 +00004660 SDValue Tmp = getValue(I.getOperand(1));
Bill Wendling0d580132009-12-23 01:28:19 +00004661 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
4662 Tmp.getValueType(), Tmp));
Dale Johannesen52fb79b2009-09-25 17:23:22 +00004663 return;
4664 }
Chris Lattner8047d9a2009-12-24 00:37:38 +00004665 } else if (Name == "memcmp") {
4666 if (visitMemCmpCall(I))
4667 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004668 }
4669 }
4670 } else if (isa<InlineAsm>(I.getOperand(0))) {
4671 visitInlineAsm(&I);
4672 return;
4673 }
4674
4675 SDValue Callee;
4676 if (!RenameFn)
4677 Callee = getValue(I.getOperand(0));
4678 else
Bill Wendling056292f2008-09-16 21:48:12 +00004679 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004680
Bill Wendling0d580132009-12-23 01:28:19 +00004681 // Check if we can potentially perform a tail call. More detailed checking is
4682 // be done within LowerCallTo, after more information about the call is known.
Evan Cheng11e67932010-01-26 23:13:04 +00004683 LowerCallTo(&I, Callee, I.isTailCall());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004684}
4685
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004686/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004687/// this value and returns the result as a ValueVT value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004688/// Chain/Flag as the input and updates them for the output Chain/Flag.
4689/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004690SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
Bill Wendlingec72e322009-12-22 01:11:43 +00004691 unsigned Order, SDValue &Chain,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004692 SDValue *Flag) const {
4693 // Assemble the legal parts into the final values.
4694 SmallVector<SDValue, 4> Values(ValueVTs.size());
4695 SmallVector<SDValue, 8> Parts;
4696 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4697 // Copy the legal parts from the registers.
Owen Andersone50ed302009-08-10 22:56:29 +00004698 EVT ValueVT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00004699 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
Owen Andersone50ed302009-08-10 22:56:29 +00004700 EVT RegisterVT = RegVTs[Value];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004701
4702 Parts.resize(NumRegs);
4703 for (unsigned i = 0; i != NumRegs; ++i) {
4704 SDValue P;
Bill Wendlingec72e322009-12-22 01:11:43 +00004705 if (Flag == 0) {
Dale Johannesena04b7572009-02-03 23:04:43 +00004706 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
Bill Wendlingec72e322009-12-22 01:11:43 +00004707 } else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004708 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004709 *Flag = P.getValue(2);
4710 }
Bill Wendlingec72e322009-12-22 01:11:43 +00004711
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004712 Chain = P.getValue(1);
Bill Wendlingec72e322009-12-22 01:11:43 +00004713
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004714 // If the source register was virtual and if we know something about it,
4715 // add an assert node.
4716 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4717 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4718 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4719 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4720 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4721 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004722
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004723 unsigned RegSize = RegisterVT.getSizeInBits();
4724 unsigned NumSignBits = LOI.NumSignBits;
4725 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004726
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004727 // FIXME: We capture more information than the dag can represent. For
4728 // now, just use the tightest assertzext/assertsext possible.
4729 bool isSExt = true;
Owen Anderson825b72b2009-08-11 20:47:22 +00004730 EVT FromVT(MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004731 if (NumSignBits == RegSize)
Owen Anderson825b72b2009-08-11 20:47:22 +00004732 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004733 else if (NumZeroBits >= RegSize-1)
Owen Anderson825b72b2009-08-11 20:47:22 +00004734 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004735 else if (NumSignBits > RegSize-8)
Owen Anderson825b72b2009-08-11 20:47:22 +00004736 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
Dan Gohman07c26ee2009-03-31 01:38:29 +00004737 else if (NumZeroBits >= RegSize-8)
Owen Anderson825b72b2009-08-11 20:47:22 +00004738 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004739 else if (NumSignBits > RegSize-16)
Owen Anderson825b72b2009-08-11 20:47:22 +00004740 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
Dan Gohman07c26ee2009-03-31 01:38:29 +00004741 else if (NumZeroBits >= RegSize-16)
Owen Anderson825b72b2009-08-11 20:47:22 +00004742 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004743 else if (NumSignBits > RegSize-32)
Owen Anderson825b72b2009-08-11 20:47:22 +00004744 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
Dan Gohman07c26ee2009-03-31 01:38:29 +00004745 else if (NumZeroBits >= RegSize-32)
Owen Anderson825b72b2009-08-11 20:47:22 +00004746 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004747
Bill Wendling4533cac2010-01-28 21:51:40 +00004748 if (FromVT != MVT::Other)
Dale Johannesen66978ee2009-01-31 02:22:37 +00004749 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004750 RegisterVT, P, DAG.getValueType(FromVT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004751 }
4752 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004753
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004754 Parts[i] = P;
4755 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004756
Bill Wendling3ea3c242009-12-22 02:10:19 +00004757 Values[Value] = getCopyFromParts(DAG, dl, Order, Parts.begin(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00004758 NumRegs, RegisterVT, ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004759 Part += NumRegs;
4760 Parts.clear();
4761 }
4762
Bill Wendling4533cac2010-01-28 21:51:40 +00004763 return DAG.getNode(ISD::MERGE_VALUES, dl,
4764 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4765 &Values[0], ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004766}
4767
4768/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004769/// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004770/// Chain/Flag as the input and updates them for the output Chain/Flag.
4771/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004772void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Bill Wendlingec72e322009-12-22 01:11:43 +00004773 unsigned Order, SDValue &Chain,
4774 SDValue *Flag) const {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004775 // Get the list of the values's legal parts.
4776 unsigned NumRegs = Regs.size();
4777 SmallVector<SDValue, 8> Parts(NumRegs);
4778 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00004779 EVT ValueVT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00004780 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
Owen Andersone50ed302009-08-10 22:56:29 +00004781 EVT RegisterVT = RegVTs[Value];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004782
Bill Wendling3ea3c242009-12-22 02:10:19 +00004783 getCopyToParts(DAG, dl, Order,
4784 Val.getValue(Val.getResNo() + Value),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004785 &Parts[Part], NumParts, RegisterVT);
4786 Part += NumParts;
4787 }
4788
4789 // Copy the parts into the registers.
4790 SmallVector<SDValue, 8> Chains(NumRegs);
4791 for (unsigned i = 0; i != NumRegs; ++i) {
4792 SDValue Part;
Bill Wendlingec72e322009-12-22 01:11:43 +00004793 if (Flag == 0) {
Dale Johannesena04b7572009-02-03 23:04:43 +00004794 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
Bill Wendlingec72e322009-12-22 01:11:43 +00004795 } else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004796 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004797 *Flag = Part.getValue(1);
4798 }
Bill Wendlingec72e322009-12-22 01:11:43 +00004799
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004800 Chains[i] = Part.getValue(0);
4801 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004802
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004803 if (NumRegs == 1 || Flag)
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004804 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004805 // flagged to it. That is the CopyToReg nodes and the user are considered
4806 // a single scheduling unit. If we create a TokenFactor and return it as
4807 // chain, then the TokenFactor is both a predecessor (operand) of the
4808 // user as well as a successor (the TF operands are flagged to the user).
4809 // c1, f1 = CopyToReg
4810 // c2, f2 = CopyToReg
4811 // c3 = TokenFactor c1, c2
4812 // ...
4813 // = op c3, ..., f2
4814 Chain = Chains[NumRegs-1];
4815 else
Owen Anderson825b72b2009-08-11 20:47:22 +00004816 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004817}
4818
4819/// AddInlineAsmOperands - Add this value to the specified inlineasm node
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004820/// operand list. This adds the code marker and includes the number of
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004821/// values added into it.
Evan Cheng697cbbf2009-03-20 18:03:34 +00004822void RegsForValue::AddInlineAsmOperands(unsigned Code,
4823 bool HasMatching,unsigned MatchingIdx,
Bill Wendling651ad132009-12-22 01:25:10 +00004824 SelectionDAG &DAG, unsigned Order,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004825 std::vector<SDValue> &Ops) const {
Evan Cheng697cbbf2009-03-20 18:03:34 +00004826 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
4827 unsigned Flag = Code | (Regs.size() << 3);
4828 if (HasMatching)
4829 Flag |= 0x80000000 | (MatchingIdx << 16);
Dale Johannesen99499332009-12-23 07:32:51 +00004830 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
Bill Wendling651ad132009-12-22 01:25:10 +00004831 Ops.push_back(Res);
4832
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004833 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
Owen Anderson23b9b192009-08-12 00:36:31 +00004834 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
Owen Andersone50ed302009-08-10 22:56:29 +00004835 EVT RegisterVT = RegVTs[Value];
Chris Lattner58f15c42008-10-17 16:21:11 +00004836 for (unsigned i = 0; i != NumRegs; ++i) {
4837 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Bill Wendling4533cac2010-01-28 21:51:40 +00004838 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner58f15c42008-10-17 16:21:11 +00004839 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004840 }
4841}
4842
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004843/// isAllocatableRegister - If the specified register is safe to allocate,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004844/// i.e. it isn't a stack pointer or some other special register, return the
4845/// register class for the register. Otherwise, return null.
4846static const TargetRegisterClass *
4847isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4848 const TargetLowering &TLI,
4849 const TargetRegisterInfo *TRI) {
Owen Anderson825b72b2009-08-11 20:47:22 +00004850 EVT FoundVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004851 const TargetRegisterClass *FoundRC = 0;
4852 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4853 E = TRI->regclass_end(); RCI != E; ++RCI) {
Owen Anderson825b72b2009-08-11 20:47:22 +00004854 EVT ThisVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004855
4856 const TargetRegisterClass *RC = *RCI;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004857 // If none of the the value types for this register class are valid, we
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004858 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4859 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4860 I != E; ++I) {
4861 if (TLI.isTypeLegal(*I)) {
4862 // If we have already found this register in a different register class,
4863 // choose the one with the largest VT specified. For example, on
4864 // PowerPC, we favor f64 register classes over f32.
Owen Anderson825b72b2009-08-11 20:47:22 +00004865 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004866 ThisVT = *I;
4867 break;
4868 }
4869 }
4870 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004871
Owen Anderson825b72b2009-08-11 20:47:22 +00004872 if (ThisVT == MVT::Other) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004873
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004874 // NOTE: This isn't ideal. In particular, this might allocate the
4875 // frame pointer in functions that need it (due to them not being taken
4876 // out of allocation, because a variable sized allocation hasn't been seen
4877 // yet). This is a slight code pessimization, but should still work.
4878 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4879 E = RC->allocation_order_end(MF); I != E; ++I)
4880 if (*I == Reg) {
4881 // We found a matching register class. Keep looking at others in case
4882 // we find one with larger registers that this physreg is also in.
4883 FoundRC = RC;
4884 FoundVT = ThisVT;
4885 break;
4886 }
4887 }
4888 return FoundRC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004889}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004890
4891
4892namespace llvm {
4893/// AsmOperandInfo - This contains information for each constraint that we are
4894/// lowering.
Cedric Venetaff9c272009-02-14 16:06:42 +00004895class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
Daniel Dunbarc0c3b9a2008-09-10 04:16:29 +00004896 public TargetLowering::AsmOperandInfo {
Cedric Venetaff9c272009-02-14 16:06:42 +00004897public:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004898 /// CallOperand - If this is the result output operand or a clobber
4899 /// this is null, otherwise it is the incoming operand to the CallInst.
4900 /// This gets modified as the asm is processed.
4901 SDValue CallOperand;
4902
4903 /// AssignedRegs - If this is a register or register class operand, this
4904 /// contains the set of register corresponding to the operand.
4905 RegsForValue AssignedRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004906
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004907 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4908 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4909 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004910
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004911 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4912 /// busy in OutputRegs/InputRegs.
4913 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004914 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004915 std::set<unsigned> &InputRegs,
4916 const TargetRegisterInfo &TRI) const {
4917 if (isOutReg) {
4918 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4919 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4920 }
4921 if (isInReg) {
4922 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4923 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4924 }
4925 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004926
Owen Andersone50ed302009-08-10 22:56:29 +00004927 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
Chris Lattner81249c92008-10-17 17:05:25 +00004928 /// corresponds to. If there is no Value* for this operand, it returns
Owen Anderson825b72b2009-08-11 20:47:22 +00004929 /// MVT::Other.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004930 EVT getCallOperandValEVT(LLVMContext &Context,
Owen Anderson1d0be152009-08-13 21:58:54 +00004931 const TargetLowering &TLI,
Chris Lattner81249c92008-10-17 17:05:25 +00004932 const TargetData *TD) const {
Owen Anderson825b72b2009-08-11 20:47:22 +00004933 if (CallOperandVal == 0) return MVT::Other;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004934
Chris Lattner81249c92008-10-17 17:05:25 +00004935 if (isa<BasicBlock>(CallOperandVal))
4936 return TLI.getPointerTy();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004937
Chris Lattner81249c92008-10-17 17:05:25 +00004938 const llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004939
Chris Lattner81249c92008-10-17 17:05:25 +00004940 // If this is an indirect operand, the operand is a pointer to the
4941 // accessed type.
Bob Wilsone261b0c2009-12-22 18:34:19 +00004942 if (isIndirect) {
4943 const llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
4944 if (!PtrTy)
4945 llvm_report_error("Indirect operand for inline asm not a pointer!");
4946 OpTy = PtrTy->getElementType();
4947 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004948
Chris Lattner81249c92008-10-17 17:05:25 +00004949 // If OpTy is not a single value, it may be a struct/union that we
4950 // can tile with integers.
4951 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4952 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4953 switch (BitSize) {
4954 default: break;
4955 case 1:
4956 case 8:
4957 case 16:
4958 case 32:
4959 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00004960 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00004961 OpTy = IntegerType::get(Context, BitSize);
Chris Lattner81249c92008-10-17 17:05:25 +00004962 break;
4963 }
4964 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004965
Chris Lattner81249c92008-10-17 17:05:25 +00004966 return TLI.getValueType(OpTy, true);
4967 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004968
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004969private:
4970 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4971 /// specified set.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004972 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004973 const TargetRegisterInfo &TRI) {
4974 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4975 Regs.insert(Reg);
4976 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4977 for (; *Aliases; ++Aliases)
4978 Regs.insert(*Aliases);
4979 }
4980};
4981} // end llvm namespace.
4982
4983
4984/// GetRegistersForValue - Assign registers (virtual or physical) for the
4985/// specified operand. We prefer to assign virtual registers, to allow the
Bob Wilson266d9452009-12-17 05:07:36 +00004986/// register allocator to handle the assignment process. However, if the asm
4987/// uses features that we can't model on machineinstrs, we have SDISel do the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004988/// allocation. This produces generally horrible, but correct, code.
4989///
4990/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004991/// Input and OutputRegs are the set of already allocated physical registers.
4992///
Dan Gohman2048b852009-11-23 18:04:58 +00004993void SelectionDAGBuilder::
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004994GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004995 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004996 std::set<unsigned> &InputRegs) {
Dan Gohman0d24bfb2009-08-15 02:06:22 +00004997 LLVMContext &Context = FuncInfo.Fn->getContext();
Owen Anderson23b9b192009-08-12 00:36:31 +00004998
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004999 // Compute whether this value requires an input register, an output register,
5000 // or both.
5001 bool isOutReg = false;
5002 bool isInReg = false;
5003 switch (OpInfo.Type) {
5004 case InlineAsm::isOutput:
5005 isOutReg = true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005006
5007 // If there is an input constraint that matches this, we need to reserve
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005008 // the input register so no other inputs allocate to it.
Chris Lattner6bdcda32008-10-17 16:47:46 +00005009 isInReg = OpInfo.hasMatchingInput();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005010 break;
5011 case InlineAsm::isInput:
5012 isInReg = true;
5013 isOutReg = false;
5014 break;
5015 case InlineAsm::isClobber:
5016 isOutReg = true;
5017 isInReg = true;
5018 break;
5019 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005020
5021
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005022 MachineFunction &MF = DAG.getMachineFunction();
5023 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005024
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005025 // If this is a constraint for a single physreg, or a constraint for a
5026 // register class, find it.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005027 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005028 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5029 OpInfo.ConstraintVT);
5030
5031 unsigned NumRegs = 1;
Owen Anderson825b72b2009-08-11 20:47:22 +00005032 if (OpInfo.ConstraintVT != MVT::Other) {
Chris Lattner01426e12008-10-21 00:45:36 +00005033 // If this is a FP input in an integer register (or visa versa) insert a bit
5034 // cast of the input value. More generally, handle any case where the input
5035 // value disagrees with the register class we plan to stick this in.
5036 if (OpInfo.Type == InlineAsm::isInput &&
5037 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
Owen Andersone50ed302009-08-10 22:56:29 +00005038 // Try to convert to the first EVT that the reg class contains. If the
Chris Lattner01426e12008-10-21 00:45:36 +00005039 // types are identical size, use a bitcast to convert (e.g. two differing
5040 // vector types).
Owen Andersone50ed302009-08-10 22:56:29 +00005041 EVT RegVT = *PhysReg.second->vt_begin();
Chris Lattner01426e12008-10-21 00:45:36 +00005042 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005043 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005044 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00005045 OpInfo.ConstraintVT = RegVT;
5046 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5047 // If the input is a FP value and we want it in FP registers, do a
5048 // bitcast to the corresponding integer type. This turns an f64 value
5049 // into i64, which can be passed with two i32 values on a 32-bit
5050 // machine.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005051 RegVT = EVT::getIntegerVT(Context,
Owen Anderson23b9b192009-08-12 00:36:31 +00005052 OpInfo.ConstraintVT.getSizeInBits());
Dale Johannesen66978ee2009-01-31 02:22:37 +00005053 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005054 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00005055 OpInfo.ConstraintVT = RegVT;
5056 }
5057 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005058
Owen Anderson23b9b192009-08-12 00:36:31 +00005059 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00005060 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005061
Owen Andersone50ed302009-08-10 22:56:29 +00005062 EVT RegVT;
5063 EVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005064
5065 // If this is a constraint for a specific physical register, like {r17},
5066 // assign it now.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005067 if (unsigned AssignedReg = PhysReg.first) {
5068 const TargetRegisterClass *RC = PhysReg.second;
Owen Anderson825b72b2009-08-11 20:47:22 +00005069 if (OpInfo.ConstraintVT == MVT::Other)
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005070 ValueVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005071
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005072 // Get the actual register value type. This is important, because the user
5073 // may have asked for (e.g.) the AX register in i32 type. We need to
5074 // remember that AX is actually i16 to get the right extension.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005075 RegVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005076
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005077 // This is a explicit reference to a physical register.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005078 Regs.push_back(AssignedReg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005079
5080 // If this is an expanded reference, add the rest of the regs to Regs.
5081 if (NumRegs != 1) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005082 TargetRegisterClass::iterator I = RC->begin();
5083 for (; *I != AssignedReg; ++I)
5084 assert(I != RC->end() && "Didn't find reg!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005085
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005086 // Already added the first reg.
5087 --NumRegs; ++I;
5088 for (; NumRegs; --NumRegs, ++I) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005089 assert(I != RC->end() && "Ran out of registers to allocate!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005090 Regs.push_back(*I);
5091 }
5092 }
Bill Wendling651ad132009-12-22 01:25:10 +00005093
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005094 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5095 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5096 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5097 return;
5098 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005099
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005100 // Otherwise, if this was a reference to an LLVM register class, create vregs
5101 // for this reference.
Chris Lattnerb3b44842009-03-24 15:25:07 +00005102 if (const TargetRegisterClass *RC = PhysReg.second) {
5103 RegVT = *RC->vt_begin();
Owen Anderson825b72b2009-08-11 20:47:22 +00005104 if (OpInfo.ConstraintVT == MVT::Other)
Evan Chengfb112882009-03-23 08:01:15 +00005105 ValueVT = RegVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005106
Evan Chengfb112882009-03-23 08:01:15 +00005107 // Create the appropriate number of virtual registers.
5108 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5109 for (; NumRegs; --NumRegs)
Chris Lattnerb3b44842009-03-24 15:25:07 +00005110 Regs.push_back(RegInfo.createVirtualRegister(RC));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005111
Evan Chengfb112882009-03-23 08:01:15 +00005112 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5113 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005114 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005115
Chris Lattnerfc9d1612009-03-24 15:22:11 +00005116 // This is a reference to a register class that doesn't directly correspond
5117 // to an LLVM register class. Allocate NumRegs consecutive, available,
5118 // registers from the class.
5119 std::vector<unsigned> RegClassRegs
5120 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5121 OpInfo.ConstraintVT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005122
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005123 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5124 unsigned NumAllocated = 0;
5125 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5126 unsigned Reg = RegClassRegs[i];
5127 // See if this register is available.
5128 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5129 (isInReg && InputRegs.count(Reg))) { // Already used.
5130 // Make sure we find consecutive registers.
5131 NumAllocated = 0;
5132 continue;
5133 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005134
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005135 // Check to see if this register is allocatable (i.e. don't give out the
5136 // stack pointer).
Chris Lattnerfc9d1612009-03-24 15:22:11 +00005137 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5138 if (!RC) { // Couldn't allocate this register.
5139 // Reset NumAllocated to make sure we return consecutive registers.
5140 NumAllocated = 0;
5141 continue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005142 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005143
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005144 // Okay, this register is good, we can use it.
5145 ++NumAllocated;
5146
5147 // If we allocated enough consecutive registers, succeed.
5148 if (NumAllocated == NumRegs) {
5149 unsigned RegStart = (i-NumAllocated)+1;
5150 unsigned RegEnd = i+1;
5151 // Mark all of the allocated registers used.
5152 for (unsigned i = RegStart; i != RegEnd; ++i)
5153 Regs.push_back(RegClassRegs[i]);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005154
5155 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005156 OpInfo.ConstraintVT);
5157 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5158 return;
5159 }
5160 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005161
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005162 // Otherwise, we couldn't allocate enough registers for this.
5163}
5164
Evan Chengda43bcf2008-09-24 00:05:32 +00005165/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5166/// processed uses a memory 'm' constraint.
5167static bool
5168hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
Dan Gohmane9530ec2009-01-15 16:58:17 +00005169 const TargetLowering &TLI) {
Evan Chengda43bcf2008-09-24 00:05:32 +00005170 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5171 InlineAsm::ConstraintInfo &CI = CInfos[i];
5172 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5173 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5174 if (CType == TargetLowering::C_Memory)
5175 return true;
5176 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005177
Chris Lattner6c147292009-04-30 00:48:50 +00005178 // Indirect operand accesses access memory.
5179 if (CI.isIndirect)
5180 return true;
Evan Chengda43bcf2008-09-24 00:05:32 +00005181 }
5182
5183 return false;
5184}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005185
5186/// visitInlineAsm - Handle a call to an InlineAsm object.
5187///
Dan Gohman2048b852009-11-23 18:04:58 +00005188void SelectionDAGBuilder::visitInlineAsm(CallSite CS) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005189 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5190
5191 /// ConstraintOperands - Information about all of the constraints.
5192 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005193
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005194 std::set<unsigned> OutputRegs, InputRegs;
5195
5196 // Do a prepass over the constraints, canonicalizing them, and building up the
5197 // ConstraintOperands list.
5198 std::vector<InlineAsm::ConstraintInfo>
5199 ConstraintInfos = IA->ParseConstraints();
5200
Evan Chengda43bcf2008-09-24 00:05:32 +00005201 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005202
Chris Lattner6c147292009-04-30 00:48:50 +00005203 SDValue Chain, Flag;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005204
Chris Lattner6c147292009-04-30 00:48:50 +00005205 // We won't need to flush pending loads if this asm doesn't touch
5206 // memory and is nonvolatile.
5207 if (hasMemory || IA->hasSideEffects())
Dale Johannesen97d14fc2009-04-18 00:09:40 +00005208 Chain = getRoot();
Chris Lattner6c147292009-04-30 00:48:50 +00005209 else
5210 Chain = DAG.getRoot();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005211
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005212 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5213 unsigned ResNo = 0; // ResNo - The result number of the next output.
5214 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5215 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5216 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005217
Owen Anderson825b72b2009-08-11 20:47:22 +00005218 EVT OpVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005219
5220 // Compute the value type for each operand.
5221 switch (OpInfo.Type) {
5222 case InlineAsm::isOutput:
5223 // Indirect outputs just consume an argument.
5224 if (OpInfo.isIndirect) {
5225 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5226 break;
5227 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005228
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005229 // The return value of the call is this value. As such, there is no
5230 // corresponding argument.
Benjamin Kramerf0127052010-01-05 13:12:22 +00005231 assert(!CS.getType()->isVoidTy() &&
Owen Anderson1d0be152009-08-13 21:58:54 +00005232 "Bad inline asm!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005233 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5234 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5235 } else {
5236 assert(ResNo == 0 && "Asm only has one result!");
5237 OpVT = TLI.getValueType(CS.getType());
5238 }
5239 ++ResNo;
5240 break;
5241 case InlineAsm::isInput:
5242 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5243 break;
5244 case InlineAsm::isClobber:
5245 // Nothing to do.
5246 break;
5247 }
5248
5249 // If this is an input or an indirect output, process the call argument.
5250 // BasicBlocks are labels, currently appearing only in asm's.
5251 if (OpInfo.CallOperandVal) {
Dale Johannesen5339c552009-07-20 23:27:39 +00005252 // Strip bitcasts, if any. This mostly comes up for functions.
Dale Johannesen76711242009-08-06 22:45:51 +00005253 OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts();
5254
Chris Lattner81249c92008-10-17 17:05:25 +00005255 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005256 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00005257 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005258 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005259 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005260
Owen Anderson1d0be152009-08-13 21:58:54 +00005261 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005262 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005263
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005264 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005265 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005266
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005267 // Second pass over the constraints: compute which constraint option to use
5268 // and assign registers to constraints that want a specific physreg.
5269 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5270 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005271
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005272 // If this is an output operand with a matching input operand, look up the
Evan Cheng09dc9c02008-12-16 18:21:39 +00005273 // matching input. If their types mismatch, e.g. one is an integer, the
5274 // other is floating point, or their sizes are different, flag it as an
5275 // error.
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005276 if (OpInfo.hasMatchingInput()) {
5277 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5278 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Evan Cheng09dc9c02008-12-16 18:21:39 +00005279 if ((OpInfo.ConstraintVT.isInteger() !=
5280 Input.ConstraintVT.isInteger()) ||
5281 (OpInfo.ConstraintVT.getSizeInBits() !=
5282 Input.ConstraintVT.getSizeInBits())) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005283 llvm_report_error("Unsupported asm: input constraint"
Torok Edwin7d696d82009-07-11 13:10:19 +00005284 " with a matching output constraint of incompatible"
5285 " type!");
Evan Cheng09dc9c02008-12-16 18:21:39 +00005286 }
5287 Input.ConstraintVT = OpInfo.ConstraintVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005288 }
5289 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005290
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005291 // Compute the constraint code and ConstraintType to use.
Evan Chengda43bcf2008-09-24 00:05:32 +00005292 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005293
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005294 // If this is a memory input, and if the operand is not indirect, do what we
5295 // need to to provide an address for the memory input.
5296 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5297 !OpInfo.isIndirect) {
5298 assert(OpInfo.Type == InlineAsm::isInput &&
5299 "Can only indirectify direct input operands!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005300
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005301 // Memory operands really want the address of the value. If we don't have
5302 // an indirect input, put it in the constpool if we can, otherwise spill
5303 // it to a stack slot.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005304
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005305 // If the operand is a float, integer, or vector constant, spill to a
5306 // constant pool entry to get its address.
5307 Value *OpVal = OpInfo.CallOperandVal;
5308 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5309 isa<ConstantVector>(OpVal)) {
5310 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5311 TLI.getPointerTy());
5312 } else {
5313 // Otherwise, create a stack slot and emit a store to it before the
5314 // asm.
5315 const Type *Ty = OpVal->getType();
Duncan Sands777d2302009-05-09 07:06:46 +00005316 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005317 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5318 MachineFunction &MF = DAG.getMachineFunction();
David Greene3f2bf852009-11-12 20:49:22 +00005319 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005320 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Dale Johannesen66978ee2009-01-31 02:22:37 +00005321 Chain = DAG.getStore(Chain, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005322 OpInfo.CallOperand, StackSlot, NULL, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005323 OpInfo.CallOperand = StackSlot;
5324 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005325
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005326 // There is no longer a Value* corresponding to this operand.
5327 OpInfo.CallOperandVal = 0;
Bill Wendling651ad132009-12-22 01:25:10 +00005328
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005329 // It is now an indirect operand.
5330 OpInfo.isIndirect = true;
5331 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005332
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005333 // If this constraint is for a specific register, allocate it before
5334 // anything else.
5335 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005336 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005337 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005338
Bill Wendling651ad132009-12-22 01:25:10 +00005339 ConstraintInfos.clear();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005340
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005341 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00005342 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005343 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5344 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005345
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005346 // C_Register operands have already been allocated, Other/Memory don't need
5347 // to be.
5348 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005349 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005350 }
5351
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005352 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5353 std::vector<SDValue> AsmNodeOperands;
5354 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5355 AsmNodeOperands.push_back(
Dan Gohmanf2d7fb32010-01-04 21:00:54 +00005356 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
5357 TLI.getPointerTy()));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005358
5359
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005360 // Loop over all of the inputs, copying the operand values into the
5361 // appropriate registers and processing the output regs.
5362 RegsForValue RetValRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005363
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005364 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5365 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005366
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005367 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5368 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5369
5370 switch (OpInfo.Type) {
5371 case InlineAsm::isOutput: {
5372 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5373 OpInfo.ConstraintType != TargetLowering::C_Register) {
5374 // Memory output, or 'other' output (e.g. 'X' constraint).
5375 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5376
5377 // Add information to the INLINEASM node to know about this output.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005378 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5379 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005380 TLI.getPointerTy()));
5381 AsmNodeOperands.push_back(OpInfo.CallOperand);
5382 break;
5383 }
5384
5385 // Otherwise, this is a register or register class output.
5386
5387 // Copy the output from the appropriate register. Find a register that
5388 // we can use.
5389 if (OpInfo.AssignedRegs.Regs.empty()) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005390 llvm_report_error("Couldn't allocate output reg for"
Torok Edwin7d696d82009-07-11 13:10:19 +00005391 " constraint '" + OpInfo.ConstraintCode + "'!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005392 }
5393
5394 // If this is an indirect operand, store through the pointer after the
5395 // asm.
5396 if (OpInfo.isIndirect) {
5397 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5398 OpInfo.CallOperandVal));
5399 } else {
5400 // This is the result value of the call.
Benjamin Kramerf0127052010-01-05 13:12:22 +00005401 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005402 // Concatenate this output onto the outputs list.
5403 RetValRegs.append(OpInfo.AssignedRegs);
5404 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005405
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005406 // Add information to the INLINEASM node to know that this register is
5407 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00005408 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5409 6 /* EARLYCLOBBER REGDEF */ :
5410 2 /* REGDEF */ ,
Evan Chengfb112882009-03-23 08:01:15 +00005411 false,
5412 0,
Bill Wendling651ad132009-12-22 01:25:10 +00005413 DAG, SDNodeOrder,
5414 AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005415 break;
5416 }
5417 case InlineAsm::isInput: {
5418 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005419
Chris Lattner6bdcda32008-10-17 16:47:46 +00005420 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005421 // If this is required to match an output register we have already set,
5422 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00005423 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005424
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005425 // Scan until we find the definition we already emitted of this operand.
5426 // When we find it, create a RegsForValue operand.
5427 unsigned CurOp = 2; // The first operand.
5428 for (; OperandNo; --OperandNo) {
5429 // Advance to the next operand.
Evan Cheng697cbbf2009-03-20 18:03:34 +00005430 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005431 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005432 assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5433 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5434 (OpFlag & 7) == 4 /*MEM*/) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005435 "Skipped past definitions?");
Evan Cheng697cbbf2009-03-20 18:03:34 +00005436 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005437 }
5438
Evan Cheng697cbbf2009-03-20 18:03:34 +00005439 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005440 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005441 if ((OpFlag & 7) == 2 /*REGDEF*/
5442 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5443 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
Dan Gohman15480bd2009-06-15 22:32:41 +00005444 if (OpInfo.isIndirect) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005445 llvm_report_error("Don't know how to handle tied indirect "
Torok Edwin7d696d82009-07-11 13:10:19 +00005446 "register inputs yet!");
Dan Gohman15480bd2009-06-15 22:32:41 +00005447 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005448 RegsForValue MatchedRegs;
5449 MatchedRegs.TLI = &TLI;
5450 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
Owen Andersone50ed302009-08-10 22:56:29 +00005451 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
Evan Chengfb112882009-03-23 08:01:15 +00005452 MatchedRegs.RegVTs.push_back(RegVT);
5453 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005454 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
Evan Chengfb112882009-03-23 08:01:15 +00005455 i != e; ++i)
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005456 MatchedRegs.Regs.push_back
5457 (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005458
5459 // Use the produced MatchedRegs object to
Dale Johannesen66978ee2009-01-31 02:22:37 +00005460 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
Bill Wendlingec72e322009-12-22 01:11:43 +00005461 SDNodeOrder, Chain, &Flag);
Evan Chengfb112882009-03-23 08:01:15 +00005462 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5463 true, OpInfo.getMatchedOperand(),
Bill Wendling651ad132009-12-22 01:25:10 +00005464 DAG, SDNodeOrder, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005465 break;
5466 } else {
Evan Cheng697cbbf2009-03-20 18:03:34 +00005467 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5468 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5469 "Unexpected number of operands");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005470 // Add information to the INLINEASM node to know about this input.
Evan Chengfb112882009-03-23 08:01:15 +00005471 // See InlineAsm.h isUseOperandTiedToDef.
5472 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
Evan Cheng697cbbf2009-03-20 18:03:34 +00005473 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005474 TLI.getPointerTy()));
5475 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5476 break;
5477 }
5478 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005479
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005480 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005481 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005482 "Don't know how to handle indirect other inputs yet!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005483
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005484 std::vector<SDValue> Ops;
5485 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Chengda43bcf2008-09-24 00:05:32 +00005486 hasMemory, Ops, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005487 if (Ops.empty()) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005488 llvm_report_error("Invalid operand for inline asm"
Torok Edwin7d696d82009-07-11 13:10:19 +00005489 " constraint '" + OpInfo.ConstraintCode + "'!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005490 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005491
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005492 // Add information to the INLINEASM node to know about this input.
5493 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005494 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005495 TLI.getPointerTy()));
5496 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5497 break;
5498 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5499 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5500 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5501 "Memory operands expect pointer values");
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.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005504 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5505 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005506 TLI.getPointerTy()));
5507 AsmNodeOperands.push_back(InOperandVal);
5508 break;
5509 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005510
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005511 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5512 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5513 "Unknown constraint type!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005514 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005515 "Don't know how to handle indirect register inputs yet!");
5516
5517 // Copy the input into the appropriate registers.
Evan Chengaa765b82008-09-25 00:14:04 +00005518 if (OpInfo.AssignedRegs.Regs.empty()) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005519 llvm_report_error("Couldn't allocate input reg for"
Torok Edwin7d696d82009-07-11 13:10:19 +00005520 " constraint '"+ OpInfo.ConstraintCode +"'!");
Evan Chengaa765b82008-09-25 00:14:04 +00005521 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005522
Dale Johannesen66978ee2009-01-31 02:22:37 +00005523 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
Bill Wendlingec72e322009-12-22 01:11:43 +00005524 SDNodeOrder, Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005525
Evan Cheng697cbbf2009-03-20 18:03:34 +00005526 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
Bill Wendling651ad132009-12-22 01:25:10 +00005527 DAG, SDNodeOrder,
5528 AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005529 break;
5530 }
5531 case InlineAsm::isClobber: {
5532 // Add the clobbered value to the operand list, so that the register
5533 // allocator is aware that the physreg got clobbered.
5534 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesen91aac102008-09-17 21:13:11 +00005535 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
Bill Wendling651ad132009-12-22 01:25:10 +00005536 false, 0, DAG, SDNodeOrder,
5537 AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005538 break;
5539 }
5540 }
5541 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005542
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005543 // Finish up input operands.
5544 AsmNodeOperands[0] = Chain;
5545 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005546
Dale Johannesen66978ee2009-01-31 02:22:37 +00005547 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00005548 DAG.getVTList(MVT::Other, MVT::Flag),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005549 &AsmNodeOperands[0], AsmNodeOperands.size());
5550 Flag = Chain.getValue(1);
5551
5552 // If this asm returns a register value, copy the result from that register
5553 // and set it as the value of the call.
5554 if (!RetValRegs.Regs.empty()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00005555 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
Bill Wendlingec72e322009-12-22 01:11:43 +00005556 SDNodeOrder, Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005557
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005558 // FIXME: Why don't we do this for inline asms with MRVs?
5559 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
Owen Andersone50ed302009-08-10 22:56:29 +00005560 EVT ResultType = TLI.getValueType(CS.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005561
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005562 // If any of the results of the inline asm is a vector, it may have the
5563 // wrong width/num elts. This can happen for register classes that can
5564 // contain multiple different value types. The preg or vreg allocated may
5565 // not have the same VT as was expected. Convert it to the right type
5566 // with bit_convert.
5567 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005568 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005569 ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005570
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005571 } else if (ResultType != Val.getValueType() &&
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005572 ResultType.isInteger() && Val.getValueType().isInteger()) {
5573 // If a result value was tied to an input value, the computed result may
5574 // have a wider width than the expected result. Extract the relevant
5575 // portion.
Dale Johannesen66978ee2009-01-31 02:22:37 +00005576 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005577 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005578
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005579 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00005580 }
Dan Gohman95915732008-10-18 01:03:45 +00005581
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005582 setValue(CS.getInstruction(), Val);
Dale Johannesenec65a7d2009-04-14 00:56:56 +00005583 // Don't need to use this as a chain in this case.
5584 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5585 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005586 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005587
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005588 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005589
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005590 // Process indirect outputs, first output all of the flagged copies out of
5591 // physregs.
5592 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5593 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5594 Value *Ptr = IndirectStoresToEmit[i].second;
Dale Johannesen66978ee2009-01-31 02:22:37 +00005595 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
Bill Wendlingec72e322009-12-22 01:11:43 +00005596 SDNodeOrder, Chain, &Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005597 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6c147292009-04-30 00:48:50 +00005598
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005599 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005600
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005601 // Emit the non-flagged stores from the physregs.
5602 SmallVector<SDValue, 8> OutChains;
Bill Wendling651ad132009-12-22 01:25:10 +00005603 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
5604 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
5605 StoresToEmit[i].first,
5606 getValue(StoresToEmit[i].second),
5607 StoresToEmit[i].second, 0);
5608 OutChains.push_back(Val);
Bill Wendling651ad132009-12-22 01:25:10 +00005609 }
5610
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005611 if (!OutChains.empty())
Owen Anderson825b72b2009-08-11 20:47:22 +00005612 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005613 &OutChains[0], OutChains.size());
Bill Wendling651ad132009-12-22 01:25:10 +00005614
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005615 DAG.setRoot(Chain);
5616}
5617
Dan Gohman2048b852009-11-23 18:04:58 +00005618void SelectionDAGBuilder::visitVAStart(CallInst &I) {
Bill Wendlingc1d3c942009-12-23 00:44:51 +00005619 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
5620 MVT::Other, getRoot(),
5621 getValue(I.getOperand(1)),
5622 DAG.getSrcValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005623}
5624
Dan Gohman2048b852009-11-23 18:04:58 +00005625void SelectionDAGBuilder::visitVAArg(VAArgInst &I) {
Dale Johannesena04b7572009-02-03 23:04:43 +00005626 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5627 getRoot(), getValue(I.getOperand(0)),
5628 DAG.getSrcValue(I.getOperand(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005629 setValue(&I, V);
5630 DAG.setRoot(V.getValue(1));
5631}
5632
Dan Gohman2048b852009-11-23 18:04:58 +00005633void SelectionDAGBuilder::visitVAEnd(CallInst &I) {
Bill Wendlingc1d3c942009-12-23 00:44:51 +00005634 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
5635 MVT::Other, getRoot(),
5636 getValue(I.getOperand(1)),
5637 DAG.getSrcValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005638}
5639
Dan Gohman2048b852009-11-23 18:04:58 +00005640void SelectionDAGBuilder::visitVACopy(CallInst &I) {
Bill Wendlingc1d3c942009-12-23 00:44:51 +00005641 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
5642 MVT::Other, getRoot(),
5643 getValue(I.getOperand(1)),
5644 getValue(I.getOperand(2)),
5645 DAG.getSrcValue(I.getOperand(1)),
5646 DAG.getSrcValue(I.getOperand(2))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005647}
5648
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005649/// TargetLowering::LowerCallTo - This is the default LowerCallTo
Dan Gohman98ca4f22009-08-05 01:29:28 +00005650/// implementation, which just calls LowerCall.
5651/// FIXME: When all targets are
5652/// migrated to using LowerCall, this hook should be integrated into SDISel.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005653std::pair<SDValue, SDValue>
5654TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5655 bool RetSExt, bool RetZExt, bool isVarArg,
Tilmann Scheller6b61cd12009-07-03 06:44:53 +00005656 bool isInreg, unsigned NumFixedArgs,
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00005657 CallingConv::ID CallConv, bool isTailCall,
Dan Gohman98ca4f22009-08-05 01:29:28 +00005658 bool isReturnValueUsed,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005659 SDValue Callee,
Bill Wendling3ea3c242009-12-22 02:10:19 +00005660 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl,
5661 unsigned Order) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005662 // Handle all of the outgoing arguments.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005663 SmallVector<ISD::OutputArg, 32> Outs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005664 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Owen Andersone50ed302009-08-10 22:56:29 +00005665 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005666 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5667 for (unsigned Value = 0, NumValues = ValueVTs.size();
5668 Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00005669 EVT VT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00005670 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005671 SDValue Op = SDValue(Args[i].Node.getNode(),
5672 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005673 ISD::ArgFlagsTy Flags;
5674 unsigned OriginalAlignment =
5675 getTargetData()->getABITypeAlignment(ArgTy);
5676
5677 if (Args[i].isZExt)
5678 Flags.setZExt();
5679 if (Args[i].isSExt)
5680 Flags.setSExt();
5681 if (Args[i].isInReg)
5682 Flags.setInReg();
5683 if (Args[i].isSRet)
5684 Flags.setSRet();
5685 if (Args[i].isByVal) {
5686 Flags.setByVal();
5687 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5688 const Type *ElementTy = Ty->getElementType();
5689 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sands777d2302009-05-09 07:06:46 +00005690 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005691 // For ByVal, alignment should come from FE. BE will guess if this
5692 // info is not there but there are cases it cannot get right.
5693 if (Args[i].Alignment)
5694 FrameAlign = Args[i].Alignment;
5695 Flags.setByValAlign(FrameAlign);
5696 Flags.setByValSize(FrameSize);
5697 }
5698 if (Args[i].isNest)
5699 Flags.setNest();
5700 Flags.setOrigAlign(OriginalAlignment);
5701
Owen Anderson23b9b192009-08-12 00:36:31 +00005702 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
5703 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005704 SmallVector<SDValue, 4> Parts(NumParts);
5705 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5706
5707 if (Args[i].isSExt)
5708 ExtendKind = ISD::SIGN_EXTEND;
5709 else if (Args[i].isZExt)
5710 ExtendKind = ISD::ZERO_EXTEND;
5711
Bill Wendling3ea3c242009-12-22 02:10:19 +00005712 getCopyToParts(DAG, dl, Order, Op, &Parts[0], NumParts,
5713 PartVT, ExtendKind);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005714
Dan Gohman98ca4f22009-08-05 01:29:28 +00005715 for (unsigned j = 0; j != NumParts; ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005716 // if it isn't first piece, alignment must be 1
Dan Gohman98ca4f22009-08-05 01:29:28 +00005717 ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs);
5718 if (NumParts > 1 && j == 0)
5719 MyFlags.Flags.setSplit();
5720 else if (j != 0)
5721 MyFlags.Flags.setOrigAlign(1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005722
Dan Gohman98ca4f22009-08-05 01:29:28 +00005723 Outs.push_back(MyFlags);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005724 }
5725 }
5726 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005727
Dan Gohman98ca4f22009-08-05 01:29:28 +00005728 // Handle the incoming return values from the call.
5729 SmallVector<ISD::InputArg, 32> Ins;
Owen Andersone50ed302009-08-10 22:56:29 +00005730 SmallVector<EVT, 4> RetTys;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005731 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005732 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Owen Andersone50ed302009-08-10 22:56:29 +00005733 EVT VT = RetTys[I];
Owen Anderson23b9b192009-08-12 00:36:31 +00005734 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5735 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005736 for (unsigned i = 0; i != NumRegs; ++i) {
5737 ISD::InputArg MyFlags;
5738 MyFlags.VT = RegisterVT;
5739 MyFlags.Used = isReturnValueUsed;
5740 if (RetSExt)
5741 MyFlags.Flags.setSExt();
5742 if (RetZExt)
5743 MyFlags.Flags.setZExt();
5744 if (isInreg)
5745 MyFlags.Flags.setInReg();
5746 Ins.push_back(MyFlags);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005747 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005748 }
5749
Dan Gohman98ca4f22009-08-05 01:29:28 +00005750 SmallVector<SDValue, 4> InVals;
Evan Cheng022d9e12010-02-02 23:55:14 +00005751 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
Dan Gohman98ca4f22009-08-05 01:29:28 +00005752 Outs, Ins, dl, DAG, InVals);
Dan Gohman5e866062009-08-06 15:37:27 +00005753
5754 // Verify that the target's LowerCall behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +00005755 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00005756 "LowerCall didn't return a valid chain!");
5757 assert((!isTailCall || InVals.empty()) &&
5758 "LowerCall emitted a return value for a tail call!");
5759 assert((isTailCall || InVals.size() == Ins.size()) &&
5760 "LowerCall didn't emit the correct number of values!");
5761 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5762 assert(InVals[i].getNode() &&
5763 "LowerCall emitted a null value!");
5764 assert(Ins[i].VT == InVals[i].getValueType() &&
5765 "LowerCall emitted a value with the wrong type!");
5766 });
Dan Gohman98ca4f22009-08-05 01:29:28 +00005767
5768 // For a tail call, the return value is merely live-out and there aren't
5769 // any nodes in the DAG representing it. Return a special value to
5770 // indicate that a tail call has been emitted and no more Instructions
5771 // should be processed in the current block.
5772 if (isTailCall) {
5773 DAG.setRoot(Chain);
5774 return std::make_pair(SDValue(), SDValue());
5775 }
5776
5777 // Collect the legal value parts into potentially illegal values
5778 // that correspond to the original function's return values.
5779 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5780 if (RetSExt)
5781 AssertOp = ISD::AssertSext;
5782 else if (RetZExt)
5783 AssertOp = ISD::AssertZext;
5784 SmallVector<SDValue, 4> ReturnValues;
5785 unsigned CurReg = 0;
5786 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Owen Andersone50ed302009-08-10 22:56:29 +00005787 EVT VT = RetTys[I];
Owen Anderson23b9b192009-08-12 00:36:31 +00005788 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5789 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005790
Bill Wendling4533cac2010-01-28 21:51:40 +00005791 ReturnValues.push_back(getCopyFromParts(DAG, dl, Order, &InVals[CurReg],
5792 NumRegs, RegisterVT, VT,
5793 AssertOp));
Dan Gohman98ca4f22009-08-05 01:29:28 +00005794 CurReg += NumRegs;
5795 }
5796
5797 // For a function returning void, there is no return value. We can't create
5798 // such a node, so we just return a null return value in that case. In
5799 // that case, nothing will actualy look at the value.
5800 if (ReturnValues.empty())
5801 return std::make_pair(SDValue(), Chain);
5802
5803 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
5804 DAG.getVTList(&RetTys[0], RetTys.size()),
5805 &ReturnValues[0], ReturnValues.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005806 return std::make_pair(Res, Chain);
5807}
5808
Duncan Sands9fbc7e22009-01-21 09:00:29 +00005809void TargetLowering::LowerOperationWrapper(SDNode *N,
5810 SmallVectorImpl<SDValue> &Results,
5811 SelectionDAG &DAG) {
5812 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptabb326bb2009-01-21 04:48:39 +00005813 if (Res.getNode())
5814 Results.push_back(Res);
5815}
5816
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005817SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005818 llvm_unreachable("LowerOperation not implemented for this target!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005819 return SDValue();
5820}
5821
Dan Gohman2048b852009-11-23 18:04:58 +00005822void SelectionDAGBuilder::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005823 SDValue Op = getValue(V);
5824 assert((Op.getOpcode() != ISD::CopyFromReg ||
5825 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5826 "Copy from a reg to the same reg!");
5827 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5828
Owen Anderson23b9b192009-08-12 00:36:31 +00005829 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005830 SDValue Chain = DAG.getEntryNode();
Bill Wendlingec72e322009-12-22 01:11:43 +00005831 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), SDNodeOrder, Chain, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005832 PendingExports.push_back(Chain);
5833}
5834
5835#include "llvm/CodeGen/SelectionDAGISel.h"
5836
Dan Gohman8c2b5252009-10-30 01:27:03 +00005837void SelectionDAGISel::LowerArguments(BasicBlock *LLVMBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005838 // If this is the entry block, emit arguments.
5839 Function &F = *LLVMBB->getParent();
Dan Gohman2048b852009-11-23 18:04:58 +00005840 SelectionDAG &DAG = SDB->DAG;
Dan Gohman98ca4f22009-08-05 01:29:28 +00005841 SDValue OldRoot = DAG.getRoot();
Dan Gohman2048b852009-11-23 18:04:58 +00005842 DebugLoc dl = SDB->getCurDebugLoc();
Dan Gohman98ca4f22009-08-05 01:29:28 +00005843 const TargetData *TD = TLI.getTargetData();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005844 SmallVector<ISD::InputArg, 16> Ins;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005845
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +00005846 // Check whether the function can return without sret-demotion.
5847 SmallVector<EVT, 4> OutVTs;
5848 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005849 getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005850 OutVTs, OutsFlags, TLI);
5851 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
5852
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005853 FLI.CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(), F.isVarArg(),
Bill Wendling3ea3c242009-12-22 02:10:19 +00005854 OutVTs, OutsFlags, DAG);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005855 if (!FLI.CanLowerReturn) {
5856 // Put in an sret pointer parameter before all the other parameters.
5857 SmallVector<EVT, 1> ValueVTs;
5858 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5859
5860 // NOTE: Assuming that a pointer will never break down to more than one VT
5861 // or one register.
5862 ISD::ArgFlagsTy Flags;
5863 Flags.setSRet();
5864 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), ValueVTs[0]);
5865 ISD::InputArg RetArg(Flags, RegisterVT, true);
5866 Ins.push_back(RetArg);
5867 }
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +00005868
Dan Gohman98ca4f22009-08-05 01:29:28 +00005869 // Set up the incoming argument description vector.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005870 unsigned Idx = 1;
5871 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5872 I != E; ++I, ++Idx) {
Owen Andersone50ed302009-08-10 22:56:29 +00005873 SmallVector<EVT, 4> ValueVTs;
Dan Gohman98ca4f22009-08-05 01:29:28 +00005874 ComputeValueVTs(TLI, I->getType(), ValueVTs);
5875 bool isArgValueUsed = !I->use_empty();
5876 for (unsigned Value = 0, NumValues = ValueVTs.size();
5877 Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00005878 EVT VT = ValueVTs[Value];
Owen Anderson1d0be152009-08-13 21:58:54 +00005879 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Dan Gohman98ca4f22009-08-05 01:29:28 +00005880 ISD::ArgFlagsTy Flags;
5881 unsigned OriginalAlignment =
5882 TD->getABITypeAlignment(ArgTy);
5883
5884 if (F.paramHasAttr(Idx, Attribute::ZExt))
5885 Flags.setZExt();
5886 if (F.paramHasAttr(Idx, Attribute::SExt))
5887 Flags.setSExt();
5888 if (F.paramHasAttr(Idx, Attribute::InReg))
5889 Flags.setInReg();
5890 if (F.paramHasAttr(Idx, Attribute::StructRet))
5891 Flags.setSRet();
5892 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
5893 Flags.setByVal();
5894 const PointerType *Ty = cast<PointerType>(I->getType());
5895 const Type *ElementTy = Ty->getElementType();
5896 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
5897 unsigned FrameSize = TD->getTypeAllocSize(ElementTy);
5898 // For ByVal, alignment should be passed from FE. BE will guess if
5899 // this info is not there but there are cases it cannot get right.
5900 if (F.getParamAlignment(Idx))
5901 FrameAlign = F.getParamAlignment(Idx);
5902 Flags.setByValAlign(FrameAlign);
5903 Flags.setByValSize(FrameSize);
5904 }
5905 if (F.paramHasAttr(Idx, Attribute::Nest))
5906 Flags.setNest();
5907 Flags.setOrigAlign(OriginalAlignment);
5908
Owen Anderson23b9b192009-08-12 00:36:31 +00005909 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5910 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005911 for (unsigned i = 0; i != NumRegs; ++i) {
5912 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
5913 if (NumRegs > 1 && i == 0)
5914 MyFlags.Flags.setSplit();
5915 // if it isn't first piece, alignment must be 1
5916 else if (i > 0)
5917 MyFlags.Flags.setOrigAlign(1);
5918 Ins.push_back(MyFlags);
5919 }
5920 }
5921 }
5922
5923 // Call the target to set up the argument values.
5924 SmallVector<SDValue, 8> InVals;
5925 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
5926 F.isVarArg(), Ins,
5927 dl, DAG, InVals);
Dan Gohman5e866062009-08-06 15:37:27 +00005928
5929 // Verify that the target's LowerFormalArguments behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +00005930 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00005931 "LowerFormalArguments didn't return a valid chain!");
5932 assert(InVals.size() == Ins.size() &&
5933 "LowerFormalArguments didn't emit the correct number of values!");
Bill Wendling3ea58b62009-12-22 21:35:02 +00005934 DEBUG({
5935 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5936 assert(InVals[i].getNode() &&
5937 "LowerFormalArguments emitted a null value!");
5938 assert(Ins[i].VT == InVals[i].getValueType() &&
5939 "LowerFormalArguments emitted a value with the wrong type!");
5940 }
5941 });
Bill Wendling3ea3c242009-12-22 02:10:19 +00005942
Dan Gohman5e866062009-08-06 15:37:27 +00005943 // Update the DAG with the new chain value resulting from argument lowering.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005944 DAG.setRoot(NewRoot);
5945
5946 // Set up the argument values.
5947 unsigned i = 0;
5948 Idx = 1;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005949 if (!FLI.CanLowerReturn) {
5950 // Create a virtual register for the sret pointer, and put in a copy
5951 // from the sret argument into it.
5952 SmallVector<EVT, 1> ValueVTs;
5953 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5954 EVT VT = ValueVTs[0];
5955 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5956 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Bill Wendling3ea58b62009-12-22 21:35:02 +00005957 SDValue ArgValue = getCopyFromParts(DAG, dl, 0, &InVals[0], 1,
Bill Wendling3ea3c242009-12-22 02:10:19 +00005958 RegVT, VT, AssertOp);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005959
Dan Gohman2048b852009-11-23 18:04:58 +00005960 MachineFunction& MF = SDB->DAG.getMachineFunction();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005961 MachineRegisterInfo& RegInfo = MF.getRegInfo();
5962 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
5963 FLI.DemoteRegister = SRetReg;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005964 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(),
5965 SRetReg, ArgValue);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005966 DAG.setRoot(NewRoot);
Bill Wendling3ea3c242009-12-22 02:10:19 +00005967
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005968 // i indexes lowered arguments. Bump it past the hidden sret argument.
5969 // Idx indexes LLVM arguments. Don't touch it.
5970 ++i;
5971 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00005972
Dan Gohman98ca4f22009-08-05 01:29:28 +00005973 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5974 ++I, ++Idx) {
5975 SmallVector<SDValue, 4> ArgValues;
Owen Andersone50ed302009-08-10 22:56:29 +00005976 SmallVector<EVT, 4> ValueVTs;
Dan Gohman98ca4f22009-08-05 01:29:28 +00005977 ComputeValueVTs(TLI, I->getType(), ValueVTs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005978 unsigned NumValues = ValueVTs.size();
Dan Gohman98ca4f22009-08-05 01:29:28 +00005979 for (unsigned Value = 0; Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00005980 EVT VT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00005981 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5982 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005983
5984 if (!I->use_empty()) {
5985 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5986 if (F.paramHasAttr(Idx, Attribute::SExt))
5987 AssertOp = ISD::AssertSext;
5988 else if (F.paramHasAttr(Idx, Attribute::ZExt))
5989 AssertOp = ISD::AssertZext;
5990
Bill Wendling3ea58b62009-12-22 21:35:02 +00005991 ArgValues.push_back(getCopyFromParts(DAG, dl, 0, &InVals[i],
Bill Wendling3ea3c242009-12-22 02:10:19 +00005992 NumParts, PartVT, VT,
5993 AssertOp));
Dan Gohman98ca4f22009-08-05 01:29:28 +00005994 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00005995
Dan Gohman98ca4f22009-08-05 01:29:28 +00005996 i += NumParts;
5997 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00005998
Dan Gohman98ca4f22009-08-05 01:29:28 +00005999 if (!I->use_empty()) {
Bill Wendling3ea3c242009-12-22 02:10:19 +00006000 SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues,
6001 SDB->getCurDebugLoc());
6002 SDB->setValue(I, Res);
6003
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006004 // If this argument is live outside of the entry block, insert a copy from
6005 // whereever we got it to the vreg that other BB's will reference it as.
Dan Gohman2048b852009-11-23 18:04:58 +00006006 SDB->CopyToExportRegsIfNeeded(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006007 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006008 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006009
Dan Gohman98ca4f22009-08-05 01:29:28 +00006010 assert(i == InVals.size() && "Argument register count mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006011
6012 // Finally, if the target has anything special to do, allow it to do so.
6013 // FIXME: this should insert code into the DAG!
Dan Gohman2048b852009-11-23 18:04:58 +00006014 EmitFunctionEntryCode(F, SDB->DAG.getMachineFunction());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006015}
6016
6017/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
6018/// ensure constants are generated when needed. Remember the virtual registers
6019/// that need to be added to the Machine PHI nodes as input. We cannot just
6020/// directly add them, because expansion might result in multiple MBB's for one
6021/// BB. As such, the start of the BB might correspond to a different MBB than
6022/// the end.
6023///
6024void
6025SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
6026 TerminatorInst *TI = LLVMBB->getTerminator();
6027
6028 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6029
6030 // Check successor nodes' PHI nodes that expect a constant to be available
6031 // from this block.
6032 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6033 BasicBlock *SuccBB = TI->getSuccessor(succ);
6034 if (!isa<PHINode>(SuccBB->begin())) continue;
6035 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006036
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006037 // If this terminator has multiple identical successors (common for
6038 // switches), only handle each succ once.
6039 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006040
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006041 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6042 PHINode *PN;
6043
6044 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6045 // nodes and Machine PHI nodes, but the incoming operands have not been
6046 // emitted yet.
6047 for (BasicBlock::iterator I = SuccBB->begin();
6048 (PN = dyn_cast<PHINode>(I)); ++I) {
6049 // Ignore dead phi's.
6050 if (PN->use_empty()) continue;
6051
6052 unsigned Reg;
6053 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6054
6055 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
Dan Gohman2048b852009-11-23 18:04:58 +00006056 unsigned &RegOut = SDB->ConstantsOut[C];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006057 if (RegOut == 0) {
6058 RegOut = FuncInfo->CreateRegForValue(C);
Dan Gohman2048b852009-11-23 18:04:58 +00006059 SDB->CopyValueToVirtualRegister(C, RegOut);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006060 }
6061 Reg = RegOut;
6062 } else {
6063 Reg = FuncInfo->ValueMap[PHIOp];
6064 if (Reg == 0) {
6065 assert(isa<AllocaInst>(PHIOp) &&
6066 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
6067 "Didn't codegen value into a register!??");
6068 Reg = FuncInfo->CreateRegForValue(PHIOp);
Dan Gohman2048b852009-11-23 18:04:58 +00006069 SDB->CopyValueToVirtualRegister(PHIOp, Reg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006070 }
6071 }
6072
6073 // Remember that this register needs to added to the machine PHI node as
6074 // the input for this MBB.
Owen Andersone50ed302009-08-10 22:56:29 +00006075 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006076 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6077 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
Owen Andersone50ed302009-08-10 22:56:29 +00006078 EVT VT = ValueVTs[vti];
Owen Anderson23b9b192009-08-12 00:36:31 +00006079 unsigned NumRegisters = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006080 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Dan Gohman2048b852009-11-23 18:04:58 +00006081 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006082 Reg += NumRegisters;
6083 }
6084 }
6085 }
Dan Gohman2048b852009-11-23 18:04:58 +00006086 SDB->ConstantsOut.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006087}
6088
Dan Gohman3df24e62008-09-03 23:12:08 +00006089/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
6090/// supports legal types, and it emits MachineInstrs directly instead of
6091/// creating SelectionDAG nodes.
6092///
6093bool
6094SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
6095 FastISel *F) {
6096 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006097
Dan Gohman3df24e62008-09-03 23:12:08 +00006098 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
Dan Gohman2048b852009-11-23 18:04:58 +00006099 unsigned OrigNumPHINodesToUpdate = SDB->PHINodesToUpdate.size();
Dan Gohman3df24e62008-09-03 23:12:08 +00006100
6101 // Check successor nodes' PHI nodes that expect a constant to be available
6102 // from this block.
6103 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6104 BasicBlock *SuccBB = TI->getSuccessor(succ);
6105 if (!isa<PHINode>(SuccBB->begin())) continue;
6106 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006107
Dan Gohman3df24e62008-09-03 23:12:08 +00006108 // If this terminator has multiple identical successors (common for
6109 // switches), only handle each succ once.
6110 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006111
Dan Gohman3df24e62008-09-03 23:12:08 +00006112 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6113 PHINode *PN;
6114
6115 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6116 // nodes and Machine PHI nodes, but the incoming operands have not been
6117 // emitted yet.
6118 for (BasicBlock::iterator I = SuccBB->begin();
6119 (PN = dyn_cast<PHINode>(I)); ++I) {
6120 // Ignore dead phi's.
6121 if (PN->use_empty()) continue;
6122
6123 // Only handle legal types. Two interesting things to note here. First,
6124 // by bailing out early, we may leave behind some dead instructions,
6125 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
6126 // own moves. Second, this check is necessary becuase FastISel doesn't
6127 // use CreateRegForValue to create registers, so it always creates
6128 // exactly one register for each non-void instruction.
Owen Andersone50ed302009-08-10 22:56:29 +00006129 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
Owen Anderson825b72b2009-08-11 20:47:22 +00006130 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
6131 // Promote MVT::i1.
6132 if (VT == MVT::i1)
Owen Anderson23b9b192009-08-12 00:36:31 +00006133 VT = TLI.getTypeToTransformTo(*CurDAG->getContext(), VT);
Dan Gohman74321ab2008-09-10 21:01:31 +00006134 else {
Dan Gohman2048b852009-11-23 18:04:58 +00006135 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
Dan Gohman74321ab2008-09-10 21:01:31 +00006136 return false;
6137 }
Dan Gohman3df24e62008-09-03 23:12:08 +00006138 }
6139
6140 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6141
6142 unsigned Reg = F->getRegForValue(PHIOp);
6143 if (Reg == 0) {
Dan Gohman2048b852009-11-23 18:04:58 +00006144 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
Dan Gohman3df24e62008-09-03 23:12:08 +00006145 return false;
6146 }
Dan Gohman2048b852009-11-23 18:04:58 +00006147 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
Dan Gohman3df24e62008-09-03 23:12:08 +00006148 }
6149 }
6150
6151 return true;
6152}