blob: 4bbb3dea92f46dd0915bfd2063fbbdc92d3895e2 [file] [log] [blame]
Dan Gohman2048b852009-11-23 18:04:58 +00001//===-- SelectionDAGBuilder.cpp - Selection-DAG building ------------------===//
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements routines for translating from LLVM IR into SelectionDAG IR.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
Devang Patel00190342010-03-15 19:15:44 +000015#include "SDNodeDbgValue.h"
Dan Gohman2048b852009-11-23 18:04:58 +000016#include "SelectionDAGBuilder.h"
Dan Gohman6277eb22009-11-23 17:16:22 +000017#include "FunctionLoweringInfo.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000018#include "llvm/ADT/BitVector.h"
Dan Gohman5b229802008-09-04 20:49:27 +000019#include "llvm/ADT/SmallSet.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000020#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner8047d9a2009-12-24 00:37:38 +000021#include "llvm/Analysis/ConstantFolding.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000022#include "llvm/Constants.h"
23#include "llvm/CallingConv.h"
24#include "llvm/DerivedTypes.h"
25#include "llvm/Function.h"
26#include "llvm/GlobalVariable.h"
27#include "llvm/InlineAsm.h"
28#include "llvm/Instructions.h"
29#include "llvm/Intrinsics.h"
30#include "llvm/IntrinsicInst.h"
Bill Wendlingb2a42982008-11-06 02:29:10 +000031#include "llvm/Module.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000032#include "llvm/CodeGen/FastISel.h"
33#include "llvm/CodeGen/GCStrategy.h"
34#include "llvm/CodeGen/GCMetadata.h"
35#include "llvm/CodeGen/MachineFunction.h"
36#include "llvm/CodeGen/MachineFrameInfo.h"
37#include "llvm/CodeGen/MachineInstrBuilder.h"
38#include "llvm/CodeGen/MachineJumpTableInfo.h"
39#include "llvm/CodeGen/MachineModuleInfo.h"
40#include "llvm/CodeGen/MachineRegisterInfo.h"
Bill Wendlingb2a42982008-11-06 02:29:10 +000041#include "llvm/CodeGen/PseudoSourceValue.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000042#include "llvm/CodeGen/SelectionDAG.h"
Devang Patel83489bb2009-01-13 00:35:13 +000043#include "llvm/Analysis/DebugInfo.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000044#include "llvm/Target/TargetRegisterInfo.h"
45#include "llvm/Target/TargetData.h"
46#include "llvm/Target/TargetFrameInfo.h"
47#include "llvm/Target/TargetInstrInfo.h"
Dale Johannesen49de9822009-02-05 01:49:45 +000048#include "llvm/Target/TargetIntrinsicInfo.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000049#include "llvm/Target/TargetLowering.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000050#include "llvm/Target/TargetOptions.h"
51#include "llvm/Support/Compiler.h"
Mikhail Glushenkov2388a582009-01-16 07:02:28 +000052#include "llvm/Support/CommandLine.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000053#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000054#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000055#include "llvm/Support/MathExtras.h"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +000056#include "llvm/Support/raw_ostream.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000057#include <algorithm>
58using namespace llvm;
59
Dale Johannesen601d3c02008-09-05 01:48:15 +000060/// LimitFloatPrecision - Generate low-precision inline sequences for
61/// some float libcalls (6, 8 or 12 bits).
62static unsigned LimitFloatPrecision;
63
64static cl::opt<unsigned, true>
65LimitFPPrecision("limit-float-precision",
66 cl::desc("Generate low-precision inline sequences "
67 "for some float libcalls"),
68 cl::location(LimitFloatPrecision),
69 cl::init(0));
70
Dan Gohmanf9bd4502009-11-23 17:46:23 +000071namespace {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000072 /// RegsForValue - This struct represents the registers (physical or virtual)
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +000073 /// that a particular set of values is assigned, and the type information
74 /// about the value. The most common situation is to represent one value at a
75 /// time, but struct or array values are handled element-wise as multiple
76 /// values. The splitting of aggregates is performed recursively, so that we
77 /// never have aggregate-typed registers. The values at this point do not
78 /// necessarily have legal types, so each value may require one or more
79 /// registers of some legal type.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000080 ///
Dan Gohmanf9bd4502009-11-23 17:46:23 +000081 struct RegsForValue {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000082 /// TLI - The TargetLowering object.
83 ///
84 const TargetLowering *TLI;
85
86 /// ValueVTs - The value types of the values, which may not be legal, and
87 /// may need be promoted or synthesized from one or more registers.
88 ///
Owen Andersone50ed302009-08-10 22:56:29 +000089 SmallVector<EVT, 4> ValueVTs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +000090
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000091 /// RegVTs - The value types of the registers. This is the same size as
92 /// ValueVTs and it records, for each value, what the type of the assigned
93 /// register or registers are. (Individual values are never synthesized
94 /// from more than one type of register.)
95 ///
96 /// With virtual registers, the contents of RegVTs is redundant with TLI's
97 /// getRegisterType member function, however when with physical registers
98 /// it is necessary to have a separate record of the types.
99 ///
Owen Andersone50ed302009-08-10 22:56:29 +0000100 SmallVector<EVT, 4> RegVTs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000101
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000102 /// Regs - This list holds the registers assigned to the values.
103 /// Each legal or promoted value requires one register, and each
104 /// expanded value requires multiple registers.
105 ///
106 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000107
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000108 RegsForValue() : TLI(0) {}
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000109
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000110 RegsForValue(const TargetLowering &tli,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000111 const SmallVector<unsigned, 4> &regs,
Owen Andersone50ed302009-08-10 22:56:29 +0000112 EVT regvt, EVT valuevt)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000113 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
114 RegsForValue(const TargetLowering &tli,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000115 const SmallVector<unsigned, 4> &regs,
Owen Andersone50ed302009-08-10 22:56:29 +0000116 const SmallVector<EVT, 4> &regvts,
117 const SmallVector<EVT, 4> &valuevts)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000118 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
Owen Anderson23b9b192009-08-12 00:36:31 +0000119 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000120 unsigned Reg, const Type *Ty) : TLI(&tli) {
121 ComputeValueVTs(tli, Ty, ValueVTs);
122
123 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +0000124 EVT ValueVT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +0000125 unsigned NumRegs = TLI->getNumRegisters(Context, ValueVT);
126 EVT RegisterVT = TLI->getRegisterType(Context, ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000127 for (unsigned i = 0; i != NumRegs; ++i)
128 Regs.push_back(Reg + i);
129 RegVTs.push_back(RegisterVT);
130 Reg += NumRegs;
131 }
132 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000133
Evan Cheng8112b532010-02-10 01:21:02 +0000134 /// areValueTypesLegal - Return true if types of all the values are legal.
135 bool areValueTypesLegal() {
136 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
137 EVT RegisterVT = RegVTs[Value];
138 if (!TLI->isTypeLegal(RegisterVT))
139 return false;
140 }
141 return true;
142 }
143
144
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000145 /// append - Add the specified values to this one.
146 void append(const RegsForValue &RHS) {
147 TLI = RHS.TLI;
148 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
149 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
150 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
151 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000152
153
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000154 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000155 /// this value and returns the result as a ValueVTs value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000156 /// Chain/Flag as the input and updates them for the output Chain/Flag.
157 /// If the Flag pointer is NULL, no flag is used.
Bill Wendling46ada192010-03-02 01:55:18 +0000158 SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
Bill Wendlingec72e322009-12-22 01:11:43 +0000159 SDValue &Chain, SDValue *Flag) const;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000160
161 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000162 /// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000163 /// Chain/Flag as the input and updates them for the output Chain/Flag.
164 /// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000165 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Bill Wendling46ada192010-03-02 01:55:18 +0000166 SDValue &Chain, SDValue *Flag) const;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000167
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000168 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
Evan Cheng697cbbf2009-03-20 18:03:34 +0000169 /// operand list. This adds the code marker, matching input operand index
170 /// (if applicable), and includes the number of values added into it.
171 void AddInlineAsmOperands(unsigned Code,
172 bool HasMatching, unsigned MatchingIdx,
Bill Wendling46ada192010-03-02 01:55:18 +0000173 SelectionDAG &DAG,
Bill Wendling651ad132009-12-22 01:25:10 +0000174 std::vector<SDValue> &Ops) const;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000175 };
176}
177
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000178/// getCopyFromParts - Create a value that contains the specified legal parts
179/// combined into the value they represent. If the parts combine to a type
180/// larger then ValueVT then AssertOp can be used to specify whether the extra
181/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
182/// (ISD::AssertSext).
Bill Wendling46ada192010-03-02 01:55:18 +0000183static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
Dale Johannesen66978ee2009-01-31 02:22:37 +0000184 const SDValue *Parts,
Owen Andersone50ed302009-08-10 22:56:29 +0000185 unsigned NumParts, EVT PartVT, EVT ValueVT,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000186 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000187 assert(NumParts > 0 && "No parts to assemble!");
Dan Gohmane9530ec2009-01-15 16:58:17 +0000188 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000189 SDValue Val = Parts[0];
190
191 if (NumParts > 1) {
192 // Assemble the value from multiple parts.
Eli Friedman2ac8b322009-05-20 06:02:09 +0000193 if (!ValueVT.isVector() && ValueVT.isInteger()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000194 unsigned PartBits = PartVT.getSizeInBits();
195 unsigned ValueBits = ValueVT.getSizeInBits();
196
197 // Assemble the power of 2 part.
198 unsigned RoundParts = NumParts & (NumParts - 1) ?
199 1 << Log2_32(NumParts) : NumParts;
200 unsigned RoundBits = PartBits * RoundParts;
Owen Andersone50ed302009-08-10 22:56:29 +0000201 EVT RoundVT = RoundBits == ValueBits ?
Owen Anderson23b9b192009-08-12 00:36:31 +0000202 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000203 SDValue Lo, Hi;
204
Owen Anderson23b9b192009-08-12 00:36:31 +0000205 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000206
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000207 if (RoundParts > 2) {
Bill Wendling46ada192010-03-02 01:55:18 +0000208 Lo = getCopyFromParts(DAG, dl, Parts, RoundParts / 2,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000209 PartVT, HalfVT);
Bill Wendling46ada192010-03-02 01:55:18 +0000210 Hi = getCopyFromParts(DAG, dl, Parts + RoundParts / 2,
Bill Wendling3ea3c242009-12-22 02:10:19 +0000211 RoundParts / 2, PartVT, HalfVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000212 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000213 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
214 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000215 }
Bill Wendling3ea3c242009-12-22 02:10:19 +0000216
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000217 if (TLI.isBigEndian())
218 std::swap(Lo, Hi);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000219
Dale Johannesen66978ee2009-01-31 02:22:37 +0000220 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000221
222 if (RoundParts < NumParts) {
223 // Assemble the trailing non-power-of-2 part.
224 unsigned OddParts = NumParts - RoundParts;
Owen Anderson23b9b192009-08-12 00:36:31 +0000225 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
Bill Wendling46ada192010-03-02 01:55:18 +0000226 Hi = getCopyFromParts(DAG, dl,
Bill Wendling3ea3c242009-12-22 02:10:19 +0000227 Parts + RoundParts, OddParts, PartVT, OddVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000228
229 // Combine the round and odd parts.
230 Lo = Val;
231 if (TLI.isBigEndian())
232 std::swap(Lo, Hi);
Owen Anderson23b9b192009-08-12 00:36:31 +0000233 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000234 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
235 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000236 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands92abc622009-01-31 15:50:11 +0000237 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000238 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
239 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000240 }
Eli Friedman2ac8b322009-05-20 06:02:09 +0000241 } else if (ValueVT.isVector()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000242 // Handle a multi-element vector.
Owen Andersone50ed302009-08-10 22:56:29 +0000243 EVT IntermediateVT, RegisterVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000244 unsigned NumIntermediates;
245 unsigned NumRegs =
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000246 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
Owen Anderson23b9b192009-08-12 00:36:31 +0000247 NumIntermediates, RegisterVT);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000248 assert(NumRegs == NumParts
249 && "Part count doesn't match vector breakdown!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000250 NumParts = NumRegs; // Silence a compiler warning.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000251 assert(RegisterVT == PartVT
252 && "Part type doesn't match vector breakdown!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000253 assert(RegisterVT == Parts[0].getValueType() &&
254 "Part type doesn't match part!");
255
256 // Assemble the parts into intermediate operands.
257 SmallVector<SDValue, 8> Ops(NumIntermediates);
258 if (NumIntermediates == NumParts) {
259 // If the register was not expanded, truncate or copy the value,
260 // as appropriate.
261 for (unsigned i = 0; i != NumParts; ++i)
Bill Wendling46ada192010-03-02 01:55:18 +0000262 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000263 PartVT, IntermediateVT);
264 } else if (NumParts > 0) {
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000265 // If the intermediate type was expanded, build the intermediate
266 // operands from the parts.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000267 assert(NumParts % NumIntermediates == 0 &&
268 "Must expand into a divisible number of parts!");
269 unsigned Factor = NumParts / NumIntermediates;
270 for (unsigned i = 0; i != NumIntermediates; ++i)
Bill Wendling46ada192010-03-02 01:55:18 +0000271 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000272 PartVT, IntermediateVT);
273 }
274
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000275 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
276 // intermediate operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000277 Val = DAG.getNode(IntermediateVT.isVector() ?
Dale Johannesen66978ee2009-01-31 02:22:37 +0000278 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000279 ValueVT, &Ops[0], NumIntermediates);
Eli Friedman2ac8b322009-05-20 06:02:09 +0000280 } else if (PartVT.isFloatingPoint()) {
281 // FP split into multiple FP parts (for ppcf128)
Owen Anderson825b72b2009-08-11 20:47:22 +0000282 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
Eli Friedman2ac8b322009-05-20 06:02:09 +0000283 "Unexpected split");
284 SDValue Lo, Hi;
Owen Anderson825b72b2009-08-11 20:47:22 +0000285 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[0]);
286 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[1]);
Eli Friedman2ac8b322009-05-20 06:02:09 +0000287 if (TLI.isBigEndian())
288 std::swap(Lo, Hi);
289 Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi);
290 } else {
291 // FP split into integer parts (soft fp)
292 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
293 !PartVT.isVector() && "Unexpected split");
Owen Anderson23b9b192009-08-12 00:36:31 +0000294 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
Bill Wendling46ada192010-03-02 01:55:18 +0000295 Val = getCopyFromParts(DAG, dl, Parts, NumParts, PartVT, IntVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000296 }
297 }
298
299 // There is now one part, held in Val. Correct it to match ValueVT.
300 PartVT = Val.getValueType();
301
302 if (PartVT == ValueVT)
303 return Val;
304
305 if (PartVT.isVector()) {
306 assert(ValueVT.isVector() && "Unknown vector conversion!");
Bill Wendling4533cac2010-01-28 21:51:40 +0000307 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000308 }
309
310 if (ValueVT.isVector()) {
311 assert(ValueVT.getVectorElementType() == PartVT &&
312 ValueVT.getVectorNumElements() == 1 &&
313 "Only trivial scalar-to-vector conversions should get here!");
Bill Wendling4533cac2010-01-28 21:51:40 +0000314 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000315 }
316
317 if (PartVT.isInteger() &&
318 ValueVT.isInteger()) {
319 if (ValueVT.bitsLT(PartVT)) {
320 // For a truncate, see if we have any information to
321 // indicate whether the truncated bits will always be
322 // zero or sign-extension.
323 if (AssertOp != ISD::DELETED_NODE)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000324 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000325 DAG.getValueType(ValueVT));
Bill Wendling4533cac2010-01-28 21:51:40 +0000326 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000327 } else {
Bill Wendling4533cac2010-01-28 21:51:40 +0000328 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000329 }
330 }
331
332 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
Bill Wendling3ea3c242009-12-22 02:10:19 +0000333 if (ValueVT.bitsLT(Val.getValueType())) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000334 // FP_ROUND's are always exact here.
Bill Wendling4533cac2010-01-28 21:51:40 +0000335 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
336 DAG.getIntPtrConstant(1));
Bill Wendling3ea3c242009-12-22 02:10:19 +0000337 }
338
Bill Wendling4533cac2010-01-28 21:51:40 +0000339 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000340 }
341
Bill Wendling4533cac2010-01-28 21:51:40 +0000342 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
343 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000344
Torok Edwinc23197a2009-07-14 16:55:14 +0000345 llvm_unreachable("Unknown mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000346 return SDValue();
347}
348
349/// getCopyToParts - Create a series of nodes that contain the specified value
350/// split into legal parts. If the parts contain more bits than Val, then, for
351/// integers, ExtendKind can be used to specify how to generate the extra bits.
Bill Wendling46ada192010-03-02 01:55:18 +0000352static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl,
Bill Wendling3ea3c242009-12-22 02:10:19 +0000353 SDValue Val, SDValue *Parts, unsigned NumParts,
354 EVT PartVT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000355 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohmane9530ec2009-01-15 16:58:17 +0000356 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Owen Andersone50ed302009-08-10 22:56:29 +0000357 EVT PtrVT = TLI.getPointerTy();
358 EVT ValueVT = Val.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000359 unsigned PartBits = PartVT.getSizeInBits();
Dale Johannesen8a36f502009-02-25 22:39:13 +0000360 unsigned OrigNumParts = NumParts;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000361 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
362
363 if (!NumParts)
364 return;
365
366 if (!ValueVT.isVector()) {
367 if (PartVT == ValueVT) {
368 assert(NumParts == 1 && "No-op copy with multiple parts!");
369 Parts[0] = Val;
370 return;
371 }
372
373 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
374 // If the parts cover more bits than the value has, promote the value.
375 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
376 assert(NumParts == 1 && "Do not know what to promote to!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000377 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000378 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
Owen Anderson23b9b192009-08-12 00:36:31 +0000379 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000380 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000381 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000382 llvm_unreachable("Unknown mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000383 }
384 } else if (PartBits == ValueVT.getSizeInBits()) {
385 // Different types of the same size.
386 assert(NumParts == 1 && PartVT != ValueVT);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000387 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000388 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
389 // If the parts cover less bits than value has, truncate the value.
390 if (PartVT.isInteger() && ValueVT.isInteger()) {
Owen Anderson23b9b192009-08-12 00:36:31 +0000391 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000392 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000393 } else {
Torok Edwinc23197a2009-07-14 16:55:14 +0000394 llvm_unreachable("Unknown mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000395 }
396 }
397
398 // The value may have changed - recompute ValueVT.
399 ValueVT = Val.getValueType();
400 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
401 "Failed to tile the value with PartVT!");
402
403 if (NumParts == 1) {
404 assert(PartVT == ValueVT && "Type conversion failed!");
405 Parts[0] = Val;
406 return;
407 }
408
409 // Expand the value into multiple parts.
410 if (NumParts & (NumParts - 1)) {
411 // The number of parts is not a power of 2. Split off and copy the tail.
412 assert(PartVT.isInteger() && ValueVT.isInteger() &&
413 "Do not know what to expand to!");
414 unsigned RoundParts = 1 << Log2_32(NumParts);
415 unsigned RoundBits = RoundParts * PartBits;
416 unsigned OddParts = NumParts - RoundParts;
Dale Johannesen66978ee2009-01-31 02:22:37 +0000417 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000418 DAG.getConstant(RoundBits,
Duncan Sands92abc622009-01-31 15:50:11 +0000419 TLI.getPointerTy()));
Bill Wendling46ada192010-03-02 01:55:18 +0000420 getCopyToParts(DAG, dl, OddVal, Parts + RoundParts,
Bill Wendling3ea3c242009-12-22 02:10:19 +0000421 OddParts, PartVT);
422
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000423 if (TLI.isBigEndian())
424 // The odd parts were reversed by getCopyToParts - unreverse them.
425 std::reverse(Parts + RoundParts, Parts + NumParts);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000426
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000427 NumParts = RoundParts;
Owen Anderson23b9b192009-08-12 00:36:31 +0000428 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000429 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000430 }
431
432 // The number of parts is a power of 2. Repeatedly bisect the value using
433 // EXTRACT_ELEMENT.
Scott Michelfdc40a02009-02-17 22:15:04 +0000434 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
Chris Lattnerf031e8a2010-01-01 03:32:16 +0000435 EVT::getIntegerVT(*DAG.getContext(),
436 ValueVT.getSizeInBits()),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000437 Val);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000438
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000439 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
440 for (unsigned i = 0; i < NumParts; i += StepSize) {
441 unsigned ThisBits = StepSize * PartBits / 2;
Owen Anderson23b9b192009-08-12 00:36:31 +0000442 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000443 SDValue &Part0 = Parts[i];
444 SDValue &Part1 = Parts[i+StepSize/2];
445
Scott Michelfdc40a02009-02-17 22:15:04 +0000446 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000447 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000448 DAG.getConstant(1, PtrVT));
Scott Michelfdc40a02009-02-17 22:15:04 +0000449 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000450 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000451 DAG.getConstant(0, PtrVT));
452
453 if (ThisBits == PartBits && ThisVT != PartVT) {
Scott Michelfdc40a02009-02-17 22:15:04 +0000454 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000455 PartVT, Part0);
Scott Michelfdc40a02009-02-17 22:15:04 +0000456 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000457 PartVT, Part1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000458 }
459 }
460 }
461
462 if (TLI.isBigEndian())
Dale Johannesen8a36f502009-02-25 22:39:13 +0000463 std::reverse(Parts, Parts + OrigNumParts);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000464
465 return;
466 }
467
468 // Vector ValueVT.
469 if (NumParts == 1) {
470 if (PartVT != ValueVT) {
Bob Wilson5afffae2009-12-18 01:03:29 +0000471 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000472 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000473 } else {
474 assert(ValueVT.getVectorElementType() == PartVT &&
475 ValueVT.getVectorNumElements() == 1 &&
476 "Only trivial vector-to-scalar conversions should get here!");
Scott Michelfdc40a02009-02-17 22:15:04 +0000477 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000478 PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000479 DAG.getConstant(0, PtrVT));
480 }
481 }
482
483 Parts[0] = Val;
484 return;
485 }
486
487 // Handle a multi-element vector.
Owen Andersone50ed302009-08-10 22:56:29 +0000488 EVT IntermediateVT, RegisterVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000489 unsigned NumIntermediates;
Owen Anderson23b9b192009-08-12 00:36:31 +0000490 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
491 IntermediateVT, NumIntermediates, RegisterVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000492 unsigned NumElements = ValueVT.getVectorNumElements();
493
494 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
495 NumParts = NumRegs; // Silence a compiler warning.
496 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
497
498 // Split the vector into intermediate operands.
499 SmallVector<SDValue, 8> Ops(NumIntermediates);
Bill Wendling3ea3c242009-12-22 02:10:19 +0000500 for (unsigned i = 0; i != NumIntermediates; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000501 if (IntermediateVT.isVector())
Scott Michelfdc40a02009-02-17 22:15:04 +0000502 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000503 IntermediateVT, Val,
504 DAG.getConstant(i * (NumElements / NumIntermediates),
505 PtrVT));
506 else
Scott Michelfdc40a02009-02-17 22:15:04 +0000507 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000508 IntermediateVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000509 DAG.getConstant(i, PtrVT));
Bill Wendling3ea3c242009-12-22 02:10:19 +0000510 }
511
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000512 // Split the intermediate operands into legal parts.
513 if (NumParts == NumIntermediates) {
514 // If the register was not expanded, promote or copy the value,
515 // as appropriate.
516 for (unsigned i = 0; i != NumParts; ++i)
Bill Wendling46ada192010-03-02 01:55:18 +0000517 getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000518 } else if (NumParts > 0) {
519 // If the intermediate type was expanded, split each the value into
520 // legal parts.
521 assert(NumParts % NumIntermediates == 0 &&
522 "Must expand into a divisible number of parts!");
523 unsigned Factor = NumParts / NumIntermediates;
524 for (unsigned i = 0; i != NumIntermediates; ++i)
Bill Wendling46ada192010-03-02 01:55:18 +0000525 getCopyToParts(DAG, dl, Ops[i], &Parts[i*Factor], Factor, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000526 }
527}
528
529
Dan Gohman2048b852009-11-23 18:04:58 +0000530void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000531 AA = &aa;
532 GFI = gfi;
533 TD = DAG.getTarget().getTargetData();
534}
535
536/// clear - Clear out the curret SelectionDAG and the associated
Dan Gohman2048b852009-11-23 18:04:58 +0000537/// state and prepare this SelectionDAGBuilder object to be used
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000538/// for a new block. This doesn't clear out information about
539/// additional blocks that are needed to complete switch lowering
540/// or PHI node updating; that information is cleared out as it is
541/// consumed.
Dan Gohman2048b852009-11-23 18:04:58 +0000542void SelectionDAGBuilder::clear() {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000543 NodeMap.clear();
544 PendingLoads.clear();
545 PendingExports.clear();
Evan Chengfb2e7522009-09-18 21:02:19 +0000546 EdgeMapping.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000547 DAG.clear();
Chris Lattnera4f2bb02010-04-02 20:17:23 +0000548 CurDebugLoc = DebugLoc();
Dan Gohman98ca4f22009-08-05 01:29:28 +0000549 HasTailCall = false;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000550}
551
552/// getRoot - Return the current virtual root of the Selection DAG,
553/// flushing any PendingLoad items. This must be done before emitting
554/// a store or any other node that may need to be ordered after any
555/// prior load instructions.
556///
Dan Gohman2048b852009-11-23 18:04:58 +0000557SDValue SelectionDAGBuilder::getRoot() {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000558 if (PendingLoads.empty())
559 return DAG.getRoot();
560
561 if (PendingLoads.size() == 1) {
562 SDValue Root = PendingLoads[0];
563 DAG.setRoot(Root);
564 PendingLoads.clear();
565 return Root;
566 }
567
568 // Otherwise, we have to make a token factor node.
Owen Anderson825b72b2009-08-11 20:47:22 +0000569 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000570 &PendingLoads[0], PendingLoads.size());
571 PendingLoads.clear();
572 DAG.setRoot(Root);
573 return Root;
574}
575
576/// getControlRoot - Similar to getRoot, but instead of flushing all the
577/// PendingLoad items, flush all the PendingExports items. It is necessary
578/// to do this before emitting a terminator instruction.
579///
Dan Gohman2048b852009-11-23 18:04:58 +0000580SDValue SelectionDAGBuilder::getControlRoot() {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000581 SDValue Root = DAG.getRoot();
582
583 if (PendingExports.empty())
584 return Root;
585
586 // Turn all of the CopyToReg chains into one factored node.
587 if (Root.getOpcode() != ISD::EntryToken) {
588 unsigned i = 0, e = PendingExports.size();
589 for (; i != e; ++i) {
590 assert(PendingExports[i].getNode()->getNumOperands() > 1);
591 if (PendingExports[i].getNode()->getOperand(0) == Root)
592 break; // Don't add the root if we already indirectly depend on it.
593 }
594
595 if (i == e)
596 PendingExports.push_back(Root);
597 }
598
Owen Anderson825b72b2009-08-11 20:47:22 +0000599 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000600 &PendingExports[0],
601 PendingExports.size());
602 PendingExports.clear();
603 DAG.setRoot(Root);
604 return Root;
605}
606
Bill Wendling4533cac2010-01-28 21:51:40 +0000607void SelectionDAGBuilder::AssignOrderingToNode(const SDNode *Node) {
608 if (DAG.GetOrdering(Node) != 0) return; // Already has ordering.
609 DAG.AssignOrdering(Node, SDNodeOrder);
610
611 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)
612 AssignOrderingToNode(Node->getOperand(I).getNode());
613}
614
Dan Gohman2048b852009-11-23 18:04:58 +0000615void SelectionDAGBuilder::visit(Instruction &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000616 visit(I.getOpcode(), I);
617}
618
Dan Gohman2048b852009-11-23 18:04:58 +0000619void SelectionDAGBuilder::visit(unsigned Opcode, User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000620 // Note: this doesn't use InstVisitor, because it has to work with
621 // ConstantExpr's in addition to instructions.
622 switch (Opcode) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000623 default: llvm_unreachable("Unknown instruction type encountered!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000624 // Build the switch statement using the Instruction.def file.
625#define HANDLE_INST(NUM, OPCODE, CLASS) \
Bill Wendling4533cac2010-01-28 21:51:40 +0000626 case Instruction::OPCODE: visit##OPCODE((CLASS&)I); break;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000627#include "llvm/Instruction.def"
628 }
Bill Wendling4533cac2010-01-28 21:51:40 +0000629
630 // Assign the ordering to the freshly created DAG nodes.
631 if (NodeMap.count(&I)) {
632 ++SDNodeOrder;
633 AssignOrderingToNode(getValue(&I).getNode());
634 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000635}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000636
Dan Gohman2048b852009-11-23 18:04:58 +0000637SDValue SelectionDAGBuilder::getValue(const Value *V) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000638 SDValue &N = NodeMap[V];
639 if (N.getNode()) return N;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000640
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000641 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
Owen Andersone50ed302009-08-10 22:56:29 +0000642 EVT VT = TLI.getValueType(V->getType(), true);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000643
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000644 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000645 return N = DAG.getConstant(*CI, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000646
647 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
648 return N = DAG.getGlobalAddress(GV, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000649
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000650 if (isa<ConstantPointerNull>(C))
651 return N = DAG.getConstant(0, TLI.getPointerTy());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000652
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000653 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000654 return N = DAG.getConstantFP(*CFP, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000655
Nate Begeman9008ca62009-04-27 18:41:29 +0000656 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
Dale Johannesene8d72302009-02-06 23:05:02 +0000657 return N = DAG.getUNDEF(VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000658
659 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
660 visit(CE->getOpcode(), *CE);
661 SDValue N1 = NodeMap[V];
662 assert(N1.getNode() && "visit didn't populate the ValueMap!");
663 return N1;
664 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000665
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000666 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
667 SmallVector<SDValue, 4> Constants;
668 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
669 OI != OE; ++OI) {
670 SDNode *Val = getValue(*OI).getNode();
Dan Gohmaned48caf2009-09-08 01:44:02 +0000671 // If the operand is an empty aggregate, there are no values.
672 if (!Val) continue;
673 // Add each leaf value from the operand to the Constants list
674 // to form a flattened list of all the values.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000675 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
676 Constants.push_back(SDValue(Val, i));
677 }
Bill Wendling87710f02009-12-21 23:47:40 +0000678
Bill Wendling4533cac2010-01-28 21:51:40 +0000679 return DAG.getMergeValues(&Constants[0], Constants.size(),
680 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000681 }
682
Duncan Sands1df98592010-02-16 11:11:14 +0000683 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000684 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
685 "Unknown struct or array constant!");
686
Owen Andersone50ed302009-08-10 22:56:29 +0000687 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000688 ComputeValueVTs(TLI, C->getType(), ValueVTs);
689 unsigned NumElts = ValueVTs.size();
690 if (NumElts == 0)
691 return SDValue(); // empty struct
692 SmallVector<SDValue, 4> Constants(NumElts);
693 for (unsigned i = 0; i != NumElts; ++i) {
Owen Andersone50ed302009-08-10 22:56:29 +0000694 EVT EltVT = ValueVTs[i];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000695 if (isa<UndefValue>(C))
Dale Johannesene8d72302009-02-06 23:05:02 +0000696 Constants[i] = DAG.getUNDEF(EltVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000697 else if (EltVT.isFloatingPoint())
698 Constants[i] = DAG.getConstantFP(0, EltVT);
699 else
700 Constants[i] = DAG.getConstant(0, EltVT);
701 }
Bill Wendling87710f02009-12-21 23:47:40 +0000702
Bill Wendling4533cac2010-01-28 21:51:40 +0000703 return DAG.getMergeValues(&Constants[0], NumElts,
704 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000705 }
706
Dan Gohman8c2b5252009-10-30 01:27:03 +0000707 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
Dan Gohman29cbade2009-11-20 23:18:13 +0000708 return DAG.getBlockAddress(BA, VT);
Dan Gohman8c2b5252009-10-30 01:27:03 +0000709
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000710 const VectorType *VecTy = cast<VectorType>(V->getType());
711 unsigned NumElements = VecTy->getNumElements();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000712
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000713 // Now that we know the number and type of the elements, get that number of
714 // elements into the Ops array based on what kind of constant it is.
715 SmallVector<SDValue, 16> Ops;
716 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
717 for (unsigned i = 0; i != NumElements; ++i)
718 Ops.push_back(getValue(CP->getOperand(i)));
719 } else {
Nate Begeman9008ca62009-04-27 18:41:29 +0000720 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
Owen Andersone50ed302009-08-10 22:56:29 +0000721 EVT EltVT = TLI.getValueType(VecTy->getElementType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000722
723 SDValue Op;
Nate Begeman9008ca62009-04-27 18:41:29 +0000724 if (EltVT.isFloatingPoint())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000725 Op = DAG.getConstantFP(0, EltVT);
726 else
727 Op = DAG.getConstant(0, EltVT);
728 Ops.assign(NumElements, Op);
729 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000730
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000731 // Create a BUILD_VECTOR node.
Bill Wendling4533cac2010-01-28 21:51:40 +0000732 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
733 VT, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000734 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000735
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000736 // If this is a static alloca, generate it as the frameindex instead of
737 // computation.
738 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
739 DenseMap<const AllocaInst*, int>::iterator SI =
740 FuncInfo.StaticAllocaMap.find(AI);
741 if (SI != FuncInfo.StaticAllocaMap.end())
742 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
743 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000744
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000745 unsigned InReg = FuncInfo.ValueMap[V];
746 assert(InReg && "Value not in map!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000747
Owen Anderson23b9b192009-08-12 00:36:31 +0000748 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000749 SDValue Chain = DAG.getEntryNode();
Bill Wendling46ada192010-03-02 01:55:18 +0000750 return RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000751}
752
Kenneth Uildriks93ae4072010-01-16 23:37:33 +0000753/// Get the EVTs and ArgFlags collections that represent the legalized return
754/// type of the given function. This does not require a DAG or a return value,
755/// and is suitable for use before any DAGs for the function are constructed.
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000756static void getReturnInfo(const Type* ReturnType,
757 Attributes attr, SmallVectorImpl<EVT> &OutVTs,
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000758 SmallVectorImpl<ISD::ArgFlagsTy> &OutFlags,
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000759 TargetLowering &TLI,
760 SmallVectorImpl<uint64_t> *Offsets = 0) {
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000761 SmallVector<EVT, 4> ValueVTs;
Kenneth Uildriks93ae4072010-01-16 23:37:33 +0000762 ComputeValueVTs(TLI, ReturnType, ValueVTs);
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000763 unsigned NumValues = ValueVTs.size();
Kenneth Uildriks93ae4072010-01-16 23:37:33 +0000764 if (NumValues == 0) return;
765 unsigned Offset = 0;
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000766
767 for (unsigned j = 0, f = NumValues; j != f; ++j) {
768 EVT VT = ValueVTs[j];
769 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000770
771 if (attr & Attribute::SExt)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000772 ExtendKind = ISD::SIGN_EXTEND;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000773 else if (attr & Attribute::ZExt)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000774 ExtendKind = ISD::ZERO_EXTEND;
775
776 // FIXME: C calling convention requires the return type to be promoted to
777 // at least 32-bit. But this is not necessary for non-C calling
778 // conventions. The frontend should mark functions whose return values
779 // require promoting with signext or zeroext attributes.
780 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000781 EVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000782 if (VT.bitsLT(MinVT))
783 VT = MinVT;
784 }
785
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000786 unsigned NumParts = TLI.getNumRegisters(ReturnType->getContext(), VT);
787 EVT PartVT = TLI.getRegisterType(ReturnType->getContext(), VT);
Kenneth Uildriks93ae4072010-01-16 23:37:33 +0000788 unsigned PartSize = TLI.getTargetData()->getTypeAllocSize(
789 PartVT.getTypeForEVT(ReturnType->getContext()));
790
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000791 // 'inreg' on function refers to return value
792 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000793 if (attr & Attribute::InReg)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000794 Flags.setInReg();
795
796 // Propagate extension type if any
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000797 if (attr & Attribute::SExt)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000798 Flags.setSExt();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000799 else if (attr & Attribute::ZExt)
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000800 Flags.setZExt();
801
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000802 for (unsigned i = 0; i < NumParts; ++i) {
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000803 OutVTs.push_back(PartVT);
804 OutFlags.push_back(Flags);
Kenneth Uildriks93ae4072010-01-16 23:37:33 +0000805 if (Offsets)
806 {
807 Offsets->push_back(Offset);
808 Offset += PartSize;
809 }
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +0000810 }
811 }
812}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000813
Dan Gohman2048b852009-11-23 18:04:58 +0000814void SelectionDAGBuilder::visitRet(ReturnInst &I) {
Dan Gohman98ca4f22009-08-05 01:29:28 +0000815 SDValue Chain = getControlRoot();
816 SmallVector<ISD::OutputArg, 8> Outs;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000817 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000818
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000819 if (!FLI.CanLowerReturn) {
820 unsigned DemoteReg = FLI.DemoteRegister;
821 const Function *F = I.getParent()->getParent();
822
823 // Emit a store of the return value through the virtual register.
824 // Leave Outs empty so that LowerReturn won't try to load return
825 // registers the usual way.
826 SmallVector<EVT, 1> PtrValueVTs;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000827 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000828 PtrValueVTs);
829
830 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
831 SDValue RetOp = getValue(I.getOperand(0));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000832
Owen Andersone50ed302009-08-10 22:56:29 +0000833 SmallVector<EVT, 4> ValueVTs;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000834 SmallVector<uint64_t, 4> Offsets;
835 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
Dan Gohman7ea1ca62008-10-21 20:00:42 +0000836 unsigned NumValues = ValueVTs.size();
Dan Gohman7ea1ca62008-10-21 20:00:42 +0000837
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000838 SmallVector<SDValue, 4> Chains(NumValues);
839 EVT PtrVT = PtrValueVTs[0];
Bill Wendling87710f02009-12-21 23:47:40 +0000840 for (unsigned i = 0; i != NumValues; ++i) {
841 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, RetPtr,
842 DAG.getConstant(Offsets[i], PtrVT));
843 Chains[i] =
844 DAG.getStore(Chain, getCurDebugLoc(),
845 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
David Greene1e559442010-02-15 17:00:31 +0000846 Add, NULL, Offsets[i], false, false, 0);
Bill Wendling87710f02009-12-21 23:47:40 +0000847 }
848
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000849 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
850 MVT::Other, &Chains[0], NumValues);
Chris Lattner25d58372010-02-28 18:53:13 +0000851 } else if (I.getNumOperands() != 0) {
852 SmallVector<EVT, 4> ValueVTs;
853 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
854 unsigned NumValues = ValueVTs.size();
855 if (NumValues) {
856 SDValue RetOp = getValue(I.getOperand(0));
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000857 for (unsigned j = 0, f = NumValues; j != f; ++j) {
858 EVT VT = ValueVTs[j];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000859
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000860 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000861
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000862 const Function *F = I.getParent()->getParent();
863 if (F->paramHasAttr(0, Attribute::SExt))
864 ExtendKind = ISD::SIGN_EXTEND;
865 else if (F->paramHasAttr(0, Attribute::ZExt))
866 ExtendKind = ISD::ZERO_EXTEND;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000867
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +0000868 // FIXME: C calling convention requires the return type to be promoted
869 // to at least 32-bit. But this is not necessary for non-C calling
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000870 // conventions. The frontend should mark functions whose return values
871 // require promoting with signext or zeroext attributes.
872 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
873 EVT MinVT = TLI.getRegisterType(*DAG.getContext(), MVT::i32);
874 if (VT.bitsLT(MinVT))
875 VT = MinVT;
876 }
877
878 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
879 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
880 SmallVector<SDValue, 4> Parts(NumParts);
Bill Wendling46ada192010-03-02 01:55:18 +0000881 getCopyToParts(DAG, getCurDebugLoc(),
Kenneth Uildriksc158dde2009-11-11 19:59:24 +0000882 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
883 &Parts[0], NumParts, PartVT, ExtendKind);
884
885 // 'inreg' on function refers to return value
886 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
887 if (F->paramHasAttr(0, Attribute::InReg))
888 Flags.setInReg();
889
890 // Propagate extension type if any
891 if (F->paramHasAttr(0, Attribute::SExt))
892 Flags.setSExt();
893 else if (F->paramHasAttr(0, Attribute::ZExt))
894 Flags.setZExt();
895
896 for (unsigned i = 0; i < NumParts; ++i)
897 Outs.push_back(ISD::OutputArg(Flags, Parts[i], /*isfixed=*/true));
Evan Cheng3927f432009-03-25 20:20:11 +0000898 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000899 }
900 }
Dan Gohman98ca4f22009-08-05 01:29:28 +0000901
902 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
Sandeep Patel65c3c8f2009-09-02 08:44:58 +0000903 CallingConv::ID CallConv =
904 DAG.getMachineFunction().getFunction()->getCallingConv();
Dan Gohman98ca4f22009-08-05 01:29:28 +0000905 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
906 Outs, getCurDebugLoc(), DAG);
Dan Gohman5e866062009-08-06 15:37:27 +0000907
908 // Verify that the target's LowerReturn behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +0000909 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +0000910 "LowerReturn didn't return a valid chain!");
911
912 // Update the DAG with the new chain value resulting from return lowering.
Dan Gohman98ca4f22009-08-05 01:29:28 +0000913 DAG.setRoot(Chain);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000914}
915
Dan Gohmanad62f532009-04-23 23:13:24 +0000916/// CopyToExportRegsIfNeeded - If the given value has virtual registers
917/// created for it, emit nodes to copy the value into the virtual
918/// registers.
Dan Gohman2048b852009-11-23 18:04:58 +0000919void SelectionDAGBuilder::CopyToExportRegsIfNeeded(Value *V) {
Dan Gohmanad62f532009-04-23 23:13:24 +0000920 if (!V->use_empty()) {
921 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
922 if (VMI != FuncInfo.ValueMap.end())
923 CopyValueToVirtualRegister(V, VMI->second);
924 }
925}
926
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000927/// ExportFromCurrentBlock - If this condition isn't known to be exported from
928/// the current basic block, add it to ValueMap now so that we'll get a
929/// CopyTo/FromReg.
Dan Gohman2048b852009-11-23 18:04:58 +0000930void SelectionDAGBuilder::ExportFromCurrentBlock(Value *V) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000931 // No need to export constants.
932 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000933
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000934 // Already exported?
935 if (FuncInfo.isExportedInst(V)) return;
936
937 unsigned Reg = FuncInfo.InitializeRegForValue(V);
938 CopyValueToVirtualRegister(V, Reg);
939}
940
Dan Gohman2048b852009-11-23 18:04:58 +0000941bool SelectionDAGBuilder::isExportableFromCurrentBlock(Value *V,
942 const BasicBlock *FromBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000943 // The operands of the setcc have to be in this block. We don't know
944 // how to export them from some other block.
945 if (Instruction *VI = dyn_cast<Instruction>(V)) {
946 // Can export from current BB.
947 if (VI->getParent() == FromBB)
948 return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000949
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000950 // Is already exported, noop.
951 return FuncInfo.isExportedInst(V);
952 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000953
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000954 // If this is an argument, we can export it if the BB is the entry block or
955 // if it is already exported.
956 if (isa<Argument>(V)) {
957 if (FromBB == &FromBB->getParent()->getEntryBlock())
958 return true;
959
960 // Otherwise, can only export this if it is already exported.
961 return FuncInfo.isExportedInst(V);
962 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000963
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000964 // Otherwise, constants can always be exported.
965 return true;
966}
967
968static bool InBlock(const Value *V, const BasicBlock *BB) {
969 if (const Instruction *I = dyn_cast<Instruction>(V))
970 return I->getParent() == BB;
971 return true;
972}
973
Dan Gohman8c1a6ca2008-10-17 18:18:45 +0000974/// getFCmpCondCode - Return the ISD condition code corresponding to
975/// the given LLVM IR floating-point condition code. This includes
976/// consideration of global floating-point math flags.
977///
978static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
979 ISD::CondCode FPC, FOC;
980 switch (Pred) {
981 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
982 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
983 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
984 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
985 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
986 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
987 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
988 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
989 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
990 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
991 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
992 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
993 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
994 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
995 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
996 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
997 default:
Torok Edwinc23197a2009-07-14 16:55:14 +0000998 llvm_unreachable("Invalid FCmp predicate opcode!");
Dan Gohman8c1a6ca2008-10-17 18:18:45 +0000999 FOC = FPC = ISD::SETFALSE;
1000 break;
1001 }
1002 if (FiniteOnlyFPMath())
1003 return FOC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001004 else
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001005 return FPC;
1006}
1007
1008/// getICmpCondCode - Return the ISD condition code corresponding to
1009/// the given LLVM IR integer condition code.
1010///
1011static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1012 switch (Pred) {
1013 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1014 case ICmpInst::ICMP_NE: return ISD::SETNE;
1015 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1016 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1017 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1018 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1019 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1020 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1021 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1022 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1023 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001024 llvm_unreachable("Invalid ICmp predicate opcode!");
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001025 return ISD::SETNE;
1026 }
1027}
1028
Dan Gohmanc2277342008-10-17 21:16:08 +00001029/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1030/// This function emits a branch and is used at the leaves of an OR or an
1031/// AND operator tree.
1032///
1033void
Dan Gohman2048b852009-11-23 18:04:58 +00001034SelectionDAGBuilder::EmitBranchForMergedCondition(Value *Cond,
1035 MachineBasicBlock *TBB,
1036 MachineBasicBlock *FBB,
1037 MachineBasicBlock *CurBB) {
Dan Gohmanc2277342008-10-17 21:16:08 +00001038 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001039
Dan Gohmanc2277342008-10-17 21:16:08 +00001040 // If the leaf of the tree is a comparison, merge the condition into
1041 // the caseblock.
1042 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1043 // The operands of the cmp have to be in this block. We don't know
1044 // how to export them from some other block. If this is the first block
1045 // of the sequence, no exporting is needed.
1046 if (CurBB == CurMBB ||
1047 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1048 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001049 ISD::CondCode Condition;
1050 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001051 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001052 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001053 Condition = getFCmpCondCode(FC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001054 } else {
1055 Condition = ISD::SETEQ; // silence warning.
Torok Edwinc23197a2009-07-14 16:55:14 +00001056 llvm_unreachable("Unknown compare instruction");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001057 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001058
1059 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001060 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1061 SwitchCases.push_back(CB);
1062 return;
1063 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001064 }
1065
1066 // Create a CaseBlock record representing this branch.
Owen Anderson5defacc2009-07-31 17:39:07 +00001067 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
Dan Gohmanc2277342008-10-17 21:16:08 +00001068 NULL, TBB, FBB, CurBB);
1069 SwitchCases.push_back(CB);
1070}
1071
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001072/// FindMergedConditions - If Cond is an expression like
Dan Gohman2048b852009-11-23 18:04:58 +00001073void SelectionDAGBuilder::FindMergedConditions(Value *Cond,
1074 MachineBasicBlock *TBB,
1075 MachineBasicBlock *FBB,
1076 MachineBasicBlock *CurBB,
1077 unsigned Opc) {
Dan Gohmanc2277342008-10-17 21:16:08 +00001078 // If this node is not part of the or/and tree, emit it as a branch.
1079 Instruction *BOp = dyn_cast<Instruction>(Cond);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001080 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohmanc2277342008-10-17 21:16:08 +00001081 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1082 BOp->getParent() != CurBB->getBasicBlock() ||
1083 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1084 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1085 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001086 return;
1087 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001088
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001089 // Create TmpBB after CurBB.
1090 MachineFunction::iterator BBI = CurBB;
1091 MachineFunction &MF = DAG.getMachineFunction();
1092 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1093 CurBB->getParent()->insert(++BBI, TmpBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001094
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001095 if (Opc == Instruction::Or) {
1096 // Codegen X | Y as:
1097 // jmp_if_X TBB
1098 // jmp TmpBB
1099 // TmpBB:
1100 // jmp_if_Y TBB
1101 // jmp FBB
1102 //
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001103
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001104 // Emit the LHS condition.
1105 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001106
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001107 // Emit the RHS condition into TmpBB.
1108 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1109 } else {
1110 assert(Opc == Instruction::And && "Unknown merge op!");
1111 // Codegen X & Y as:
1112 // jmp_if_X TmpBB
1113 // jmp FBB
1114 // TmpBB:
1115 // jmp_if_Y TBB
1116 // jmp FBB
1117 //
1118 // This requires creation of TmpBB after CurBB.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001119
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001120 // Emit the LHS condition.
1121 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001122
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001123 // Emit the RHS condition into TmpBB.
1124 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1125 }
1126}
1127
1128/// If the set of cases should be emitted as a series of branches, return true.
1129/// If we should emit this as a bunch of and/or'd together conditions, return
1130/// false.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001131bool
Dan Gohman2048b852009-11-23 18:04:58 +00001132SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001133 if (Cases.size() != 2) return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001134
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001135 // If this is two comparisons of the same values or'd or and'd together, they
1136 // will get folded into a single comparison, so don't emit two blocks.
1137 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1138 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1139 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1140 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1141 return false;
1142 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001143
Chris Lattner133ce872010-01-02 00:00:03 +00001144 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1145 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1146 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1147 Cases[0].CC == Cases[1].CC &&
1148 isa<Constant>(Cases[0].CmpRHS) &&
1149 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1150 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1151 return false;
1152 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1153 return false;
1154 }
1155
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001156 return true;
1157}
1158
Dan Gohman2048b852009-11-23 18:04:58 +00001159void SelectionDAGBuilder::visitBr(BranchInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001160 // Update machine-CFG edges.
1161 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1162
1163 // Figure out which block is immediately after the current one.
1164 MachineBasicBlock *NextBlock = 0;
1165 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001166 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001167 NextBlock = BBI;
1168
1169 if (I.isUnconditional()) {
1170 // Update machine-CFG edges.
1171 CurMBB->addSuccessor(Succ0MBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001172
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001173 // If this is not a fall-through branch, emit the branch.
Bill Wendling4533cac2010-01-28 21:51:40 +00001174 if (Succ0MBB != NextBlock)
1175 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001176 MVT::Other, getControlRoot(),
Bill Wendling4533cac2010-01-28 21:51:40 +00001177 DAG.getBasicBlock(Succ0MBB)));
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001178
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001179 return;
1180 }
1181
1182 // If this condition is one of the special cases we handle, do special stuff
1183 // now.
1184 Value *CondVal = I.getCondition();
1185 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1186
1187 // If this is a series of conditions that are or'd or and'd together, emit
1188 // this as a sequence of branches instead of setcc's with and/or operations.
1189 // For example, instead of something like:
1190 // cmp A, B
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001191 // C = seteq
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001192 // cmp D, E
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001193 // F = setle
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001194 // or C, F
1195 // jnz foo
1196 // Emit:
1197 // cmp A, B
1198 // je foo
1199 // cmp D, E
1200 // jle foo
1201 //
1202 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001203 if (BOp->hasOneUse() &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001204 (BOp->getOpcode() == Instruction::And ||
1205 BOp->getOpcode() == Instruction::Or)) {
1206 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1207 // If the compares in later blocks need to use values not currently
1208 // exported from this block, export them now. This block should always
1209 // be the first entry.
1210 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001211
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001212 // Allow some cases to be rejected.
1213 if (ShouldEmitAsBranches(SwitchCases)) {
1214 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1215 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1216 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1217 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001218
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001219 // Emit the branch for this block.
1220 visitSwitchCase(SwitchCases[0]);
1221 SwitchCases.erase(SwitchCases.begin());
1222 return;
1223 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001224
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001225 // Okay, we decided not to do this, remove any inserted MBB's and clear
1226 // SwitchCases.
1227 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001228 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001229
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001230 SwitchCases.clear();
1231 }
1232 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001233
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001234 // Create a CaseBlock record representing this branch.
Owen Anderson5defacc2009-07-31 17:39:07 +00001235 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001236 NULL, Succ0MBB, Succ1MBB, CurMBB);
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001237
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001238 // Use visitSwitchCase to actually insert the fast branch sequence for this
1239 // cond branch.
1240 visitSwitchCase(CB);
1241}
1242
1243/// visitSwitchCase - Emits the necessary code to represent a single node in
1244/// the binary search tree resulting from lowering a switch instruction.
Dan Gohman2048b852009-11-23 18:04:58 +00001245void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001246 SDValue Cond;
1247 SDValue CondLHS = getValue(CB.CmpLHS);
Dale Johannesenf5d97892009-02-04 01:48:28 +00001248 DebugLoc dl = getCurDebugLoc();
Anton Korobeynikov23218582008-12-23 22:25:27 +00001249
1250 // Build the setcc now.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001251 if (CB.CmpMHS == NULL) {
1252 // Fold "(X == true)" to X and "(X == false)" to !X to
1253 // handle common cases produced by branch lowering.
Owen Anderson5defacc2009-07-31 17:39:07 +00001254 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
Owen Andersonf53c3712009-07-21 02:47:59 +00001255 CB.CC == ISD::SETEQ)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001256 Cond = CondLHS;
Owen Anderson5defacc2009-07-31 17:39:07 +00001257 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
Owen Andersonf53c3712009-07-21 02:47:59 +00001258 CB.CC == ISD::SETEQ) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001259 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001260 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001261 } else
Owen Anderson825b72b2009-08-11 20:47:22 +00001262 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001263 } else {
1264 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1265
Anton Korobeynikov23218582008-12-23 22:25:27 +00001266 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1267 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001268
1269 SDValue CmpOp = getValue(CB.CmpMHS);
Owen Andersone50ed302009-08-10 22:56:29 +00001270 EVT VT = CmpOp.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001271
1272 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001273 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
Dale Johannesenf5d97892009-02-04 01:48:28 +00001274 ISD::SETLE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001275 } else {
Dale Johannesenf5d97892009-02-04 01:48:28 +00001276 SDValue SUB = DAG.getNode(ISD::SUB, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001277 VT, CmpOp, DAG.getConstant(Low, VT));
Owen Anderson825b72b2009-08-11 20:47:22 +00001278 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001279 DAG.getConstant(High-Low, VT), ISD::SETULE);
1280 }
1281 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001282
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001283 // Update successor info
1284 CurMBB->addSuccessor(CB.TrueBB);
1285 CurMBB->addSuccessor(CB.FalseBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001286
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001287 // Set NextBlock to be the MBB immediately after the current one, if any.
1288 // This is used to avoid emitting unnecessary branches to the next block.
1289 MachineBasicBlock *NextBlock = 0;
1290 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001291 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001292 NextBlock = BBI;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001293
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001294 // If the lhs block is the next block, invert the condition so that we can
1295 // fall through to the lhs instead of the rhs block.
1296 if (CB.TrueBB == NextBlock) {
1297 std::swap(CB.TrueBB, CB.FalseBB);
1298 SDValue True = DAG.getConstant(1, Cond.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001299 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001300 }
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001301
Dale Johannesenf5d97892009-02-04 01:48:28 +00001302 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00001303 MVT::Other, getControlRoot(), Cond,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001304 DAG.getBasicBlock(CB.TrueBB));
Bill Wendling87710f02009-12-21 23:47:40 +00001305
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001306 // If the branch was constant folded, fix up the CFG.
1307 if (BrCond.getOpcode() == ISD::BR) {
1308 CurMBB->removeSuccessor(CB.FalseBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001309 } else {
1310 // Otherwise, go ahead and insert the false branch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001311 if (BrCond == getControlRoot())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001312 CurMBB->removeSuccessor(CB.TrueBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001313
Bill Wendling4533cac2010-01-28 21:51:40 +00001314 if (CB.FalseBB != NextBlock)
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001315 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1316 DAG.getBasicBlock(CB.FalseBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001317 }
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001318
1319 DAG.setRoot(BrCond);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001320}
1321
1322/// visitJumpTable - Emit JumpTable node in the current MBB
Dan Gohman2048b852009-11-23 18:04:58 +00001323void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001324 // Emit the code for the jump table
1325 assert(JT.Reg != -1U && "Should lower JT Header first!");
Owen Andersone50ed302009-08-10 22:56:29 +00001326 EVT PTy = TLI.getPointerTy();
Dale Johannesena04b7572009-02-03 23:04:43 +00001327 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1328 JT.Reg, PTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001329 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001330 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1331 MVT::Other, Index.getValue(1),
1332 Table, Index);
1333 DAG.setRoot(BrJumpTable);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001334}
1335
1336/// visitJumpTableHeader - This function emits necessary code to produce index
1337/// in the JumpTable from switch case.
Dan Gohman2048b852009-11-23 18:04:58 +00001338void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1339 JumpTableHeader &JTH) {
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001340 // Subtract the lowest switch case value from the value being switched on and
1341 // conditional branch to default mbb if the result is greater than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001342 // difference between smallest and largest cases.
1343 SDValue SwitchOp = getValue(JTH.SValue);
Owen Andersone50ed302009-08-10 22:56:29 +00001344 EVT VT = SwitchOp.getValueType();
Bill Wendling87710f02009-12-21 23:47:40 +00001345 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001346 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001347
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001348 // The SDNode we just created, which holds the value being switched on minus
Dan Gohmanf451cb82010-02-10 16:03:48 +00001349 // the smallest case value, needs to be copied to a virtual register so it
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001350 // can be used as an index into the jump table in a subsequent basic block.
1351 // This value may be smaller or larger than the target's pointer type, and
1352 // therefore require extension or truncating.
Bill Wendling87710f02009-12-21 23:47:40 +00001353 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001354
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001355 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001356 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1357 JumpTableReg, SwitchOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001358 JT.Reg = JumpTableReg;
1359
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001360 // Emit the range check for the jump table, and branch to the default block
1361 // for the switch statement if the value being switched on exceeds the largest
1362 // case in the switch.
Dale Johannesenf5d97892009-02-04 01:48:28 +00001363 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00001364 TLI.getSetCCResultType(Sub.getValueType()), Sub,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001365 DAG.getConstant(JTH.Last-JTH.First,VT),
1366 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001367
1368 // Set NextBlock to be the MBB immediately after the current one, if any.
1369 // This is used to avoid emitting unnecessary branches to the next block.
1370 MachineBasicBlock *NextBlock = 0;
1371 MachineFunction::iterator BBI = CurMBB;
Bill Wendling87710f02009-12-21 23:47:40 +00001372
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001373 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001374 NextBlock = BBI;
1375
Dale Johannesen66978ee2009-01-31 02:22:37 +00001376 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001377 MVT::Other, CopyTo, CMP,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001378 DAG.getBasicBlock(JT.Default));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001379
Bill Wendling4533cac2010-01-28 21:51:40 +00001380 if (JT.MBB != NextBlock)
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001381 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1382 DAG.getBasicBlock(JT.MBB));
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001383
Bill Wendling87710f02009-12-21 23:47:40 +00001384 DAG.setRoot(BrCond);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001385}
1386
1387/// visitBitTestHeader - This function emits necessary code to produce value
1388/// suitable for "bit tests"
Dan Gohman2048b852009-11-23 18:04:58 +00001389void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001390 // Subtract the minimum value
1391 SDValue SwitchOp = getValue(B.SValue);
Owen Andersone50ed302009-08-10 22:56:29 +00001392 EVT VT = SwitchOp.getValueType();
Bill Wendling87710f02009-12-21 23:47:40 +00001393 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001394 DAG.getConstant(B.First, VT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001395
1396 // Check range
Dale Johannesenf5d97892009-02-04 01:48:28 +00001397 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00001398 TLI.getSetCCResultType(Sub.getValueType()),
1399 Sub, DAG.getConstant(B.Range, VT),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001400 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001401
Bill Wendling87710f02009-12-21 23:47:40 +00001402 SDValue ShiftOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(),
1403 TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001404
Duncan Sands92abc622009-01-31 15:50:11 +00001405 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001406 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1407 B.Reg, ShiftOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001408
1409 // Set NextBlock to be the MBB immediately after the current one, if any.
1410 // This is used to avoid emitting unnecessary branches to the next block.
1411 MachineBasicBlock *NextBlock = 0;
1412 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001413 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001414 NextBlock = BBI;
1415
1416 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1417
1418 CurMBB->addSuccessor(B.Default);
1419 CurMBB->addSuccessor(MBB);
1420
Dale Johannesen66978ee2009-01-31 02:22:37 +00001421 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001422 MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001423 DAG.getBasicBlock(B.Default));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001424
Bill Wendling4533cac2010-01-28 21:51:40 +00001425 if (MBB != NextBlock)
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001426 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1427 DAG.getBasicBlock(MBB));
Bill Wendling3b7a41c2009-12-21 19:59:38 +00001428
Bill Wendling87710f02009-12-21 23:47:40 +00001429 DAG.setRoot(BrRange);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001430}
1431
1432/// visitBitTestCase - this function produces one "bit test"
Dan Gohman2048b852009-11-23 18:04:58 +00001433void SelectionDAGBuilder::visitBitTestCase(MachineBasicBlock* NextMBB,
1434 unsigned Reg,
1435 BitTestCase &B) {
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001436 // Make desired shift
Dale Johannesena04b7572009-02-03 23:04:43 +00001437 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
Duncan Sands92abc622009-01-31 15:50:11 +00001438 TLI.getPointerTy());
Scott Michelfdc40a02009-02-17 22:15:04 +00001439 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001440 TLI.getPointerTy(),
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001441 DAG.getConstant(1, TLI.getPointerTy()),
1442 ShiftOp);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001443
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001444 // Emit bit tests and jumps
Scott Michelfdc40a02009-02-17 22:15:04 +00001445 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001446 TLI.getPointerTy(), SwitchVal,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001447 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Dale Johannesenf5d97892009-02-04 01:48:28 +00001448 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1449 TLI.getSetCCResultType(AndOp.getValueType()),
Duncan Sands5480c042009-01-01 15:52:00 +00001450 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001451 ISD::SETNE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001452
1453 CurMBB->addSuccessor(B.TargetBB);
1454 CurMBB->addSuccessor(NextMBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001455
Dale Johannesen66978ee2009-01-31 02:22:37 +00001456 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00001457 MVT::Other, getControlRoot(),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001458 AndCmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001459
1460 // Set NextBlock to be the MBB immediately after the current one, if any.
1461 // This is used to avoid emitting unnecessary branches to the next block.
1462 MachineBasicBlock *NextBlock = 0;
1463 MachineFunction::iterator BBI = CurMBB;
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001464 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001465 NextBlock = BBI;
1466
Bill Wendling4533cac2010-01-28 21:51:40 +00001467 if (NextMBB != NextBlock)
Bill Wendling0777e922009-12-21 21:59:52 +00001468 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1469 DAG.getBasicBlock(NextMBB));
Bill Wendling0777e922009-12-21 21:59:52 +00001470
Bill Wendling87710f02009-12-21 23:47:40 +00001471 DAG.setRoot(BrAnd);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001472}
1473
Dan Gohman2048b852009-11-23 18:04:58 +00001474void SelectionDAGBuilder::visitInvoke(InvokeInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001475 // Retrieve successors.
1476 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1477 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1478
Gabor Greifb67e6b32009-01-15 11:10:44 +00001479 const Value *Callee(I.getCalledValue());
1480 if (isa<InlineAsm>(Callee))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001481 visitInlineAsm(&I);
1482 else
Gabor Greifb67e6b32009-01-15 11:10:44 +00001483 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001484
1485 // If the value of the invoke is used outside of its defining block, make it
1486 // available as a virtual register.
Dan Gohmanad62f532009-04-23 23:13:24 +00001487 CopyToExportRegsIfNeeded(&I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001488
1489 // Update successor info
1490 CurMBB->addSuccessor(Return);
1491 CurMBB->addSuccessor(LandingPad);
1492
1493 // Drop into normal successor.
Bill Wendling4533cac2010-01-28 21:51:40 +00001494 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1495 MVT::Other, getControlRoot(),
1496 DAG.getBasicBlock(Return)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001497}
1498
Dan Gohman2048b852009-11-23 18:04:58 +00001499void SelectionDAGBuilder::visitUnwind(UnwindInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001500}
1501
1502/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1503/// small case ranges).
Dan Gohman2048b852009-11-23 18:04:58 +00001504bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
1505 CaseRecVector& WorkList,
1506 Value* SV,
1507 MachineBasicBlock* Default) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001508 Case& BackCase = *(CR.Range.second-1);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001509
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001510 // Size is the number of Cases represented by this range.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001511 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001512 if (Size > 3)
Anton Korobeynikov23218582008-12-23 22:25:27 +00001513 return false;
1514
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001515 // Get the MachineFunction which holds the current MBB. This is used when
1516 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001517 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001518
1519 // Figure out which block is immediately after the current one.
1520 MachineBasicBlock *NextBlock = 0;
1521 MachineFunction::iterator BBI = CR.CaseBB;
1522
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001523 if (++BBI != FuncInfo.MF->end())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001524 NextBlock = BBI;
1525
1526 // TODO: If any two of the cases has the same destination, and if one value
1527 // is the same as the other, but has one bit unset that the other has set,
1528 // use bit manipulation to do two compares at once. For example:
1529 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Anton Korobeynikov23218582008-12-23 22:25:27 +00001530
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001531 // Rearrange the case blocks so that the last one falls through if possible.
1532 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1533 // The last case block won't fall through into 'NextBlock' if we emit the
1534 // branches in this order. See if rearranging a case value would help.
1535 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1536 if (I->BB == NextBlock) {
1537 std::swap(*I, BackCase);
1538 break;
1539 }
1540 }
1541 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001542
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001543 // Create a CaseBlock record representing a conditional branch to
1544 // the Case's target mbb if the value being switched on SV is equal
1545 // to C.
1546 MachineBasicBlock *CurBlock = CR.CaseBB;
1547 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1548 MachineBasicBlock *FallThrough;
1549 if (I != E-1) {
1550 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1551 CurMF->insert(BBI, FallThrough);
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001552
1553 // Put SV in a virtual register to make it available from the new blocks.
1554 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001555 } else {
1556 // If the last case doesn't match, go to the default block.
1557 FallThrough = Default;
1558 }
1559
1560 Value *RHS, *LHS, *MHS;
1561 ISD::CondCode CC;
1562 if (I->High == I->Low) {
1563 // This is just small small case range :) containing exactly 1 case
1564 CC = ISD::SETEQ;
1565 LHS = SV; RHS = I->High; MHS = NULL;
1566 } else {
1567 CC = ISD::SETLE;
1568 LHS = I->Low; MHS = SV; RHS = I->High;
1569 }
1570 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001571
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001572 // If emitting the first comparison, just call visitSwitchCase to emit the
1573 // code into the current block. Otherwise, push the CaseBlock onto the
1574 // vector to be later processed by SDISel, and insert the node's MBB
1575 // before the next MBB.
1576 if (CurBlock == CurMBB)
1577 visitSwitchCase(CB);
1578 else
1579 SwitchCases.push_back(CB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001580
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001581 CurBlock = FallThrough;
1582 }
1583
1584 return true;
1585}
1586
1587static inline bool areJTsAllowed(const TargetLowering &TLI) {
1588 return !DisableJumpTables &&
Owen Anderson825b72b2009-08-11 20:47:22 +00001589 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1590 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001591}
Anton Korobeynikov23218582008-12-23 22:25:27 +00001592
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001593static APInt ComputeRange(const APInt &First, const APInt &Last) {
1594 APInt LastExt(Last), FirstExt(First);
1595 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1596 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1597 return (LastExt - FirstExt + 1ULL);
1598}
1599
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001600/// handleJTSwitchCase - Emit jumptable for current switch case range
Dan Gohman2048b852009-11-23 18:04:58 +00001601bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR,
1602 CaseRecVector& WorkList,
1603 Value* SV,
1604 MachineBasicBlock* Default) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001605 Case& FrontCase = *CR.Range.first;
1606 Case& BackCase = *(CR.Range.second-1);
1607
Chris Lattnere880efe2009-11-07 07:50:34 +00001608 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1609 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001610
Chris Lattnere880efe2009-11-07 07:50:34 +00001611 APInt TSize(First.getBitWidth(), 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001612 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1613 I!=E; ++I)
1614 TSize += I->size();
1615
Chris Lattnere880efe2009-11-07 07:50:34 +00001616 if (!areJTsAllowed(TLI) || TSize.ult(APInt(First.getBitWidth(), 4)))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001617 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001618
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001619 APInt Range = ComputeRange(First, Last);
Chris Lattnere880efe2009-11-07 07:50:34 +00001620 double Density = TSize.roundToDouble() / Range.roundToDouble();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001621 if (Density < 0.4)
1622 return false;
1623
David Greene4b69d992010-01-05 01:24:57 +00001624 DEBUG(dbgs() << "Lowering jump table\n"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001625 << "First entry: " << First << ". Last entry: " << Last << '\n'
1626 << "Range: " << Range
1627 << "Size: " << TSize << ". Density: " << Density << "\n\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001628
1629 // Get the MachineFunction which holds the current MBB. This is used when
1630 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001631 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001632
1633 // Figure out which block is immediately after the current one.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001634 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands51498522009-09-06 18:03:32 +00001635 ++BBI;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001636
1637 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1638
1639 // Create a new basic block to hold the code for loading the address
1640 // of the jump table, and jumping to it. Update successor information;
1641 // we will either branch to the default case for the switch, or the jump
1642 // table.
1643 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1644 CurMF->insert(BBI, JumpTableBB);
1645 CR.CaseBB->addSuccessor(Default);
1646 CR.CaseBB->addSuccessor(JumpTableBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001647
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001648 // Build a vector of destination BBs, corresponding to each target
1649 // of the jump table. If the value of the jump table slot corresponds to
1650 // a case statement, push the case's BB onto the vector, otherwise, push
1651 // the default BB.
1652 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001653 APInt TEI = First;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001654 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Chris Lattner071c62f2010-01-25 23:26:13 +00001655 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
1656 const APInt &High = cast<ConstantInt>(I->High)->getValue();
Anton Korobeynikov23218582008-12-23 22:25:27 +00001657
1658 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001659 DestBBs.push_back(I->BB);
1660 if (TEI==High)
1661 ++I;
1662 } else {
1663 DestBBs.push_back(Default);
1664 }
1665 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001666
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001667 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001668 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1669 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001670 E = DestBBs.end(); I != E; ++I) {
1671 if (!SuccsHandled[(*I)->getNumber()]) {
1672 SuccsHandled[(*I)->getNumber()] = true;
1673 JumpTableBB->addSuccessor(*I);
1674 }
1675 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001676
Bob Wilsond1ec31d2010-03-18 18:42:41 +00001677 // Create a jump table index for this jump table.
Chris Lattner071c62f2010-01-25 23:26:13 +00001678 unsigned JTEncoding = TLI.getJumpTableEncoding();
1679 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
Bob Wilsond1ec31d2010-03-18 18:42:41 +00001680 ->createJumpTableIndex(DestBBs);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001681
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001682 // Set the jump table information so that we can codegen it as a second
1683 // MachineBasicBlock
1684 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1685 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1686 if (CR.CaseBB == CurMBB)
1687 visitJumpTableHeader(JT, JTH);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001688
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001689 JTCases.push_back(JumpTableBlock(JTH, JT));
1690
1691 return true;
1692}
1693
1694/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1695/// 2 subtrees.
Dan Gohman2048b852009-11-23 18:04:58 +00001696bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
1697 CaseRecVector& WorkList,
1698 Value* SV,
1699 MachineBasicBlock* Default) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001700 // Get the MachineFunction which holds the current MBB. This is used when
1701 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001702 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001703
1704 // Figure out which block is immediately after the current one.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001705 MachineFunction::iterator BBI = CR.CaseBB;
Duncan Sands51498522009-09-06 18:03:32 +00001706 ++BBI;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001707
1708 Case& FrontCase = *CR.Range.first;
1709 Case& BackCase = *(CR.Range.second-1);
1710 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1711
1712 // Size is the number of Cases represented by this range.
1713 unsigned Size = CR.Range.second - CR.Range.first;
1714
Chris Lattnere880efe2009-11-07 07:50:34 +00001715 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1716 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001717 double FMetric = 0;
1718 CaseItr Pivot = CR.Range.first + Size/2;
1719
1720 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1721 // (heuristically) allow us to emit JumpTable's later.
Chris Lattnere880efe2009-11-07 07:50:34 +00001722 APInt TSize(First.getBitWidth(), 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001723 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1724 I!=E; ++I)
1725 TSize += I->size();
1726
Chris Lattnere880efe2009-11-07 07:50:34 +00001727 APInt LSize = FrontCase.size();
1728 APInt RSize = TSize-LSize;
David Greene4b69d992010-01-05 01:24:57 +00001729 DEBUG(dbgs() << "Selecting best pivot: \n"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001730 << "First: " << First << ", Last: " << Last <<'\n'
1731 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001732 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1733 J!=E; ++I, ++J) {
Chris Lattnere880efe2009-11-07 07:50:34 +00001734 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
1735 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001736 APInt Range = ComputeRange(LEnd, RBegin);
1737 assert((Range - 2ULL).isNonNegative() &&
1738 "Invalid case distance");
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00001739 double LDensity = (double)LSize.roundToDouble() /
Chris Lattnere880efe2009-11-07 07:50:34 +00001740 (LEnd - First + 1ULL).roundToDouble();
1741 double RDensity = (double)RSize.roundToDouble() /
1742 (Last - RBegin + 1ULL).roundToDouble();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001743 double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001744 // Should always split in some non-trivial place
David Greene4b69d992010-01-05 01:24:57 +00001745 DEBUG(dbgs() <<"=>Step\n"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001746 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1747 << "LDensity: " << LDensity
1748 << ", RDensity: " << RDensity << '\n'
1749 << "Metric: " << Metric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001750 if (FMetric < Metric) {
1751 Pivot = J;
1752 FMetric = Metric;
David Greene4b69d992010-01-05 01:24:57 +00001753 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001754 }
1755
1756 LSize += J->size();
1757 RSize -= J->size();
1758 }
1759 if (areJTsAllowed(TLI)) {
1760 // If our case is dense we *really* should handle it earlier!
1761 assert((FMetric > 0) && "Should handle dense range earlier!");
1762 } else {
1763 Pivot = CR.Range.first + Size/2;
1764 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001765
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001766 CaseRange LHSR(CR.Range.first, Pivot);
1767 CaseRange RHSR(Pivot, CR.Range.second);
1768 Constant *C = Pivot->Low;
1769 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001770
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001771 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001772 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001773 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001774 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001775 // Pivot's Value, then we can branch directly to the LHS's Target,
1776 // rather than creating a leaf node for it.
1777 if ((LHSR.second - LHSR.first) == 1 &&
1778 LHSR.first->High == CR.GE &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001779 cast<ConstantInt>(C)->getValue() ==
1780 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001781 TrueBB = LHSR.first->BB;
1782 } else {
1783 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1784 CurMF->insert(BBI, TrueBB);
1785 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001786
1787 // Put SV in a virtual register to make it available from the new blocks.
1788 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001789 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001790
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001791 // Similar to the optimization above, if the Value being switched on is
1792 // known to be less than the Constant CR.LT, and the current Case Value
1793 // is CR.LT - 1, then we can branch directly to the target block for
1794 // the current Case Value, rather than emitting a RHS leaf node for it.
1795 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001796 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1797 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001798 FalseBB = RHSR.first->BB;
1799 } else {
1800 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1801 CurMF->insert(BBI, FalseBB);
1802 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001803
1804 // Put SV in a virtual register to make it available from the new blocks.
1805 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001806 }
1807
1808 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001809 // the LHS node if the value being switched on SV is less than C.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001810 // Otherwise, branch to LHS.
1811 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1812
1813 if (CR.CaseBB == CurMBB)
1814 visitSwitchCase(CB);
1815 else
1816 SwitchCases.push_back(CB);
1817
1818 return true;
1819}
1820
1821/// handleBitTestsSwitchCase - if current case range has few destination and
1822/// range span less, than machine word bitwidth, encode case range into series
1823/// of masks and emit bit tests with these masks.
Dan Gohman2048b852009-11-23 18:04:58 +00001824bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
1825 CaseRecVector& WorkList,
1826 Value* SV,
1827 MachineBasicBlock* Default){
Owen Andersone50ed302009-08-10 22:56:29 +00001828 EVT PTy = TLI.getPointerTy();
Owen Anderson77547be2009-08-10 18:56:59 +00001829 unsigned IntPtrBits = PTy.getSizeInBits();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001830
1831 Case& FrontCase = *CR.Range.first;
1832 Case& BackCase = *(CR.Range.second-1);
1833
1834 // Get the MachineFunction which holds the current MBB. This is used when
1835 // inserting any additional MBBs necessary to represent the switch.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00001836 MachineFunction *CurMF = FuncInfo.MF;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001837
Anton Korobeynikovd34167a2009-05-08 18:51:34 +00001838 // If target does not have legal shift left, do not emit bit tests at all.
1839 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
1840 return false;
1841
Anton Korobeynikov23218582008-12-23 22:25:27 +00001842 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001843 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1844 I!=E; ++I) {
1845 // Single case counts one, case range - two.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001846 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001847 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001848
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001849 // Count unique destinations
1850 SmallSet<MachineBasicBlock*, 4> Dests;
1851 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1852 Dests.insert(I->BB);
1853 if (Dests.size() > 3)
1854 // Don't bother the code below, if there are too much unique destinations
1855 return false;
1856 }
David Greene4b69d992010-01-05 01:24:57 +00001857 DEBUG(dbgs() << "Total number of unique destinations: "
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00001858 << Dests.size() << '\n'
1859 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001860
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001861 // Compute span of values.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001862 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1863 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001864 APInt cmpRange = maxValue - minValue;
1865
David Greene4b69d992010-01-05 01:24:57 +00001866 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001867 << "Low bound: " << minValue << '\n'
1868 << "High bound: " << maxValue << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001869
1870 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001871 (!(Dests.size() == 1 && numCmps >= 3) &&
1872 !(Dests.size() == 2 && numCmps >= 5) &&
1873 !(Dests.size() >= 3 && numCmps >= 6)))
1874 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001875
David Greene4b69d992010-01-05 01:24:57 +00001876 DEBUG(dbgs() << "Emitting bit tests\n");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001877 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1878
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001879 // Optimize the case where all the case values fit in a
1880 // word without having to subtract minValue. In this case,
1881 // we can optimize away the subtraction.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001882 if (minValue.isNonNegative() &&
1883 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1884 cmpRange = maxValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001885 } else {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001886 lowBound = minValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001887 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001888
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001889 CaseBitsVector CasesBits;
1890 unsigned i, count = 0;
1891
1892 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1893 MachineBasicBlock* Dest = I->BB;
1894 for (i = 0; i < count; ++i)
1895 if (Dest == CasesBits[i].BB)
1896 break;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001897
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001898 if (i == count) {
1899 assert((count < 3) && "Too much destinations to test!");
1900 CasesBits.push_back(CaseBits(0, Dest, 0));
1901 count++;
1902 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001903
1904 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1905 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1906
1907 uint64_t lo = (lowValue - lowBound).getZExtValue();
1908 uint64_t hi = (highValue - lowBound).getZExtValue();
1909
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001910 for (uint64_t j = lo; j <= hi; j++) {
1911 CasesBits[i].Mask |= 1ULL << j;
1912 CasesBits[i].Bits++;
1913 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001914
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001915 }
1916 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001917
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001918 BitTestInfo BTC;
1919
1920 // Figure out which block is immediately after the current one.
1921 MachineFunction::iterator BBI = CR.CaseBB;
1922 ++BBI;
1923
1924 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1925
David Greene4b69d992010-01-05 01:24:57 +00001926 DEBUG(dbgs() << "Cases:\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001927 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
David Greene4b69d992010-01-05 01:24:57 +00001928 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001929 << ", Bits: " << CasesBits[i].Bits
1930 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001931
1932 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1933 CurMF->insert(BBI, CaseBB);
1934 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1935 CaseBB,
1936 CasesBits[i].BB));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001937
1938 // Put SV in a virtual register to make it available from the new blocks.
1939 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001940 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001941
1942 BitTestBlock BTB(lowBound, cmpRange, SV,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001943 -1U, (CR.CaseBB == CurMBB),
1944 CR.CaseBB, Default, BTC);
1945
1946 if (CR.CaseBB == CurMBB)
1947 visitBitTestHeader(BTB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001948
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001949 BitTestCases.push_back(BTB);
1950
1951 return true;
1952}
1953
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001954/// Clusterify - Transform simple list of Cases into list of CaseRange's
Dan Gohman2048b852009-11-23 18:04:58 +00001955size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
1956 const SwitchInst& SI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001957 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001958
1959 // Start with "simple" cases
Anton Korobeynikov23218582008-12-23 22:25:27 +00001960 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001961 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1962 Cases.push_back(Case(SI.getSuccessorValue(i),
1963 SI.getSuccessorValue(i),
1964 SMBB));
1965 }
1966 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1967
1968 // Merge case into clusters
Anton Korobeynikov23218582008-12-23 22:25:27 +00001969 if (Cases.size() >= 2)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001970 // Must recompute end() each iteration because it may be
1971 // invalidated by erase if we hold on to it
Anton Korobeynikov23218582008-12-23 22:25:27 +00001972 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
1973 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
1974 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001975 MachineBasicBlock* nextBB = J->BB;
1976 MachineBasicBlock* currentBB = I->BB;
1977
1978 // If the two neighboring cases go to the same destination, merge them
1979 // into a single case.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001980 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001981 I->High = J->High;
1982 J = Cases.erase(J);
1983 } else {
1984 I = J++;
1985 }
1986 }
1987
1988 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1989 if (I->Low != I->High)
1990 // A range counts double, since it requires two compares.
1991 ++numCmps;
1992 }
1993
1994 return numCmps;
1995}
1996
Dan Gohman2048b852009-11-23 18:04:58 +00001997void SelectionDAGBuilder::visitSwitch(SwitchInst &SI) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001998 // Figure out which block is immediately after the current one.
1999 MachineBasicBlock *NextBlock = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002000 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2001
2002 // If there is only the default destination, branch to it if it is not the
2003 // next basic block. Otherwise, just fall through.
2004 if (SI.getNumOperands() == 2) {
2005 // Update machine-CFG edges.
2006
2007 // If this is not a fall-through branch, emit the branch.
2008 CurMBB->addSuccessor(Default);
Bill Wendling4533cac2010-01-28 21:51:40 +00002009 if (Default != NextBlock)
2010 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
2011 MVT::Other, getControlRoot(),
2012 DAG.getBasicBlock(Default)));
Bill Wendling49fcff82009-12-21 22:30:11 +00002013
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002014 return;
2015 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002016
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002017 // If there are any non-default case statements, create a vector of Cases
2018 // representing each one, and sort the vector so that we can efficiently
2019 // create a binary search tree from them.
2020 CaseVector Cases;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002021 size_t numCmps = Clusterify(Cases, SI);
David Greene4b69d992010-01-05 01:24:57 +00002022 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002023 << ". Total compares: " << numCmps << '\n');
Devang Patel8a84e442009-01-05 17:31:22 +00002024 numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002025
2026 // Get the Value to be switched on and default basic blocks, which will be
2027 // inserted into CaseBlock records, representing basic blocks in the binary
2028 // search tree.
2029 Value *SV = SI.getOperand(0);
2030
2031 // Push the initial CaseRec onto the worklist
2032 CaseRecVector WorkList;
2033 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2034
2035 while (!WorkList.empty()) {
2036 // Grab a record representing a case range to process off the worklist
2037 CaseRec CR = WorkList.back();
2038 WorkList.pop_back();
2039
2040 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2041 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002042
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002043 // If the range has few cases (two or less) emit a series of specific
2044 // tests.
2045 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2046 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002047
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002048 // If the switch has more than 5 blocks, and at least 40% dense, and the
2049 // target supports indirect branches, then emit a jump table rather than
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002050 // lowering the switch to a binary tree of conditional branches.
2051 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2052 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002053
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002054 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2055 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2056 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2057 }
2058}
2059
Dan Gohman2048b852009-11-23 18:04:58 +00002060void SelectionDAGBuilder::visitIndirectBr(IndirectBrInst &I) {
Jakob Stoklund Olesen598b24c2010-02-11 00:34:18 +00002061 // Update machine-CFG edges with unique successors.
Jakob Stoklund Olesenb5b90ed2010-02-11 18:06:56 +00002062 SmallVector<BasicBlock*, 32> succs;
Jakob Stoklund Olesen598b24c2010-02-11 00:34:18 +00002063 succs.reserve(I.getNumSuccessors());
Dan Gohmaneef55dc2009-10-27 22:10:34 +00002064 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
Jakob Stoklund Olesen598b24c2010-02-11 00:34:18 +00002065 succs.push_back(I.getSuccessor(i));
Jakob Stoklund Olesenb5b90ed2010-02-11 18:06:56 +00002066 array_pod_sort(succs.begin(), succs.end());
Jakob Stoklund Olesen598b24c2010-02-11 00:34:18 +00002067 succs.erase(std::unique(succs.begin(), succs.end()), succs.end());
2068 for (unsigned i = 0, e = succs.size(); i != e; ++i)
2069 CurMBB->addSuccessor(FuncInfo.MBBMap[succs[i]]);
Dan Gohmaneef55dc2009-10-27 22:10:34 +00002070
Bill Wendling4533cac2010-01-28 21:51:40 +00002071 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2072 MVT::Other, getControlRoot(),
2073 getValue(I.getAddress())));
Bill Wendling49fcff82009-12-21 22:30:11 +00002074}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002075
Dan Gohman2048b852009-11-23 18:04:58 +00002076void SelectionDAGBuilder::visitFSub(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002077 // -0.0 - X --> fneg
2078 const Type *Ty = I.getType();
Duncan Sands1df98592010-02-16 11:11:14 +00002079 if (Ty->isVectorTy()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002080 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2081 const VectorType *DestTy = cast<VectorType>(I.getType());
2082 const Type *ElTy = DestTy->getElementType();
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002083 unsigned VL = DestTy->getNumElements();
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002084 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
Owen Andersonaf7ec972009-07-28 21:19:26 +00002085 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002086 if (CV == CNZ) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002087 SDValue Op2 = getValue(I.getOperand(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00002088 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2089 Op2.getValueType(), Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002090 return;
2091 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002092 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002093 }
Bill Wendling49fcff82009-12-21 22:30:11 +00002094
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002095 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002096 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002097 SDValue Op2 = getValue(I.getOperand(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00002098 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2099 Op2.getValueType(), Op2));
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002100 return;
2101 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002102
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002103 visitBinary(I, ISD::FSUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002104}
2105
Dan Gohman2048b852009-11-23 18:04:58 +00002106void SelectionDAGBuilder::visitBinary(User &I, unsigned OpCode) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002107 SDValue Op1 = getValue(I.getOperand(0));
2108 SDValue Op2 = getValue(I.getOperand(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00002109 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2110 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002111}
2112
Dan Gohman2048b852009-11-23 18:04:58 +00002113void SelectionDAGBuilder::visitShift(User &I, unsigned Opcode) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002114 SDValue Op1 = getValue(I.getOperand(0));
2115 SDValue Op2 = getValue(I.getOperand(1));
Duncan Sands1df98592010-02-16 11:11:14 +00002116 if (!I.getType()->isVectorTy() &&
Dan Gohman57fc82d2009-04-09 03:51:29 +00002117 Op2.getValueType() != TLI.getShiftAmountTy()) {
2118 // If the operand is smaller than the shift count type, promote it.
Owen Andersone50ed302009-08-10 22:56:29 +00002119 EVT PTy = TLI.getPointerTy();
2120 EVT STy = TLI.getShiftAmountTy();
Owen Anderson77547be2009-08-10 18:56:59 +00002121 if (STy.bitsGT(Op2.getValueType()))
Dan Gohman57fc82d2009-04-09 03:51:29 +00002122 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2123 TLI.getShiftAmountTy(), Op2);
2124 // If the operand is larger than the shift count type but the shift
2125 // count type has enough bits to represent any shift value, truncate
2126 // it now. This is a common case and it exposes the truncate to
2127 // optimization early.
Owen Anderson77547be2009-08-10 18:56:59 +00002128 else if (STy.getSizeInBits() >=
Dan Gohman57fc82d2009-04-09 03:51:29 +00002129 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2130 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2131 TLI.getShiftAmountTy(), Op2);
2132 // Otherwise we'll need to temporarily settle for some other
2133 // convenient type; type legalization will make adjustments as
2134 // needed.
Owen Anderson77547be2009-08-10 18:56:59 +00002135 else if (PTy.bitsLT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002136 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002137 TLI.getPointerTy(), Op2);
Owen Anderson77547be2009-08-10 18:56:59 +00002138 else if (PTy.bitsGT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002139 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002140 TLI.getPointerTy(), Op2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002141 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002142
Bill Wendling4533cac2010-01-28 21:51:40 +00002143 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2144 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002145}
2146
Dan Gohman2048b852009-11-23 18:04:58 +00002147void SelectionDAGBuilder::visitICmp(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002148 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2149 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2150 predicate = IC->getPredicate();
2151 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2152 predicate = ICmpInst::Predicate(IC->getPredicate());
2153 SDValue Op1 = getValue(I.getOperand(0));
2154 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002155 ISD::CondCode Opcode = getICmpCondCode(predicate);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002156
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, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002159}
2160
Dan Gohman2048b852009-11-23 18:04:58 +00002161void SelectionDAGBuilder::visitFCmp(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002162 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2163 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2164 predicate = FC->getPredicate();
2165 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2166 predicate = FCmpInst::Predicate(FC->getPredicate());
2167 SDValue Op1 = getValue(I.getOperand(0));
2168 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002169 ISD::CondCode Condition = getFCmpCondCode(predicate);
Owen Andersone50ed302009-08-10 22:56:29 +00002170 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002171 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002172}
2173
Dan Gohman2048b852009-11-23 18:04:58 +00002174void SelectionDAGBuilder::visitSelect(User &I) {
Owen Andersone50ed302009-08-10 22:56:29 +00002175 SmallVector<EVT, 4> ValueVTs;
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002176 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2177 unsigned NumValues = ValueVTs.size();
Bill Wendling49fcff82009-12-21 22:30:11 +00002178 if (NumValues == 0) return;
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002179
Bill Wendling49fcff82009-12-21 22:30:11 +00002180 SmallVector<SDValue, 4> Values(NumValues);
2181 SDValue Cond = getValue(I.getOperand(0));
2182 SDValue TrueVal = getValue(I.getOperand(1));
2183 SDValue FalseVal = getValue(I.getOperand(2));
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002184
Bill Wendling4533cac2010-01-28 21:51:40 +00002185 for (unsigned i = 0; i != NumValues; ++i)
Bill Wendling49fcff82009-12-21 22:30:11 +00002186 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
Chris Lattnerb3e87b22010-03-12 07:15:36 +00002187 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
2188 Cond,
Bill Wendling49fcff82009-12-21 22:30:11 +00002189 SDValue(TrueVal.getNode(),
2190 TrueVal.getResNo() + i),
2191 SDValue(FalseVal.getNode(),
2192 FalseVal.getResNo() + i));
2193
Bill Wendling4533cac2010-01-28 21:51:40 +00002194 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2195 DAG.getVTList(&ValueVTs[0], NumValues),
2196 &Values[0], NumValues));
Bill Wendling49fcff82009-12-21 22:30:11 +00002197}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002198
Dan Gohman2048b852009-11-23 18:04:58 +00002199void SelectionDAGBuilder::visitTrunc(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002200 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2201 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002202 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002203 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002204}
2205
Dan Gohman2048b852009-11-23 18:04:58 +00002206void SelectionDAGBuilder::visitZExt(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002207 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2208 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2209 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002210 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002211 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002212}
2213
Dan Gohman2048b852009-11-23 18:04:58 +00002214void SelectionDAGBuilder::visitSExt(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002215 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2216 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2217 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002218 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002219 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002220}
2221
Dan Gohman2048b852009-11-23 18:04:58 +00002222void SelectionDAGBuilder::visitFPTrunc(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002223 // FPTrunc is never a no-op cast, no need to check
2224 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002225 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002226 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2227 DestVT, N, DAG.getIntPtrConstant(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002228}
2229
Dan Gohman2048b852009-11-23 18:04:58 +00002230void SelectionDAGBuilder::visitFPExt(User &I){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002231 // FPTrunc 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_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002235}
2236
Dan Gohman2048b852009-11-23 18:04:58 +00002237void SelectionDAGBuilder::visitFPToUI(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002238 // FPToUI 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::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002242}
2243
Dan Gohman2048b852009-11-23 18:04:58 +00002244void SelectionDAGBuilder::visitFPToSI(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002245 // FPToSI is never a no-op cast, no need to check
2246 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::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002249}
2250
Dan Gohman2048b852009-11-23 18:04:58 +00002251void SelectionDAGBuilder::visitUIToFP(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002252 // UIToFP is never a no-op cast, no need to check
2253 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002254 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002255 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002256}
2257
Dan Gohman2048b852009-11-23 18:04:58 +00002258void SelectionDAGBuilder::visitSIToFP(User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002259 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002260 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002261 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002262 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002263}
2264
Dan Gohman2048b852009-11-23 18:04:58 +00002265void SelectionDAGBuilder::visitPtrToInt(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002266 // What to do depends on the size of the integer and the size of the pointer.
2267 // We can either truncate, zero extend, or no-op, accordingly.
2268 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002269 EVT SrcVT = N.getValueType();
2270 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002271 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002272}
2273
Dan Gohman2048b852009-11-23 18:04:58 +00002274void SelectionDAGBuilder::visitIntToPtr(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002275 // What to do depends on the size of the integer and the size of the pointer.
2276 // We can either truncate, zero extend, or no-op, accordingly.
2277 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002278 EVT SrcVT = N.getValueType();
2279 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendling4533cac2010-01-28 21:51:40 +00002280 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002281}
2282
Dan Gohman2048b852009-11-23 18:04:58 +00002283void SelectionDAGBuilder::visitBitCast(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002284 SDValue N = getValue(I.getOperand(0));
Owen Andersone50ed302009-08-10 22:56:29 +00002285 EVT DestVT = TLI.getValueType(I.getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002286
Bill Wendling49fcff82009-12-21 22:30:11 +00002287 // BitCast assures us that source and destination are the same size so this is
2288 // either a BIT_CONVERT or a no-op.
Bill Wendling4533cac2010-01-28 21:51:40 +00002289 if (DestVT != N.getValueType())
2290 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
2291 DestVT, N)); // convert types.
2292 else
Bill Wendling49fcff82009-12-21 22:30:11 +00002293 setValue(&I, N); // noop cast.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002294}
2295
Dan Gohman2048b852009-11-23 18:04:58 +00002296void SelectionDAGBuilder::visitInsertElement(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002297 SDValue InVec = getValue(I.getOperand(0));
2298 SDValue InVal = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002299 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00002300 TLI.getPointerTy(),
2301 getValue(I.getOperand(2)));
Bill Wendling4533cac2010-01-28 21:51:40 +00002302 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2303 TLI.getValueType(I.getType()),
2304 InVec, InVal, InIdx));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002305}
2306
Dan Gohman2048b852009-11-23 18:04:58 +00002307void SelectionDAGBuilder::visitExtractElement(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002308 SDValue InVec = getValue(I.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00002309 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Bill Wendling87710f02009-12-21 23:47:40 +00002310 TLI.getPointerTy(),
2311 getValue(I.getOperand(1)));
Bill Wendling4533cac2010-01-28 21:51:40 +00002312 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2313 TLI.getValueType(I.getType()), InVec, InIdx));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002314}
2315
Mon P Wangaeb06d22008-11-10 04:46:22 +00002316// Utility for visitShuffleVector - Returns true if the mask is mask starting
2317// from SIndx and increasing to the element length (undefs are allowed).
Nate Begeman5a5ca152009-04-29 05:20:52 +00002318static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2319 unsigned MaskNumElts = Mask.size();
2320 for (unsigned i = 0; i != MaskNumElts; ++i)
2321 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
Nate Begeman9008ca62009-04-27 18:41:29 +00002322 return false;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002323 return true;
2324}
2325
Dan Gohman2048b852009-11-23 18:04:58 +00002326void SelectionDAGBuilder::visitShuffleVector(User &I) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002327 SmallVector<int, 8> Mask;
Mon P Wang230e4fa2008-11-21 04:25:21 +00002328 SDValue Src1 = getValue(I.getOperand(0));
2329 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002330
Nate Begeman9008ca62009-04-27 18:41:29 +00002331 // Convert the ConstantVector mask operand into an array of ints, with -1
2332 // representing undef values.
2333 SmallVector<Constant*, 8> MaskElts;
Chris Lattnerb29d5962010-02-01 20:48:08 +00002334 cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
Nate Begeman5a5ca152009-04-29 05:20:52 +00002335 unsigned MaskNumElts = MaskElts.size();
2336 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002337 if (isa<UndefValue>(MaskElts[i]))
2338 Mask.push_back(-1);
2339 else
2340 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2341 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002342
Owen Andersone50ed302009-08-10 22:56:29 +00002343 EVT VT = TLI.getValueType(I.getType());
2344 EVT SrcVT = Src1.getValueType();
Nate Begeman5a5ca152009-04-29 05:20:52 +00002345 unsigned SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002346
Mon P Wangc7849c22008-11-16 05:06:27 +00002347 if (SrcNumElts == MaskNumElts) {
Bill Wendling4533cac2010-01-28 21:51:40 +00002348 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2349 &Mask[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002350 return;
2351 }
2352
2353 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002354 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2355 // Mask is longer than the source vectors and is a multiple of the source
2356 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang230e4fa2008-11-21 04:25:21 +00002357 // lengths match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002358 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2359 // The shuffle is concatenating two vectors together.
Bill Wendling4533cac2010-01-28 21:51:40 +00002360 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2361 VT, Src1, Src2));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002362 return;
2363 }
2364
Mon P Wangc7849c22008-11-16 05:06:27 +00002365 // Pad both vectors with undefs to make them the same length as the mask.
2366 unsigned NumConcat = MaskNumElts / SrcNumElts;
Nate Begeman9008ca62009-04-27 18:41:29 +00002367 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2368 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
Dale Johannesene8d72302009-02-06 23:05:02 +00002369 SDValue UndefVal = DAG.getUNDEF(SrcVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002370
Nate Begeman9008ca62009-04-27 18:41:29 +00002371 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2372 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002373 MOps1[0] = Src1;
2374 MOps2[0] = Src2;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002375
2376 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2377 getCurDebugLoc(), VT,
Nate Begeman9008ca62009-04-27 18:41:29 +00002378 &MOps1[0], NumConcat);
2379 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002380 getCurDebugLoc(), VT,
Nate Begeman9008ca62009-04-27 18:41:29 +00002381 &MOps2[0], NumConcat);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002382
Mon P Wangaeb06d22008-11-10 04:46:22 +00002383 // Readjust mask for new input vector length.
Nate Begeman9008ca62009-04-27 18:41:29 +00002384 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002385 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002386 int Idx = Mask[i];
Nate Begeman5a5ca152009-04-29 05:20:52 +00002387 if (Idx < (int)SrcNumElts)
Nate Begeman9008ca62009-04-27 18:41:29 +00002388 MappedOps.push_back(Idx);
2389 else
2390 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002391 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002392
Bill Wendling4533cac2010-01-28 21:51:40 +00002393 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2394 &MappedOps[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002395 return;
2396 }
2397
Mon P Wangc7849c22008-11-16 05:06:27 +00002398 if (SrcNumElts > MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002399 // Analyze the access pattern of the vector to see if we can extract
2400 // two subvectors and do the shuffle. The analysis is done by calculating
2401 // the range of elements the mask access on both vectors.
2402 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2403 int MaxRange[2] = {-1, -1};
2404
Nate Begeman5a5ca152009-04-29 05:20:52 +00002405 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002406 int Idx = Mask[i];
2407 int Input = 0;
2408 if (Idx < 0)
2409 continue;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002410
Nate Begeman5a5ca152009-04-29 05:20:52 +00002411 if (Idx >= (int)SrcNumElts) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002412 Input = 1;
2413 Idx -= SrcNumElts;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002414 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002415 if (Idx > MaxRange[Input])
2416 MaxRange[Input] = Idx;
2417 if (Idx < MinRange[Input])
2418 MinRange[Input] = Idx;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002419 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002420
Mon P Wangc7849c22008-11-16 05:06:27 +00002421 // Check if the access is smaller than the vector size and can we find
2422 // a reasonable extract index.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002423 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not
2424 // Extract.
Mon P Wangc7849c22008-11-16 05:06:27 +00002425 int StartIdx[2]; // StartIdx to extract from
2426 for (int Input=0; Input < 2; ++Input) {
Nate Begeman5a5ca152009-04-29 05:20:52 +00002427 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002428 RangeUse[Input] = 0; // Unused
2429 StartIdx[Input] = 0;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002430 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002431 // Fits within range but we should see if we can find a good
Mon P Wang230e4fa2008-11-21 04:25:21 +00002432 // start index that is a multiple of the mask length.
Nate Begeman5a5ca152009-04-29 05:20:52 +00002433 if (MaxRange[Input] < (int)MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002434 RangeUse[Input] = 1; // Extract from beginning of the vector
2435 StartIdx[Input] = 0;
2436 } else {
2437 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002438 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002439 StartIdx[Input] + MaskNumElts < SrcNumElts)
Mon P Wangc7849c22008-11-16 05:06:27 +00002440 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002441 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002442 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002443 }
2444
Bill Wendling636e2582009-08-21 18:16:06 +00002445 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
Bill Wendling4533cac2010-01-28 21:51:40 +00002446 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
Mon P Wangc7849c22008-11-16 05:06:27 +00002447 return;
2448 }
2449 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2450 // Extract appropriate subvector and generate a vector shuffle
2451 for (int Input=0; Input < 2; ++Input) {
Bill Wendling87710f02009-12-21 23:47:40 +00002452 SDValue &Src = Input == 0 ? Src1 : Src2;
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002453 if (RangeUse[Input] == 0)
Dale Johannesene8d72302009-02-06 23:05:02 +00002454 Src = DAG.getUNDEF(VT);
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002455 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00002456 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002457 Src, DAG.getIntPtrConstant(StartIdx[Input]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002458 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002459
Mon P Wangc7849c22008-11-16 05:06:27 +00002460 // Calculate new mask.
Nate Begeman9008ca62009-04-27 18:41:29 +00002461 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002462 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002463 int Idx = Mask[i];
2464 if (Idx < 0)
2465 MappedOps.push_back(Idx);
Nate Begeman5a5ca152009-04-29 05:20:52 +00002466 else if (Idx < (int)SrcNumElts)
Nate Begeman9008ca62009-04-27 18:41:29 +00002467 MappedOps.push_back(Idx - StartIdx[0]);
2468 else
2469 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
Mon P Wangc7849c22008-11-16 05:06:27 +00002470 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002471
Bill Wendling4533cac2010-01-28 21:51:40 +00002472 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2473 &MappedOps[0]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002474 return;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002475 }
2476 }
2477
Mon P Wangc7849c22008-11-16 05:06:27 +00002478 // We can't use either concat vectors or extract subvectors so fall back to
2479 // replacing the shuffle with extract and build vector.
2480 // to insert and build vector.
Owen Andersone50ed302009-08-10 22:56:29 +00002481 EVT EltVT = VT.getVectorElementType();
2482 EVT PtrVT = TLI.getPointerTy();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002483 SmallVector<SDValue,8> Ops;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002484 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002485 if (Mask[i] < 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002486 Ops.push_back(DAG.getUNDEF(EltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002487 } else {
Nate Begeman9008ca62009-04-27 18:41:29 +00002488 int Idx = Mask[i];
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002489 SDValue Res;
2490
Nate Begeman5a5ca152009-04-29 05:20:52 +00002491 if (Idx < (int)SrcNumElts)
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002492 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2493 EltVT, Src1, DAG.getConstant(Idx, PtrVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002494 else
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002495 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2496 EltVT, Src2,
2497 DAG.getConstant(Idx - SrcNumElts, PtrVT));
2498
2499 Ops.push_back(Res);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002500 }
2501 }
Bill Wendlingb85b6e82009-12-21 22:42:14 +00002502
Bill Wendling4533cac2010-01-28 21:51:40 +00002503 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2504 VT, &Ops[0], Ops.size()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002505}
2506
Dan Gohman2048b852009-11-23 18:04:58 +00002507void SelectionDAGBuilder::visitInsertValue(InsertValueInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002508 const Value *Op0 = I.getOperand(0);
2509 const Value *Op1 = I.getOperand(1);
2510 const Type *AggTy = I.getType();
2511 const Type *ValTy = Op1->getType();
2512 bool IntoUndef = isa<UndefValue>(Op0);
2513 bool FromUndef = isa<UndefValue>(Op1);
2514
2515 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2516 I.idx_begin(), I.idx_end());
2517
Owen Andersone50ed302009-08-10 22:56:29 +00002518 SmallVector<EVT, 4> AggValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002519 ComputeValueVTs(TLI, AggTy, AggValueVTs);
Owen Andersone50ed302009-08-10 22:56:29 +00002520 SmallVector<EVT, 4> ValValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002521 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2522
2523 unsigned NumAggValues = AggValueVTs.size();
2524 unsigned NumValValues = ValValueVTs.size();
2525 SmallVector<SDValue, 4> Values(NumAggValues);
2526
2527 SDValue Agg = getValue(Op0);
2528 SDValue Val = getValue(Op1);
2529 unsigned i = 0;
2530 // Copy the beginning value(s) from the original aggregate.
2531 for (; i != LinearIndex; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002532 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002533 SDValue(Agg.getNode(), Agg.getResNo() + i);
2534 // Copy values from the inserted value(s).
2535 for (; i != LinearIndex + NumValValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002536 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002537 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2538 // Copy remaining value(s) from the original aggregate.
2539 for (; i != NumAggValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002540 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002541 SDValue(Agg.getNode(), Agg.getResNo() + i);
2542
Bill Wendling4533cac2010-01-28 21:51:40 +00002543 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2544 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2545 &Values[0], NumAggValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002546}
2547
Dan Gohman2048b852009-11-23 18:04:58 +00002548void SelectionDAGBuilder::visitExtractValue(ExtractValueInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002549 const Value *Op0 = I.getOperand(0);
2550 const Type *AggTy = Op0->getType();
2551 const Type *ValTy = I.getType();
2552 bool OutOfUndef = isa<UndefValue>(Op0);
2553
2554 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2555 I.idx_begin(), I.idx_end());
2556
Owen Andersone50ed302009-08-10 22:56:29 +00002557 SmallVector<EVT, 4> ValValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002558 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2559
2560 unsigned NumValValues = ValValueVTs.size();
2561 SmallVector<SDValue, 4> Values(NumValValues);
2562
2563 SDValue Agg = getValue(Op0);
2564 // Copy out the selected value(s).
2565 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2566 Values[i - LinearIndex] =
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002567 OutOfUndef ?
Dale Johannesene8d72302009-02-06 23:05:02 +00002568 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002569 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002570
Bill Wendling4533cac2010-01-28 21:51:40 +00002571 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2572 DAG.getVTList(&ValValueVTs[0], NumValValues),
2573 &Values[0], NumValValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002574}
2575
Dan Gohman2048b852009-11-23 18:04:58 +00002576void SelectionDAGBuilder::visitGetElementPtr(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002577 SDValue N = getValue(I.getOperand(0));
2578 const Type *Ty = I.getOperand(0)->getType();
2579
2580 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2581 OI != E; ++OI) {
2582 Value *Idx = *OI;
2583 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2584 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2585 if (Field) {
2586 // N = N + Offset
2587 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002588 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002589 DAG.getIntPtrConstant(Offset));
2590 }
Bill Wendlinge1a90422009-12-21 23:10:19 +00002591
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002592 Ty = StTy->getElementType(Field);
Chris Lattner93b122d2010-03-16 21:25:55 +00002593 } else if (const UnionType *UnTy = dyn_cast<UnionType>(Ty)) {
2594 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2595
2596 // Offset canonically 0 for unions, but type changes
2597 Ty = UnTy->getElementType(Field);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002598 } else {
2599 Ty = cast<SequentialType>(Ty)->getElementType();
2600
2601 // If this is a constant subscript, handle it quickly.
2602 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2603 if (CI->getZExtValue() == 0) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002604 uint64_t Offs =
Duncan Sands777d2302009-05-09 07:06:46 +00002605 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Evan Cheng65b52df2009-02-09 21:01:06 +00002606 SDValue OffsVal;
Owen Andersone50ed302009-08-10 22:56:29 +00002607 EVT PTy = TLI.getPointerTy();
Owen Anderson77547be2009-08-10 18:56:59 +00002608 unsigned PtrBits = PTy.getSizeInBits();
Bill Wendlinge1a90422009-12-21 23:10:19 +00002609 if (PtrBits < 64)
Evan Cheng65b52df2009-02-09 21:01:06 +00002610 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2611 TLI.getPointerTy(),
Owen Anderson825b72b2009-08-11 20:47:22 +00002612 DAG.getConstant(Offs, MVT::i64));
Bill Wendlinge1a90422009-12-21 23:10:19 +00002613 else
Evan Chengb1032a82009-02-09 20:54:38 +00002614 OffsVal = DAG.getIntPtrConstant(Offs);
Bill Wendlinge1a90422009-12-21 23:10:19 +00002615
Dale Johannesen66978ee2009-01-31 02:22:37 +00002616 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Evan Chengb1032a82009-02-09 20:54:38 +00002617 OffsVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002618 continue;
2619 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002620
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002621 // N = N + Idx * ElementSize;
Dan Gohman7abbd042009-10-23 17:57:43 +00002622 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
2623 TD->getTypeAllocSize(Ty));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002624 SDValue IdxN = getValue(Idx);
2625
2626 // If the index is smaller or larger than intptr_t, truncate or extend
2627 // it.
Duncan Sands3a66a682009-10-13 21:04:12 +00002628 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002629
2630 // If this is a multiply by a power of two, turn it into a shl
2631 // immediately. This is a very common case.
2632 if (ElementSize != 1) {
Dan Gohman7abbd042009-10-23 17:57:43 +00002633 if (ElementSize.isPowerOf2()) {
2634 unsigned Amt = ElementSize.logBase2();
Scott Michelfdc40a02009-02-17 22:15:04 +00002635 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002636 N.getValueType(), IdxN,
Duncan Sands92abc622009-01-31 15:50:11 +00002637 DAG.getConstant(Amt, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002638 } else {
Dan Gohman7abbd042009-10-23 17:57:43 +00002639 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
Scott Michelfdc40a02009-02-17 22:15:04 +00002640 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002641 N.getValueType(), IdxN, Scale);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002642 }
2643 }
2644
Scott Michelfdc40a02009-02-17 22:15:04 +00002645 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002646 N.getValueType(), N, IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002647 }
2648 }
Bill Wendlinge1a90422009-12-21 23:10:19 +00002649
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002650 setValue(&I, N);
2651}
2652
Dan Gohman2048b852009-11-23 18:04:58 +00002653void SelectionDAGBuilder::visitAlloca(AllocaInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002654 // If this is a fixed sized alloca in the entry block of the function,
2655 // allocate it statically on the stack.
2656 if (FuncInfo.StaticAllocaMap.count(&I))
2657 return; // getValue will auto-populate this.
2658
2659 const Type *Ty = I.getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002660 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002661 unsigned Align =
2662 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2663 I.getAlignment());
2664
2665 SDValue AllocSize = getValue(I.getArraySize());
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002666
Chris Lattner0b18e592009-03-17 19:36:00 +00002667 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2668 AllocSize,
2669 DAG.getConstant(TySize, AllocSize.getValueType()));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002670
Owen Andersone50ed302009-08-10 22:56:29 +00002671 EVT IntPtr = TLI.getPointerTy();
Duncan Sands3a66a682009-10-13 21:04:12 +00002672 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00002673
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002674 // Handle alignment. If the requested alignment is less than or equal to
2675 // the stack alignment, ignore it. If the size is greater than or equal to
2676 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2677 unsigned StackAlign =
2678 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2679 if (Align <= StackAlign)
2680 Align = 0;
2681
2682 // Round the size of the allocation up to the stack alignment size
2683 // by add SA-1 to the size.
Scott Michelfdc40a02009-02-17 22:15:04 +00002684 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002685 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002686 DAG.getIntPtrConstant(StackAlign-1));
Bill Wendling856ff412009-12-22 00:12:37 +00002687
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002688 // Mask out the low bits for alignment purposes.
Scott Michelfdc40a02009-02-17 22:15:04 +00002689 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002690 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002691 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2692
2693 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Owen Anderson825b72b2009-08-11 20:47:22 +00002694 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
Scott Michelfdc40a02009-02-17 22:15:04 +00002695 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002696 VTs, Ops, 3);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002697 setValue(&I, DSA);
2698 DAG.setRoot(DSA.getValue(1));
Bill Wendling856ff412009-12-22 00:12:37 +00002699
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002700 // Inform the Frame Information that we have just allocated a variable-sized
2701 // object.
Dan Gohman0d24bfb2009-08-15 02:06:22 +00002702 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002703}
2704
Dan Gohman2048b852009-11-23 18:04:58 +00002705void SelectionDAGBuilder::visitLoad(LoadInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002706 const Value *SV = I.getOperand(0);
2707 SDValue Ptr = getValue(SV);
2708
2709 const Type *Ty = I.getType();
David Greene1e559442010-02-15 17:00:31 +00002710
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002711 bool isVolatile = I.isVolatile();
David Greene1e559442010-02-15 17:00:31 +00002712 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002713 unsigned Alignment = I.getAlignment();
2714
Owen Andersone50ed302009-08-10 22:56:29 +00002715 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002716 SmallVector<uint64_t, 4> Offsets;
2717 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2718 unsigned NumValues = ValueVTs.size();
2719 if (NumValues == 0)
2720 return;
2721
2722 SDValue Root;
2723 bool ConstantMemory = false;
2724 if (I.isVolatile())
2725 // Serialize volatile loads with other side effects.
2726 Root = getRoot();
2727 else if (AA->pointsToConstantMemory(SV)) {
2728 // Do not serialize (non-volatile) loads of constant memory with anything.
2729 Root = DAG.getEntryNode();
2730 ConstantMemory = true;
2731 } else {
2732 // Do not serialize non-volatile loads against each other.
2733 Root = DAG.getRoot();
2734 }
2735
2736 SmallVector<SDValue, 4> Values(NumValues);
2737 SmallVector<SDValue, 4> Chains(NumValues);
Owen Andersone50ed302009-08-10 22:56:29 +00002738 EVT PtrVT = Ptr.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002739 for (unsigned i = 0; i != NumValues; ++i) {
Bill Wendling856ff412009-12-22 00:12:37 +00002740 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2741 PtrVT, Ptr,
2742 DAG.getConstant(Offsets[i], PtrVT));
Dale Johannesen66978ee2009-01-31 02:22:37 +00002743 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
David Greene1e559442010-02-15 17:00:31 +00002744 A, SV, Offsets[i], isVolatile,
2745 isNonTemporal, Alignment);
Bill Wendling856ff412009-12-22 00:12:37 +00002746
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002747 Values[i] = L;
2748 Chains[i] = L.getValue(1);
2749 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002750
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002751 if (!ConstantMemory) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002752 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Bill Wendling856ff412009-12-22 00:12:37 +00002753 MVT::Other, &Chains[0], NumValues);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002754 if (isVolatile)
2755 DAG.setRoot(Chain);
2756 else
2757 PendingLoads.push_back(Chain);
2758 }
2759
Bill Wendling4533cac2010-01-28 21:51:40 +00002760 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2761 DAG.getVTList(&ValueVTs[0], NumValues),
2762 &Values[0], NumValues));
Bill Wendling856ff412009-12-22 00:12:37 +00002763}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002764
Dan Gohman2048b852009-11-23 18:04:58 +00002765void SelectionDAGBuilder::visitStore(StoreInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002766 Value *SrcV = I.getOperand(0);
2767 Value *PtrV = I.getOperand(1);
2768
Owen Andersone50ed302009-08-10 22:56:29 +00002769 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002770 SmallVector<uint64_t, 4> Offsets;
2771 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2772 unsigned NumValues = ValueVTs.size();
2773 if (NumValues == 0)
2774 return;
2775
2776 // Get the lowered operands. Note that we do this after
2777 // checking if NumResults is zero, because with zero results
2778 // the operands won't have values in the map.
2779 SDValue Src = getValue(SrcV);
2780 SDValue Ptr = getValue(PtrV);
2781
2782 SDValue Root = getRoot();
2783 SmallVector<SDValue, 4> Chains(NumValues);
Owen Andersone50ed302009-08-10 22:56:29 +00002784 EVT PtrVT = Ptr.getValueType();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002785 bool isVolatile = I.isVolatile();
David Greene1e559442010-02-15 17:00:31 +00002786 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002787 unsigned Alignment = I.getAlignment();
Bill Wendling856ff412009-12-22 00:12:37 +00002788
2789 for (unsigned i = 0; i != NumValues; ++i) {
2790 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
2791 DAG.getConstant(Offsets[i], PtrVT));
Dale Johannesen66978ee2009-01-31 02:22:37 +00002792 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002793 SDValue(Src.getNode(), Src.getResNo() + i),
David Greene1e559442010-02-15 17:00:31 +00002794 Add, PtrV, Offsets[i], isVolatile,
2795 isNonTemporal, Alignment);
Bill Wendling856ff412009-12-22 00:12:37 +00002796 }
2797
Bill Wendling4533cac2010-01-28 21:51:40 +00002798 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2799 MVT::Other, &Chains[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002800}
2801
2802/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2803/// node.
Dan Gohman2048b852009-11-23 18:04:58 +00002804void SelectionDAGBuilder::visitTargetIntrinsic(CallInst &I,
2805 unsigned Intrinsic) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002806 bool HasChain = !I.doesNotAccessMemory();
2807 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2808
2809 // Build the operand list.
2810 SmallVector<SDValue, 8> Ops;
2811 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2812 if (OnlyLoad) {
2813 // We don't need to serialize loads against other loads.
2814 Ops.push_back(DAG.getRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002815 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002816 Ops.push_back(getRoot());
2817 }
2818 }
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002819
2820 // Info is set by getTgtMemInstrinsic
2821 TargetLowering::IntrinsicInfo Info;
2822 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2823
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002824 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002825 if (!IsTgtIntrinsic)
2826 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002827
2828 // Add all operands of the call to the operand list.
2829 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2830 SDValue Op = getValue(I.getOperand(i));
2831 assert(TLI.isTypeLegal(Op.getValueType()) &&
2832 "Intrinsic uses a non-legal type?");
2833 Ops.push_back(Op);
2834 }
2835
Owen Andersone50ed302009-08-10 22:56:29 +00002836 SmallVector<EVT, 4> ValueVTs;
Bob Wilson8d919552009-07-31 22:41:21 +00002837 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2838#ifndef NDEBUG
2839 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
2840 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
2841 "Intrinsic uses a non-legal type?");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002842 }
Bob Wilson8d919552009-07-31 22:41:21 +00002843#endif // NDEBUG
Bill Wendling856ff412009-12-22 00:12:37 +00002844
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002845 if (HasChain)
Owen Anderson825b72b2009-08-11 20:47:22 +00002846 ValueVTs.push_back(MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002847
Bob Wilson8d919552009-07-31 22:41:21 +00002848 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002849
2850 // Create the node.
2851 SDValue Result;
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002852 if (IsTgtIntrinsic) {
2853 // This is target intrinsic that touches memory
Dale Johannesen66978ee2009-01-31 02:22:37 +00002854 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002855 VTs, &Ops[0], Ops.size(),
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002856 Info.memVT, Info.ptrVal, Info.offset,
2857 Info.align, Info.vol,
2858 Info.readMem, Info.writeMem);
Bill Wendling856ff412009-12-22 00:12:37 +00002859 } else if (!HasChain) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002860 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002861 VTs, &Ops[0], Ops.size());
Benjamin Kramerf0127052010-01-05 13:12:22 +00002862 } else if (!I.getType()->isVoidTy()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002863 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002864 VTs, &Ops[0], Ops.size());
Bill Wendling856ff412009-12-22 00:12:37 +00002865 } else {
Scott Michelfdc40a02009-02-17 22:15:04 +00002866 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002867 VTs, &Ops[0], Ops.size());
Bill Wendling856ff412009-12-22 00:12:37 +00002868 }
2869
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002870 if (HasChain) {
2871 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2872 if (OnlyLoad)
2873 PendingLoads.push_back(Chain);
2874 else
2875 DAG.setRoot(Chain);
2876 }
Bill Wendling856ff412009-12-22 00:12:37 +00002877
Benjamin Kramerf0127052010-01-05 13:12:22 +00002878 if (!I.getType()->isVoidTy()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002879 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
Owen Andersone50ed302009-08-10 22:56:29 +00002880 EVT VT = TLI.getValueType(PTy);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002881 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002882 }
Bill Wendling856ff412009-12-22 00:12:37 +00002883
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002884 setValue(&I, Result);
2885 }
2886}
2887
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002888/// GetSignificand - Get the significand and build it into a floating-point
2889/// number with exponent of 1:
2890///
2891/// Op = (Op & 0x007fffff) | 0x3f800000;
2892///
2893/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002894static SDValue
Bill Wendling46ada192010-03-02 01:55:18 +00002895GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
Owen Anderson825b72b2009-08-11 20:47:22 +00002896 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
2897 DAG.getConstant(0x007fffff, MVT::i32));
2898 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
2899 DAG.getConstant(0x3f800000, MVT::i32));
Bill Wendling4533cac2010-01-28 21:51:40 +00002900 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00002901}
2902
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002903/// GetExponent - Get the exponent:
2904///
Bill Wendlinge9a72862009-01-20 21:17:57 +00002905/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002906///
2907/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002908static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00002909GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
Bill Wendling46ada192010-03-02 01:55:18 +00002910 DebugLoc dl) {
Owen Anderson825b72b2009-08-11 20:47:22 +00002911 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
2912 DAG.getConstant(0x7f800000, MVT::i32));
2913 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
Duncan Sands92abc622009-01-31 15:50:11 +00002914 DAG.getConstant(23, TLI.getPointerTy()));
Owen Anderson825b72b2009-08-11 20:47:22 +00002915 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
2916 DAG.getConstant(127, MVT::i32));
Bill Wendling4533cac2010-01-28 21:51:40 +00002917 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00002918}
2919
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002920/// getF32Constant - Get 32-bit floating point constant.
2921static SDValue
2922getF32Constant(SelectionDAG &DAG, unsigned Flt) {
Owen Anderson825b72b2009-08-11 20:47:22 +00002923 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002924}
2925
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002926/// Inlined utility function to implement binary input atomic intrinsics for
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002927/// visitIntrinsicCall: I is a call instruction
2928/// Op is the associated NodeType for I
2929const char *
Dan Gohman2048b852009-11-23 18:04:58 +00002930SelectionDAGBuilder::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002931 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00002932 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00002933 DAG.getAtomic(Op, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002934 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00002935 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002936 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00002937 getValue(I.getOperand(2)),
2938 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002939 setValue(&I, L);
2940 DAG.setRoot(L.getValue(1));
2941 return 0;
2942}
2943
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002944// implVisitAluOverflow - Lower arithmetic overflow instrinsics.
Bill Wendling74c37652008-12-09 22:08:41 +00002945const char *
Dan Gohman2048b852009-11-23 18:04:58 +00002946SelectionDAGBuilder::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002947 SDValue Op1 = getValue(I.getOperand(1));
2948 SDValue Op2 = getValue(I.getOperand(2));
Bill Wendling74c37652008-12-09 22:08:41 +00002949
Owen Anderson825b72b2009-08-11 20:47:22 +00002950 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
Bill Wendling4533cac2010-01-28 21:51:40 +00002951 setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2));
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002952 return 0;
2953}
Bill Wendling74c37652008-12-09 22:08:41 +00002954
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002955/// visitExp - Lower an exp intrinsic. Handles the special sequences for
2956/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00002957void
Dan Gohman2048b852009-11-23 18:04:58 +00002958SelectionDAGBuilder::visitExp(CallInst &I) {
Dale Johannesen59e577f2008-09-05 18:38:42 +00002959 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00002960 DebugLoc dl = getCurDebugLoc();
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002961
Owen Anderson825b72b2009-08-11 20:47:22 +00002962 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002963 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2964 SDValue Op = getValue(I.getOperand(1));
2965
2966 // Put the exponent in the right bit position for later addition to the
2967 // final result:
2968 //
2969 // #define LOG2OFe 1.4426950f
2970 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
Owen Anderson825b72b2009-08-11 20:47:22 +00002971 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002972 getF32Constant(DAG, 0x3fb8aa3b));
Owen Anderson825b72b2009-08-11 20:47:22 +00002973 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002974
2975 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00002976 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
2977 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002978
2979 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00002980 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00002981 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendling856ff412009-12-22 00:12:37 +00002982
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002983 if (LimitFloatPrecision <= 6) {
2984 // For floating-point precision of 6:
2985 //
2986 // TwoToFractionalPartOfX =
2987 // 0.997535578f +
2988 // (0.735607626f + 0.252464424f * x) * x;
2989 //
2990 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00002991 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002992 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00002993 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002994 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00002995 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
2996 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002997 getF32Constant(DAG, 0x3f7f5e7e));
Owen Anderson825b72b2009-08-11 20:47:22 +00002998 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002999
3000 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00003001 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003002 TwoToFracPartOfX, IntegerPartOfX);
3003
Owen Anderson825b72b2009-08-11 20:47:22 +00003004 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003005 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3006 // For floating-point precision of 12:
3007 //
3008 // TwoToFractionalPartOfX =
3009 // 0.999892986f +
3010 // (0.696457318f +
3011 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3012 //
3013 // 0.000107046256 error, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003014 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003015 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003016 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003017 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003018 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3019 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003020 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00003021 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3022 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003023 getF32Constant(DAG, 0x3f7ff8fd));
Owen Anderson825b72b2009-08-11 20:47:22 +00003024 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003025
3026 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00003027 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003028 TwoToFracPartOfX, IntegerPartOfX);
3029
Owen Anderson825b72b2009-08-11 20:47:22 +00003030 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003031 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3032 // For floating-point precision of 18:
3033 //
3034 // TwoToFractionalPartOfX =
3035 // 0.999999982f +
3036 // (0.693148872f +
3037 // (0.240227044f +
3038 // (0.554906021e-1f +
3039 // (0.961591928e-2f +
3040 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3041 //
3042 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003043 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003044 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003045 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003046 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003047 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3048 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003049 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003050 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3051 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003052 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003053 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3054 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003055 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003056 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3057 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003058 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003059 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3060 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003061 getF32Constant(DAG, 0x3f800000));
Scott Michelfdc40a02009-02-17 22:15:04 +00003062 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003063 MVT::i32, t13);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003064
3065 // Add the exponent into the result in integer domain.
Owen Anderson825b72b2009-08-11 20:47:22 +00003066 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003067 TwoToFracPartOfX, IntegerPartOfX);
3068
Owen Anderson825b72b2009-08-11 20:47:22 +00003069 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003070 }
3071 } else {
3072 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003073 result = DAG.getNode(ISD::FEXP, dl,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003074 getValue(I.getOperand(1)).getValueType(),
3075 getValue(I.getOperand(1)));
3076 }
3077
Dale Johannesen59e577f2008-09-05 18:38:42 +00003078 setValue(&I, result);
3079}
3080
Bill Wendling39150252008-09-09 20:39:27 +00003081/// visitLog - Lower a log intrinsic. Handles the special sequences for
3082/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003083void
Dan Gohman2048b852009-11-23 18:04:58 +00003084SelectionDAGBuilder::visitLog(CallInst &I) {
Dale Johannesen59e577f2008-09-05 18:38:42 +00003085 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003086 DebugLoc dl = getCurDebugLoc();
Bill Wendling39150252008-09-09 20:39:27 +00003087
Owen Anderson825b72b2009-08-11 20:47:22 +00003088 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling39150252008-09-09 20:39:27 +00003089 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3090 SDValue Op = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003091 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling39150252008-09-09 20:39:27 +00003092
3093 // Scale the exponent by log(2) [0.69314718f].
Bill Wendling46ada192010-03-02 01:55:18 +00003094 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Owen Anderson825b72b2009-08-11 20:47:22 +00003095 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003096 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003097
3098 // Get the significand and build it into a floating-point number with
3099 // exponent of 1.
Bill Wendling46ada192010-03-02 01:55:18 +00003100 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling39150252008-09-09 20:39:27 +00003101
3102 if (LimitFloatPrecision <= 6) {
3103 // For floating-point precision of 6:
3104 //
3105 // LogofMantissa =
3106 // -1.1609546f +
3107 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003108 //
Bill Wendling39150252008-09-09 20:39:27 +00003109 // error 0.0034276066, which is better than 8 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003110 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003111 getF32Constant(DAG, 0xbe74c456));
Owen Anderson825b72b2009-08-11 20:47:22 +00003112 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003113 getF32Constant(DAG, 0x3fb3a2b1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003114 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3115 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003116 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00003117
Scott Michelfdc40a02009-02-17 22:15:04 +00003118 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003119 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003120 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3121 // For floating-point precision of 12:
3122 //
3123 // LogOfMantissa =
3124 // -1.7417939f +
3125 // (2.8212026f +
3126 // (-1.4699568f +
3127 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3128 //
3129 // error 0.000061011436, which is 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003130 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003131 getF32Constant(DAG, 0xbd67b6d6));
Owen Anderson825b72b2009-08-11 20:47:22 +00003132 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003133 getF32Constant(DAG, 0x3ee4f4b8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003134 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3135 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003136 getF32Constant(DAG, 0x3fbc278b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003137 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3138 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003139 getF32Constant(DAG, 0x40348e95));
Owen Anderson825b72b2009-08-11 20:47:22 +00003140 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3141 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003142 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00003143
Scott Michelfdc40a02009-02-17 22:15:04 +00003144 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003145 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003146 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3147 // For floating-point precision of 18:
3148 //
3149 // LogOfMantissa =
3150 // -2.1072184f +
3151 // (4.2372794f +
3152 // (-3.7029485f +
3153 // (2.2781945f +
3154 // (-0.87823314f +
3155 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3156 //
3157 // error 0.0000023660568, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003158 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003159 getF32Constant(DAG, 0xbc91e5ac));
Owen Anderson825b72b2009-08-11 20:47:22 +00003160 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003161 getF32Constant(DAG, 0x3e4350aa));
Owen Anderson825b72b2009-08-11 20:47:22 +00003162 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3163 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003164 getF32Constant(DAG, 0x3f60d3e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003165 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3166 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003167 getF32Constant(DAG, 0x4011cdf0));
Owen Anderson825b72b2009-08-11 20:47:22 +00003168 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3169 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003170 getF32Constant(DAG, 0x406cfd1c));
Owen Anderson825b72b2009-08-11 20:47:22 +00003171 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3172 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003173 getF32Constant(DAG, 0x408797cb));
Owen Anderson825b72b2009-08-11 20:47:22 +00003174 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3175 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003176 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003177
Scott Michelfdc40a02009-02-17 22:15:04 +00003178 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003179 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003180 }
3181 } else {
3182 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003183 result = DAG.getNode(ISD::FLOG, dl,
Bill Wendling39150252008-09-09 20:39:27 +00003184 getValue(I.getOperand(1)).getValueType(),
3185 getValue(I.getOperand(1)));
3186 }
3187
Dale Johannesen59e577f2008-09-05 18:38:42 +00003188 setValue(&I, result);
3189}
3190
Bill Wendling3eb59402008-09-09 00:28:24 +00003191/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3192/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003193void
Dan Gohman2048b852009-11-23 18:04:58 +00003194SelectionDAGBuilder::visitLog2(CallInst &I) {
Dale Johannesen59e577f2008-09-05 18:38:42 +00003195 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003196 DebugLoc dl = getCurDebugLoc();
Bill Wendling3eb59402008-09-09 00:28:24 +00003197
Owen Anderson825b72b2009-08-11 20:47:22 +00003198 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003199 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3200 SDValue Op = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003201 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003202
Bill Wendling39150252008-09-09 20:39:27 +00003203 // Get the exponent.
Bill Wendling46ada192010-03-02 01:55:18 +00003204 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
Bill Wendling856ff412009-12-22 00:12:37 +00003205
Bill Wendling3eb59402008-09-09 00:28:24 +00003206 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003207 // exponent of 1.
Bill Wendling46ada192010-03-02 01:55:18 +00003208 SDValue X = GetSignificand(DAG, Op1, dl);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003209
Bill Wendling3eb59402008-09-09 00:28:24 +00003210 // Different possible minimax approximations of significand in
3211 // floating-point for various degrees of accuracy over [1,2].
3212 if (LimitFloatPrecision <= 6) {
3213 // For floating-point precision of 6:
3214 //
3215 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3216 //
3217 // error 0.0049451742, which is more than 7 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003218 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003219 getF32Constant(DAG, 0xbeb08fe0));
Owen Anderson825b72b2009-08-11 20:47:22 +00003220 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003221 getF32Constant(DAG, 0x40019463));
Owen Anderson825b72b2009-08-11 20:47:22 +00003222 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3223 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003224 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003225
Scott Michelfdc40a02009-02-17 22:15:04 +00003226 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003227 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003228 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3229 // For floating-point precision of 12:
3230 //
3231 // Log2ofMantissa =
3232 // -2.51285454f +
3233 // (4.07009056f +
3234 // (-2.12067489f +
3235 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003236 //
Bill Wendling3eb59402008-09-09 00:28:24 +00003237 // error 0.0000876136000, which is better than 13 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003238 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003239 getF32Constant(DAG, 0xbda7262e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003240 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003241 getF32Constant(DAG, 0x3f25280b));
Owen Anderson825b72b2009-08-11 20:47:22 +00003242 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3243 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003244 getF32Constant(DAG, 0x4007b923));
Owen Anderson825b72b2009-08-11 20:47:22 +00003245 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3246 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003247 getF32Constant(DAG, 0x40823e2f));
Owen Anderson825b72b2009-08-11 20:47:22 +00003248 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3249 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003250 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003251
Scott Michelfdc40a02009-02-17 22:15:04 +00003252 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003253 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003254 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3255 // For floating-point precision of 18:
3256 //
3257 // Log2ofMantissa =
3258 // -3.0400495f +
3259 // (6.1129976f +
3260 // (-5.3420409f +
3261 // (3.2865683f +
3262 // (-1.2669343f +
3263 // (0.27515199f -
3264 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3265 //
3266 // error 0.0000018516, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003267 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003268 getF32Constant(DAG, 0xbcd2769e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003269 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003270 getF32Constant(DAG, 0x3e8ce0b9));
Owen Anderson825b72b2009-08-11 20:47:22 +00003271 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3272 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003273 getF32Constant(DAG, 0x3fa22ae7));
Owen Anderson825b72b2009-08-11 20:47:22 +00003274 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3275 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003276 getF32Constant(DAG, 0x40525723));
Owen Anderson825b72b2009-08-11 20:47:22 +00003277 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3278 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003279 getF32Constant(DAG, 0x40aaf200));
Owen Anderson825b72b2009-08-11 20:47:22 +00003280 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3281 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003282 getF32Constant(DAG, 0x40c39dad));
Owen Anderson825b72b2009-08-11 20:47:22 +00003283 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3284 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003285 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003286
Scott Michelfdc40a02009-02-17 22:15:04 +00003287 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003288 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003289 }
Dale Johannesen853244f2008-09-05 23:49:37 +00003290 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003291 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003292 result = DAG.getNode(ISD::FLOG2, dl,
Dale Johannesen853244f2008-09-05 23:49:37 +00003293 getValue(I.getOperand(1)).getValueType(),
3294 getValue(I.getOperand(1)));
3295 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003296
Dale Johannesen59e577f2008-09-05 18:38:42 +00003297 setValue(&I, result);
3298}
3299
Bill Wendling3eb59402008-09-09 00:28:24 +00003300/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3301/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003302void
Dan Gohman2048b852009-11-23 18:04:58 +00003303SelectionDAGBuilder::visitLog10(CallInst &I) {
Dale Johannesen59e577f2008-09-05 18:38:42 +00003304 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003305 DebugLoc dl = getCurDebugLoc();
Bill Wendling181b6272008-10-19 20:34:04 +00003306
Owen Anderson825b72b2009-08-11 20:47:22 +00003307 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003308 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3309 SDValue Op = getValue(I.getOperand(1));
Owen Anderson825b72b2009-08-11 20:47:22 +00003310 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003311
Bill Wendling39150252008-09-09 20:39:27 +00003312 // Scale the exponent by log10(2) [0.30102999f].
Bill Wendling46ada192010-03-02 01:55:18 +00003313 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Owen Anderson825b72b2009-08-11 20:47:22 +00003314 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003315 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003316
3317 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003318 // exponent of 1.
Bill Wendling46ada192010-03-02 01:55:18 +00003319 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00003320
3321 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003322 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003323 //
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003324 // Log10ofMantissa =
3325 // -0.50419619f +
3326 // (0.60948995f - 0.10380950f * x) * x;
3327 //
3328 // error 0.0014886165, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003329 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003330 getF32Constant(DAG, 0xbdd49a13));
Owen Anderson825b72b2009-08-11 20:47:22 +00003331 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003332 getF32Constant(DAG, 0x3f1c0789));
Owen Anderson825b72b2009-08-11 20:47:22 +00003333 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3334 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003335 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003336
Scott Michelfdc40a02009-02-17 22:15:04 +00003337 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003338 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003339 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3340 // For floating-point precision of 12:
3341 //
3342 // Log10ofMantissa =
3343 // -0.64831180f +
3344 // (0.91751397f +
3345 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3346 //
3347 // error 0.00019228036, which is better than 12 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, 0x3d431f31));
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, 0x3ea21fb2));
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, 0x3f6ae232));
Owen Anderson825b72b2009-08-11 20:47:22 +00003355 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3356 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003357 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00003358
Scott Michelfdc40a02009-02-17 22:15:04 +00003359 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003360 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003361 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003362 // For floating-point precision of 18:
3363 //
3364 // Log10ofMantissa =
3365 // -0.84299375f +
3366 // (1.5327582f +
3367 // (-1.0688956f +
3368 // (0.49102474f +
3369 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3370 //
3371 // error 0.0000037995730, which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003372 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003373 getF32Constant(DAG, 0x3c5d51ce));
Owen Anderson825b72b2009-08-11 20:47:22 +00003374 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003375 getF32Constant(DAG, 0x3e00685a));
Owen Anderson825b72b2009-08-11 20:47:22 +00003376 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3377 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003378 getF32Constant(DAG, 0x3efb6798));
Owen Anderson825b72b2009-08-11 20:47:22 +00003379 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3380 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003381 getF32Constant(DAG, 0x3f88d192));
Owen Anderson825b72b2009-08-11 20:47:22 +00003382 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3383 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003384 getF32Constant(DAG, 0x3fc4316c));
Owen Anderson825b72b2009-08-11 20:47:22 +00003385 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3386 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003387 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003388
Scott Michelfdc40a02009-02-17 22:15:04 +00003389 result = DAG.getNode(ISD::FADD, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003390 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003391 }
Dale Johannesen852680a2008-09-05 21:27:19 +00003392 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003393 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003394 result = DAG.getNode(ISD::FLOG10, dl,
Dale Johannesen852680a2008-09-05 21:27:19 +00003395 getValue(I.getOperand(1)).getValueType(),
3396 getValue(I.getOperand(1)));
3397 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003398
Dale Johannesen59e577f2008-09-05 18:38:42 +00003399 setValue(&I, result);
3400}
3401
Bill Wendlinge10c8142008-09-09 22:39:21 +00003402/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3403/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003404void
Dan Gohman2048b852009-11-23 18:04:58 +00003405SelectionDAGBuilder::visitExp2(CallInst &I) {
Dale Johannesen601d3c02008-09-05 01:48:15 +00003406 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003407 DebugLoc dl = getCurDebugLoc();
Bill Wendlinge10c8142008-09-09 22:39:21 +00003408
Owen Anderson825b72b2009-08-11 20:47:22 +00003409 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00003410 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3411 SDValue Op = getValue(I.getOperand(1));
3412
Owen Anderson825b72b2009-08-11 20:47:22 +00003413 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003414
3415 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00003416 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3417 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003418
3419 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00003420 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003421 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003422
3423 if (LimitFloatPrecision <= 6) {
3424 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003425 //
Bill Wendlinge10c8142008-09-09 22:39:21 +00003426 // TwoToFractionalPartOfX =
3427 // 0.997535578f +
3428 // (0.735607626f + 0.252464424f * x) * x;
3429 //
3430 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003431 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003432 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00003433 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003434 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003435 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3436 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003437 getF32Constant(DAG, 0x3f7f5e7e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003438 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003439 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003440 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003441
Scott Michelfdc40a02009-02-17 22:15:04 +00003442 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003443 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003444 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3445 // For floating-point precision of 12:
3446 //
3447 // TwoToFractionalPartOfX =
3448 // 0.999892986f +
3449 // (0.696457318f +
3450 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3451 //
3452 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003453 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003454 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003455 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003456 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003457 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3458 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003459 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00003460 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3461 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003462 getF32Constant(DAG, 0x3f7ff8fd));
Owen Anderson825b72b2009-08-11 20:47:22 +00003463 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003464 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003465 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003466
Scott Michelfdc40a02009-02-17 22:15:04 +00003467 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003468 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003469 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3470 // For floating-point precision of 18:
3471 //
3472 // TwoToFractionalPartOfX =
3473 // 0.999999982f +
3474 // (0.693148872f +
3475 // (0.240227044f +
3476 // (0.554906021e-1f +
3477 // (0.961591928e-2f +
3478 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3479 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003480 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003481 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003482 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003483 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003484 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3485 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003486 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003487 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3488 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003489 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003490 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3491 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003492 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003493 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3494 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003495 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003496 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3497 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003498 getF32Constant(DAG, 0x3f800000));
Owen Anderson825b72b2009-08-11 20:47:22 +00003499 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003500 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003501 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003502
Scott Michelfdc40a02009-02-17 22:15:04 +00003503 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003504 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003505 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00003506 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003507 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003508 result = DAG.getNode(ISD::FEXP2, dl,
Dale Johannesen601d3c02008-09-05 01:48:15 +00003509 getValue(I.getOperand(1)).getValueType(),
3510 getValue(I.getOperand(1)));
3511 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00003512
Dale Johannesen601d3c02008-09-05 01:48:15 +00003513 setValue(&I, result);
3514}
3515
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003516/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3517/// limited-precision mode with x == 10.0f.
3518void
Dan Gohman2048b852009-11-23 18:04:58 +00003519SelectionDAGBuilder::visitPow(CallInst &I) {
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003520 SDValue result;
3521 Value *Val = I.getOperand(1);
Dale Johannesen66978ee2009-01-31 02:22:37 +00003522 DebugLoc dl = getCurDebugLoc();
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003523 bool IsExp10 = false;
3524
Owen Anderson825b72b2009-08-11 20:47:22 +00003525 if (getValue(Val).getValueType() == MVT::f32 &&
3526 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003527 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3528 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3529 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3530 APFloat Ten(10.0f);
3531 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3532 }
3533 }
3534 }
3535
3536 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3537 SDValue Op = getValue(I.getOperand(2));
3538
3539 // Put the exponent in the right bit position for later addition to the
3540 // final result:
3541 //
3542 // #define LOG2OF10 3.3219281f
3543 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
Owen Anderson825b72b2009-08-11 20:47:22 +00003544 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003545 getF32Constant(DAG, 0x40549a78));
Owen Anderson825b72b2009-08-11 20:47:22 +00003546 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003547
3548 // FractionalPartOfX = x - (float)IntegerPartOfX;
Owen Anderson825b72b2009-08-11 20:47:22 +00003549 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3550 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003551
3552 // IntegerPartOfX <<= 23;
Owen Anderson825b72b2009-08-11 20:47:22 +00003553 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003554 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003555
3556 if (LimitFloatPrecision <= 6) {
3557 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003558 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003559 // twoToFractionalPartOfX =
3560 // 0.997535578f +
3561 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003562 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003563 // error 0.0144103317, which is 6 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003564 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003565 getF32Constant(DAG, 0x3e814304));
Owen Anderson825b72b2009-08-11 20:47:22 +00003566 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003567 getF32Constant(DAG, 0x3f3c50c8));
Owen Anderson825b72b2009-08-11 20:47:22 +00003568 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3569 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003570 getF32Constant(DAG, 0x3f7f5e7e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003571 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003572 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003573 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003574
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003575 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003576 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003577 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3578 // For floating-point precision of 12:
3579 //
3580 // TwoToFractionalPartOfX =
3581 // 0.999892986f +
3582 // (0.696457318f +
3583 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3584 //
3585 // error 0.000107046256, which is 13 to 14 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003586 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003587 getF32Constant(DAG, 0x3da235e3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003588 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003589 getF32Constant(DAG, 0x3e65b8f3));
Owen Anderson825b72b2009-08-11 20:47:22 +00003590 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3591 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003592 getF32Constant(DAG, 0x3f324b07));
Owen Anderson825b72b2009-08-11 20:47:22 +00003593 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3594 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003595 getF32Constant(DAG, 0x3f7ff8fd));
Owen Anderson825b72b2009-08-11 20:47:22 +00003596 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003597 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003598 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003599
Scott Michelfdc40a02009-02-17 22:15:04 +00003600 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003601 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003602 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3603 // For floating-point precision of 18:
3604 //
3605 // TwoToFractionalPartOfX =
3606 // 0.999999982f +
3607 // (0.693148872f +
3608 // (0.240227044f +
3609 // (0.554906021e-1f +
3610 // (0.961591928e-2f +
3611 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3612 // error 2.47208000*10^(-7), which is better than 18 bits
Owen Anderson825b72b2009-08-11 20:47:22 +00003613 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003614 getF32Constant(DAG, 0x3924b03e));
Owen Anderson825b72b2009-08-11 20:47:22 +00003615 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003616 getF32Constant(DAG, 0x3ab24b87));
Owen Anderson825b72b2009-08-11 20:47:22 +00003617 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3618 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003619 getF32Constant(DAG, 0x3c1d8c17));
Owen Anderson825b72b2009-08-11 20:47:22 +00003620 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3621 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003622 getF32Constant(DAG, 0x3d634a1d));
Owen Anderson825b72b2009-08-11 20:47:22 +00003623 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3624 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003625 getF32Constant(DAG, 0x3e75fe14));
Owen Anderson825b72b2009-08-11 20:47:22 +00003626 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3627 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003628 getF32Constant(DAG, 0x3f317234));
Owen Anderson825b72b2009-08-11 20:47:22 +00003629 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3630 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003631 getF32Constant(DAG, 0x3f800000));
Owen Anderson825b72b2009-08-11 20:47:22 +00003632 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003633 SDValue TwoToFractionalPartOfX =
Owen Anderson825b72b2009-08-11 20:47:22 +00003634 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003635
Scott Michelfdc40a02009-02-17 22:15:04 +00003636 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Owen Anderson825b72b2009-08-11 20:47:22 +00003637 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003638 }
3639 } else {
3640 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003641 result = DAG.getNode(ISD::FPOW, dl,
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003642 getValue(I.getOperand(1)).getValueType(),
3643 getValue(I.getOperand(1)),
3644 getValue(I.getOperand(2)));
3645 }
3646
3647 setValue(&I, result);
3648}
3649
Chris Lattnerf031e8a2010-01-01 03:32:16 +00003650
3651/// ExpandPowI - Expand a llvm.powi intrinsic.
3652static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS,
3653 SelectionDAG &DAG) {
3654 // If RHS is a constant, we can expand this out to a multiplication tree,
3655 // otherwise we end up lowering to a call to __powidf2 (for example). When
3656 // optimizing for size, we only want to do this if the expansion would produce
3657 // a small number of multiplies, otherwise we do the full expansion.
3658 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3659 // Get the exponent as a positive value.
3660 unsigned Val = RHSC->getSExtValue();
3661 if ((int)Val < 0) Val = -Val;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003662
Chris Lattnerf031e8a2010-01-01 03:32:16 +00003663 // powi(x, 0) -> 1.0
3664 if (Val == 0)
3665 return DAG.getConstantFP(1.0, LHS.getValueType());
3666
3667 Function *F = DAG.getMachineFunction().getFunction();
3668 if (!F->hasFnAttr(Attribute::OptimizeForSize) ||
3669 // If optimizing for size, don't insert too many multiplies. This
3670 // inserts up to 5 multiplies.
3671 CountPopulation_32(Val)+Log2_32(Val) < 7) {
3672 // We use the simple binary decomposition method to generate the multiply
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003673 // sequence. There are more optimal ways to do this (for example,
Chris Lattnerf031e8a2010-01-01 03:32:16 +00003674 // powi(x,15) generates one more multiply than it should), but this has
3675 // the benefit of being both really simple and much better than a libcall.
3676 SDValue Res; // Logically starts equal to 1.0
3677 SDValue CurSquare = LHS;
3678 while (Val) {
Mikhail Glushenkovbfdfea82010-01-01 04:41:36 +00003679 if (Val & 1) {
Chris Lattnerf031e8a2010-01-01 03:32:16 +00003680 if (Res.getNode())
3681 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
3682 else
3683 Res = CurSquare; // 1.0*CurSquare.
Mikhail Glushenkovbfdfea82010-01-01 04:41:36 +00003684 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003685
Chris Lattnerf031e8a2010-01-01 03:32:16 +00003686 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
3687 CurSquare, CurSquare);
3688 Val >>= 1;
3689 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003690
Chris Lattnerf031e8a2010-01-01 03:32:16 +00003691 // If the original was negative, invert the result, producing 1/(x*x*x).
3692 if (RHSC->getSExtValue() < 0)
3693 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
3694 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
3695 return Res;
3696 }
3697 }
3698
3699 // Otherwise, expand to a libcall.
3700 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
3701}
3702
3703
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003704/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3705/// we want to emit this as a call to a named external function, return the name
3706/// otherwise lower it and return null.
3707const char *
Dan Gohman2048b852009-11-23 18:04:58 +00003708SelectionDAGBuilder::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00003709 DebugLoc dl = getCurDebugLoc();
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003710 SDValue Res;
3711
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003712 switch (Intrinsic) {
3713 default:
3714 // By default, turn this into a target intrinsic node.
3715 visitTargetIntrinsic(I, Intrinsic);
3716 return 0;
3717 case Intrinsic::vastart: visitVAStart(I); return 0;
3718 case Intrinsic::vaend: visitVAEnd(I); return 0;
3719 case Intrinsic::vacopy: visitVACopy(I); return 0;
3720 case Intrinsic::returnaddress:
Bill Wendling4533cac2010-01-28 21:51:40 +00003721 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
3722 getValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003723 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00003724 case Intrinsic::frameaddress:
Bill Wendling4533cac2010-01-28 21:51:40 +00003725 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
3726 getValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003727 return 0;
3728 case Intrinsic::setjmp:
3729 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003730 case Intrinsic::longjmp:
3731 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
Chris Lattner824b9582008-11-21 16:42:48 +00003732 case Intrinsic::memcpy: {
Mon P Wang20adc9d2010-04-04 03:10:48 +00003733 // Assert for address < 256 since we support only user defined address
3734 // spaces.
3735 assert(cast<PointerType>(I.getOperand(1)->getType())->getAddressSpace()
3736 < 256 &&
3737 cast<PointerType>(I.getOperand(2)->getType())->getAddressSpace()
3738 < 256 &&
3739 "Unknown address space");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003740 SDValue Op1 = getValue(I.getOperand(1));
3741 SDValue Op2 = getValue(I.getOperand(2));
3742 SDValue Op3 = getValue(I.getOperand(3));
3743 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Mon P Wang20adc9d2010-04-04 03:10:48 +00003744 bool isVol = cast<ConstantInt>(I.getOperand(5))->getZExtValue();
3745 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol, false,
Bill Wendling4533cac2010-01-28 21:51:40 +00003746 I.getOperand(1), 0, I.getOperand(2), 0));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003747 return 0;
3748 }
Chris Lattner824b9582008-11-21 16:42:48 +00003749 case Intrinsic::memset: {
Mon P Wang20adc9d2010-04-04 03:10:48 +00003750 // Assert for address < 256 since we support only user defined address
3751 // spaces.
3752 assert(cast<PointerType>(I.getOperand(1)->getType())->getAddressSpace()
3753 < 256 &&
3754 "Unknown address space");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003755 SDValue Op1 = getValue(I.getOperand(1));
3756 SDValue Op2 = getValue(I.getOperand(2));
3757 SDValue Op3 = getValue(I.getOperand(3));
3758 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Mon P Wang20adc9d2010-04-04 03:10:48 +00003759 bool isVol = cast<ConstantInt>(I.getOperand(5))->getZExtValue();
3760 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
Bill Wendling4533cac2010-01-28 21:51:40 +00003761 I.getOperand(1), 0));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003762 return 0;
3763 }
Chris Lattner824b9582008-11-21 16:42:48 +00003764 case Intrinsic::memmove: {
Mon P Wang20adc9d2010-04-04 03:10:48 +00003765 // Assert for address < 256 since we support only user defined address
3766 // spaces.
3767 assert(cast<PointerType>(I.getOperand(1)->getType())->getAddressSpace()
3768 < 256 &&
3769 cast<PointerType>(I.getOperand(2)->getType())->getAddressSpace()
3770 < 256 &&
3771 "Unknown address space");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003772 SDValue Op1 = getValue(I.getOperand(1));
3773 SDValue Op2 = getValue(I.getOperand(2));
3774 SDValue Op3 = getValue(I.getOperand(3));
3775 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Mon P Wang20adc9d2010-04-04 03:10:48 +00003776 bool isVol = cast<ConstantInt>(I.getOperand(5))->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003777
3778 // If the source and destination are known to not be aliases, we can
3779 // lower memmove as memcpy.
3780 uint64_t Size = -1ULL;
3781 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003782 Size = C->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003783 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3784 AliasAnalysis::NoAlias) {
Mon P Wang20adc9d2010-04-04 03:10:48 +00003785 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
3786 false, I.getOperand(1), 0, I.getOperand(2), 0));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003787 return 0;
3788 }
3789
Mon P Wang20adc9d2010-04-04 03:10:48 +00003790 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
Bill Wendling4533cac2010-01-28 21:51:40 +00003791 I.getOperand(1), 0, I.getOperand(2), 0));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003792 return 0;
3793 }
Bill Wendling92c1e122009-02-13 02:16:35 +00003794 case Intrinsic::dbg_declare: {
Dale Johannesen904c2fa2010-02-01 19:54:53 +00003795 // FIXME: currently, we get here only if OptLevel != CodeGenOpt::None.
3796 // The real handling of this intrinsic is in FastISel.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003797 if (OptLevel != CodeGenOpt::None)
Devang Patel7e1e31f2009-07-02 22:43:26 +00003798 // FIXME: Variable debug info is not supported here.
3799 return 0;
Devang Patel7e1e31f2009-07-02 22:43:26 +00003800 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
Chris Lattnerbf0ca2b2009-12-29 09:32:19 +00003801 if (!DIDescriptor::ValidDebugInfo(DI.getVariable(), CodeGenOpt::None))
Devang Patel7e1e31f2009-07-02 22:43:26 +00003802 return 0;
3803
Devang Patelac1ceb32009-10-09 22:42:28 +00003804 MDNode *Variable = DI.getVariable();
Devang Patel24f20e02009-08-22 17:12:53 +00003805 Value *Address = DI.getAddress();
Dale Johannesen8ac38f22010-02-08 21:53:27 +00003806 if (!Address)
3807 return 0;
Devang Patel24f20e02009-08-22 17:12:53 +00003808 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
3809 Address = BCI->getOperand(0);
3810 AllocaInst *AI = dyn_cast<AllocaInst>(Address);
3811 // Don't handle byval struct arguments or VLAs, for example.
3812 if (!AI)
3813 return 0;
Devang Patelbd1d6a82009-09-05 00:34:14 +00003814 DenseMap<const AllocaInst*, int>::iterator SI =
3815 FuncInfo.StaticAllocaMap.find(AI);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00003816 if (SI == FuncInfo.StaticAllocaMap.end())
Devang Patelbd1d6a82009-09-05 00:34:14 +00003817 return 0; // VLAs.
3818 int FI = SI->second;
Devang Patel70d75ca2009-11-12 19:02:56 +00003819
Chris Lattner512063d2010-04-05 06:19:28 +00003820 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
3821 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
3822 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003823 return 0;
Bill Wendling92c1e122009-02-13 02:16:35 +00003824 }
Dale Johannesen904c2fa2010-02-01 19:54:53 +00003825 case Intrinsic::dbg_value: {
Dale Johannesen904c2fa2010-02-01 19:54:53 +00003826 DbgValueInst &DI = cast<DbgValueInst>(I);
3827 if (!DIDescriptor::ValidDebugInfo(DI.getVariable(), CodeGenOpt::None))
3828 return 0;
3829
3830 MDNode *Variable = DI.getVariable();
Devang Patel00190342010-03-15 19:15:44 +00003831 uint64_t Offset = DI.getOffset();
Dale Johannesen904c2fa2010-02-01 19:54:53 +00003832 Value *V = DI.getValue();
3833 if (!V)
3834 return 0;
Devang Patel00190342010-03-15 19:15:44 +00003835
3836 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
3837 // but do not always have a corresponding SDNode built. The SDNodeOrder
3838 // absolute, but not relative, values are different depending on whether
3839 // debug info exists.
3840 ++SDNodeOrder;
3841 if (isa<ConstantInt>(V) || isa<ConstantFP>(V)) {
Evan Cheng31441b72010-03-29 20:48:30 +00003842 DAG.AddDbgValue(DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder));
Devang Patel00190342010-03-15 19:15:44 +00003843 } else {
3844 SDValue &N = NodeMap[V];
Evan Cheng31441b72010-03-29 20:48:30 +00003845 if (N.getNode())
3846 DAG.AddDbgValue(DAG.getDbgValue(Variable, N.getNode(),
3847 N.getResNo(), Offset, dl, SDNodeOrder),
3848 N.getNode());
3849 else
Devang Patel00190342010-03-15 19:15:44 +00003850 // We may expand this to cover more cases. One case where we have no
3851 // data available is an unreferenced parameter; we need this fallback.
Evan Cheng31441b72010-03-29 20:48:30 +00003852 DAG.AddDbgValue(DAG.getDbgValue(Variable,
Devang Patel00190342010-03-15 19:15:44 +00003853 UndefValue::get(V->getType()),
Evan Cheng31441b72010-03-29 20:48:30 +00003854 Offset, dl, SDNodeOrder));
Devang Patel00190342010-03-15 19:15:44 +00003855 }
3856
3857 // Build a debug info table entry.
Dale Johannesen904c2fa2010-02-01 19:54:53 +00003858 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
3859 V = BCI->getOperand(0);
3860 AllocaInst *AI = dyn_cast<AllocaInst>(V);
3861 // Don't handle byval struct arguments or VLAs, for example.
3862 if (!AI)
3863 return 0;
3864 DenseMap<const AllocaInst*, int>::iterator SI =
3865 FuncInfo.StaticAllocaMap.find(AI);
3866 if (SI == FuncInfo.StaticAllocaMap.end())
3867 return 0; // VLAs.
3868 int FI = SI->second;
Chris Lattnerde4845c2010-04-02 19:42:39 +00003869
Chris Lattner512063d2010-04-05 06:19:28 +00003870 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
3871 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
3872 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
Dale Johannesen904c2fa2010-02-01 19:54:53 +00003873 return 0;
3874 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003875 case Intrinsic::eh_exception: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003876 // Insert the EXCEPTIONADDR instruction.
Duncan Sandsb0f1e172009-05-22 20:36:31 +00003877 assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!");
Owen Anderson825b72b2009-08-11 20:47:22 +00003878 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003879 SDValue Ops[1];
3880 Ops[0] = DAG.getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003881 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003882 setValue(&I, Op);
3883 DAG.setRoot(Op.getValue(1));
3884 return 0;
3885 }
3886
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00003887 case Intrinsic::eh_selector: {
Chris Lattner512063d2010-04-05 06:19:28 +00003888 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Chris Lattner3a5815f2009-09-17 23:54:54 +00003889 if (CurMBB->isLandingPad())
Chris Lattner512063d2010-04-05 06:19:28 +00003890 AddCatchInfo(I, &MMI, CurMBB);
Chris Lattner3a5815f2009-09-17 23:54:54 +00003891 else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003892#ifndef NDEBUG
Chris Lattner3a5815f2009-09-17 23:54:54 +00003893 FuncInfo.CatchInfoLost.insert(&I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003894#endif
Chris Lattner3a5815f2009-09-17 23:54:54 +00003895 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3896 unsigned Reg = TLI.getExceptionSelectorRegister();
3897 if (Reg) CurMBB->addLiveIn(Reg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003898 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003899
Chris Lattner3a5815f2009-09-17 23:54:54 +00003900 // Insert the EHSELECTION instruction.
3901 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3902 SDValue Ops[2];
3903 Ops[0] = getValue(I.getOperand(1));
3904 Ops[1] = getRoot();
3905 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
Chris Lattner3a5815f2009-09-17 23:54:54 +00003906 DAG.setRoot(Op.getValue(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00003907 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003908 return 0;
3909 }
3910
Duncan Sandsb01bbdc2009-10-14 16:11:37 +00003911 case Intrinsic::eh_typeid_for: {
Chris Lattner512063d2010-04-05 06:19:28 +00003912 // Find the type id for the given typeinfo.
3913 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3914 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
3915 Res = DAG.getConstant(TypeID, MVT::i32);
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003916 setValue(&I, Res);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003917 return 0;
3918 }
3919
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003920 case Intrinsic::eh_return_i32:
3921 case Intrinsic::eh_return_i64:
Chris Lattner512063d2010-04-05 06:19:28 +00003922 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
3923 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
3924 MVT::Other,
3925 getControlRoot(),
3926 getValue(I.getOperand(1)),
3927 getValue(I.getOperand(2))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003928 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003929 case Intrinsic::eh_unwind_init:
Chris Lattner512063d2010-04-05 06:19:28 +00003930 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003931 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003932 case Intrinsic::eh_dwarf_cfa: {
Owen Andersone50ed302009-08-10 22:56:29 +00003933 EVT VT = getValue(I.getOperand(1)).getValueType();
Duncan Sands3a66a682009-10-13 21:04:12 +00003934 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), dl,
3935 TLI.getPointerTy());
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003936 SDValue Offset = DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003937 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003938 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003939 TLI.getPointerTy()),
3940 CfaArg);
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003941 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003942 TLI.getPointerTy(),
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003943 DAG.getConstant(0, TLI.getPointerTy()));
Bill Wendling4533cac2010-01-28 21:51:40 +00003944 setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
3945 FA, Offset));
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003946 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003947 }
Jim Grosbachca752c92010-01-28 01:45:32 +00003948 case Intrinsic::eh_sjlj_callsite: {
Chris Lattner512063d2010-04-05 06:19:28 +00003949 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Jim Grosbachca752c92010-01-28 01:45:32 +00003950 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(1));
3951 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
Chris Lattner512063d2010-04-05 06:19:28 +00003952 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
Jim Grosbachca752c92010-01-28 01:45:32 +00003953
Chris Lattner512063d2010-04-05 06:19:28 +00003954 MMI.setCurrentCallSite(CI->getZExtValue());
Jim Grosbachca752c92010-01-28 01:45:32 +00003955 return 0;
3956 }
3957
Mon P Wang77cdf302008-11-10 20:54:11 +00003958 case Intrinsic::convertff:
3959 case Intrinsic::convertfsi:
3960 case Intrinsic::convertfui:
3961 case Intrinsic::convertsif:
3962 case Intrinsic::convertuif:
3963 case Intrinsic::convertss:
3964 case Intrinsic::convertsu:
3965 case Intrinsic::convertus:
3966 case Intrinsic::convertuu: {
3967 ISD::CvtCode Code = ISD::CVT_INVALID;
3968 switch (Intrinsic) {
3969 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
3970 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
3971 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
3972 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
3973 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
3974 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
3975 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
3976 case Intrinsic::convertus: Code = ISD::CVT_US; break;
3977 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
3978 }
Owen Andersone50ed302009-08-10 22:56:29 +00003979 EVT DestVT = TLI.getValueType(I.getType());
Bill Wendlingd0283fa2009-12-22 00:40:51 +00003980 Value *Op1 = I.getOperand(1);
3981 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
3982 DAG.getValueType(DestVT),
3983 DAG.getValueType(getValue(Op1).getValueType()),
3984 getValue(I.getOperand(2)),
3985 getValue(I.getOperand(3)),
3986 Code);
3987 setValue(&I, Res);
Mon P Wang77cdf302008-11-10 20:54:11 +00003988 return 0;
3989 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003990 case Intrinsic::sqrt:
Bill Wendling4533cac2010-01-28 21:51:40 +00003991 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
3992 getValue(I.getOperand(1)).getValueType(),
3993 getValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003994 return 0;
3995 case Intrinsic::powi:
Bill Wendling4533cac2010-01-28 21:51:40 +00003996 setValue(&I, ExpandPowI(dl, getValue(I.getOperand(1)),
3997 getValue(I.getOperand(2)), DAG));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003998 return 0;
3999 case Intrinsic::sin:
Bill Wendling4533cac2010-01-28 21:51:40 +00004000 setValue(&I, DAG.getNode(ISD::FSIN, dl,
4001 getValue(I.getOperand(1)).getValueType(),
4002 getValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004003 return 0;
4004 case Intrinsic::cos:
Bill Wendling4533cac2010-01-28 21:51:40 +00004005 setValue(&I, DAG.getNode(ISD::FCOS, dl,
4006 getValue(I.getOperand(1)).getValueType(),
4007 getValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004008 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004009 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004010 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004011 return 0;
4012 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004013 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004014 return 0;
4015 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004016 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004017 return 0;
4018 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004019 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004020 return 0;
4021 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00004022 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004023 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004024 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004025 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004026 return 0;
Anton Korobeynikovbe5b0322010-03-14 18:42:15 +00004027 case Intrinsic::convert_to_fp16:
4028 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, dl,
4029 MVT::i16, getValue(I.getOperand(1))));
4030 return 0;
4031 case Intrinsic::convert_from_fp16:
4032 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, dl,
4033 MVT::f32, getValue(I.getOperand(1))));
4034 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004035 case Intrinsic::pcmarker: {
4036 SDValue Tmp = getValue(I.getOperand(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00004037 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004038 return 0;
4039 }
4040 case Intrinsic::readcyclecounter: {
4041 SDValue Op = getRoot();
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004042 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4043 DAG.getVTList(MVT::i64, MVT::Other),
4044 &Op, 1);
4045 setValue(&I, Res);
4046 DAG.setRoot(Res.getValue(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004047 return 0;
4048 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004049 case Intrinsic::bswap:
Bill Wendling4533cac2010-01-28 21:51:40 +00004050 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
4051 getValue(I.getOperand(1)).getValueType(),
4052 getValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004053 return 0;
4054 case Intrinsic::cttz: {
4055 SDValue Arg = getValue(I.getOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00004056 EVT Ty = Arg.getValueType();
Bill Wendling4533cac2010-01-28 21:51:40 +00004057 setValue(&I, DAG.getNode(ISD::CTTZ, dl, Ty, Arg));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004058 return 0;
4059 }
4060 case Intrinsic::ctlz: {
4061 SDValue Arg = getValue(I.getOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00004062 EVT Ty = Arg.getValueType();
Bill Wendling4533cac2010-01-28 21:51:40 +00004063 setValue(&I, DAG.getNode(ISD::CTLZ, dl, Ty, Arg));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004064 return 0;
4065 }
4066 case Intrinsic::ctpop: {
4067 SDValue Arg = getValue(I.getOperand(1));
Owen Andersone50ed302009-08-10 22:56:29 +00004068 EVT Ty = Arg.getValueType();
Bill Wendling4533cac2010-01-28 21:51:40 +00004069 setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004070 return 0;
4071 }
4072 case Intrinsic::stacksave: {
4073 SDValue Op = getRoot();
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004074 Res = DAG.getNode(ISD::STACKSAVE, dl,
4075 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4076 setValue(&I, Res);
4077 DAG.setRoot(Res.getValue(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004078 return 0;
4079 }
4080 case Intrinsic::stackrestore: {
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004081 Res = getValue(I.getOperand(1));
Bill Wendling4533cac2010-01-28 21:51:40 +00004082 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004083 return 0;
4084 }
Bill Wendling57344502008-11-18 11:01:33 +00004085 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00004086 // Emit code into the DAG to store the stack guard onto the stack.
4087 MachineFunction &MF = DAG.getMachineFunction();
4088 MachineFrameInfo *MFI = MF.getFrameInfo();
Owen Andersone50ed302009-08-10 22:56:29 +00004089 EVT PtrTy = TLI.getPointerTy();
Bill Wendlingb2a42982008-11-06 02:29:10 +00004090
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004091 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4092 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
Bill Wendlingb2a42982008-11-06 02:29:10 +00004093
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004094 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00004095 MFI->setStackProtectorIndex(FI);
4096
4097 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4098
4099 // Store the stack protector onto the stack.
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004100 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4101 PseudoSourceValue::getFixedStack(FI),
David Greene1e559442010-02-15 17:00:31 +00004102 0, true, false, 0);
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004103 setValue(&I, Res);
4104 DAG.setRoot(Res);
Bill Wendlingb2a42982008-11-06 02:29:10 +00004105 return 0;
4106 }
Eric Christopher7b5e6172009-10-27 00:52:25 +00004107 case Intrinsic::objectsize: {
4108 // If we don't know by now, we're never going to know.
4109 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2));
4110
4111 assert(CI && "Non-constant type in __builtin_object_size?");
4112
Eric Christopher7e5d2ff2009-10-28 21:32:16 +00004113 SDValue Arg = getValue(I.getOperand(0));
4114 EVT Ty = Arg.getValueType();
4115
Eric Christopherd060b252009-12-23 02:51:48 +00004116 if (CI->getZExtValue() == 0)
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004117 Res = DAG.getConstant(-1ULL, Ty);
Eric Christopher7b5e6172009-10-27 00:52:25 +00004118 else
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004119 Res = DAG.getConstant(0, Ty);
4120
4121 setValue(&I, Res);
Eric Christopher7b5e6172009-10-27 00:52:25 +00004122 return 0;
4123 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004124 case Intrinsic::var_annotation:
4125 // Discard annotate attributes
4126 return 0;
4127
4128 case Intrinsic::init_trampoline: {
4129 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4130
4131 SDValue Ops[6];
4132 Ops[0] = getRoot();
4133 Ops[1] = getValue(I.getOperand(1));
4134 Ops[2] = getValue(I.getOperand(2));
4135 Ops[3] = getValue(I.getOperand(3));
4136 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4137 Ops[5] = DAG.getSrcValue(F);
4138
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004139 Res = DAG.getNode(ISD::TRAMPOLINE, dl,
4140 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4141 Ops, 6);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004142
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004143 setValue(&I, Res);
4144 DAG.setRoot(Res.getValue(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004145 return 0;
4146 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004147 case Intrinsic::gcroot:
4148 if (GFI) {
4149 Value *Alloca = I.getOperand(1);
4150 Constant *TypeMap = cast<Constant>(I.getOperand(2));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004151
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004152 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4153 GFI->addStackRoot(FI->getIndex(), TypeMap);
4154 }
4155 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004156 case Intrinsic::gcread:
4157 case Intrinsic::gcwrite:
Torok Edwinc23197a2009-07-14 16:55:14 +00004158 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004159 return 0;
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004160 case Intrinsic::flt_rounds:
Bill Wendling4533cac2010-01-28 21:51:40 +00004161 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004162 return 0;
Bill Wendlingd0283fa2009-12-22 00:40:51 +00004163 case Intrinsic::trap:
Bill Wendling4533cac2010-01-28 21:51:40 +00004164 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004165 return 0;
Bill Wendlingef375462008-11-21 02:38:44 +00004166 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00004167 return implVisitAluOverflow(I, ISD::UADDO);
4168 case Intrinsic::sadd_with_overflow:
4169 return implVisitAluOverflow(I, ISD::SADDO);
4170 case Intrinsic::usub_with_overflow:
4171 return implVisitAluOverflow(I, ISD::USUBO);
4172 case Intrinsic::ssub_with_overflow:
4173 return implVisitAluOverflow(I, ISD::SSUBO);
4174 case Intrinsic::umul_with_overflow:
4175 return implVisitAluOverflow(I, ISD::UMULO);
4176 case Intrinsic::smul_with_overflow:
4177 return implVisitAluOverflow(I, ISD::SMULO);
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004178
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004179 case Intrinsic::prefetch: {
4180 SDValue Ops[4];
4181 Ops[0] = getRoot();
4182 Ops[1] = getValue(I.getOperand(1));
4183 Ops[2] = getValue(I.getOperand(2));
4184 Ops[3] = getValue(I.getOperand(3));
Bill Wendling4533cac2010-01-28 21:51:40 +00004185 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004186 return 0;
4187 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004188
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004189 case Intrinsic::memory_barrier: {
4190 SDValue Ops[6];
4191 Ops[0] = getRoot();
4192 for (int x = 1; x < 6; ++x)
4193 Ops[x] = getValue(I.getOperand(x));
4194
Bill Wendling4533cac2010-01-28 21:51:40 +00004195 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004196 return 0;
4197 }
4198 case Intrinsic::atomic_cmp_swap: {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004199 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004200 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00004201 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004202 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4203 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004204 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004205 getValue(I.getOperand(2)),
4206 getValue(I.getOperand(3)),
4207 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004208 setValue(&I, L);
4209 DAG.setRoot(L.getValue(1));
4210 return 0;
4211 }
4212 case Intrinsic::atomic_load_add:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004213 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004214 case Intrinsic::atomic_load_sub:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004215 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004216 case Intrinsic::atomic_load_or:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004217 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004218 case Intrinsic::atomic_load_xor:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004219 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004220 case Intrinsic::atomic_load_and:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004221 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004222 case Intrinsic::atomic_load_nand:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004223 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004224 case Intrinsic::atomic_load_max:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004225 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004226 case Intrinsic::atomic_load_min:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004227 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004228 case Intrinsic::atomic_load_umin:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004229 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004230 case Intrinsic::atomic_load_umax:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004231 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004232 case Intrinsic::atomic_swap:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004233 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Duncan Sandsf07c9492009-11-10 09:08:09 +00004234
4235 case Intrinsic::invariant_start:
4236 case Intrinsic::lifetime_start:
4237 // Discard region information.
Bill Wendling4533cac2010-01-28 21:51:40 +00004238 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
Duncan Sandsf07c9492009-11-10 09:08:09 +00004239 return 0;
4240 case Intrinsic::invariant_end:
4241 case Intrinsic::lifetime_end:
4242 // Discard region information.
4243 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004244 }
4245}
4246
Dan Gohman98ca4f22009-08-05 01:29:28 +00004247/// Test if the given instruction is in a position to be optimized
4248/// with a tail-call. This roughly means that it's in a block with
4249/// a return and there's nothing that needs to be scheduled
4250/// between it and the return.
4251///
4252/// This function only tests target-independent requirements.
Dan Gohman98ca4f22009-08-05 01:29:28 +00004253static bool
Evan Cheng86809cc2010-02-03 03:28:02 +00004254isInTailCallPosition(CallSite CS, Attributes CalleeRetAttr,
Dan Gohman98ca4f22009-08-05 01:29:28 +00004255 const TargetLowering &TLI) {
Evan Cheng86809cc2010-02-03 03:28:02 +00004256 const Instruction *I = CS.getInstruction();
Dan Gohman98ca4f22009-08-05 01:29:28 +00004257 const BasicBlock *ExitBB = I->getParent();
4258 const TerminatorInst *Term = ExitBB->getTerminator();
4259 const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
4260 const Function *F = ExitBB->getParent();
4261
Dan Gohmanc2e93b22010-02-08 20:34:14 +00004262 // The block must end in a return statement or unreachable.
4263 //
4264 // FIXME: Decline tailcall if it's not guaranteed and if the block ends in
4265 // an unreachable, for now. The way tailcall optimization is currently
4266 // implemented means it will add an epilogue followed by a jump. That is
4267 // not profitable. Also, if the callee is a special function (e.g.
4268 // longjmp on x86), it can end up causing miscompilation that has not
4269 // been fully understood.
4270 if (!Ret &&
4271 (!GuaranteedTailCallOpt || !isa<UnreachableInst>(Term))) return false;
Dan Gohman98ca4f22009-08-05 01:29:28 +00004272
4273 // If I will have a chain, make sure no other instruction that will have a
4274 // chain interposes between I and the return.
4275 if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
4276 !I->isSafeToSpeculativelyExecute())
4277 for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
4278 --BBI) {
4279 if (&*BBI == I)
4280 break;
Devang Patel1ac24292010-03-18 16:41:16 +00004281 // Debug info intrinsics do not get in the way of tail call optimization.
Devang Patelc3188ce2010-03-17 23:52:37 +00004282 if (isa<DbgInfoIntrinsic>(BBI))
4283 continue;
Dan Gohman98ca4f22009-08-05 01:29:28 +00004284 if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
4285 !BBI->isSafeToSpeculativelyExecute())
4286 return false;
4287 }
4288
4289 // If the block ends with a void return or unreachable, it doesn't matter
4290 // what the call's return type is.
4291 if (!Ret || Ret->getNumOperands() == 0) return true;
4292
Dan Gohmaned9bab32009-11-14 02:06:30 +00004293 // If the return value is undef, it doesn't matter what the call's
4294 // return type is.
4295 if (isa<UndefValue>(Ret->getOperand(0))) return true;
4296
Dan Gohman98ca4f22009-08-05 01:29:28 +00004297 // Conservatively require the attributes of the call to match those of
Dan Gohman01205a82009-11-13 18:49:38 +00004298 // the return. Ignore noalias because it doesn't affect the call sequence.
4299 unsigned CallerRetAttr = F->getAttributes().getRetAttributes();
4300 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
Dan Gohman98ca4f22009-08-05 01:29:28 +00004301 return false;
4302
Evan Cheng6fdce652010-02-04 19:07:06 +00004303 // It's not safe to eliminate the sign / zero extension of the return value.
Evan Cheng446bc102010-02-04 02:45:02 +00004304 if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
4305 return false;
4306
Dan Gohman98ca4f22009-08-05 01:29:28 +00004307 // Otherwise, make sure the unmodified return value of I is the return value.
4308 for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ;
4309 U = dyn_cast<Instruction>(U->getOperand(0))) {
4310 if (!U)
4311 return false;
4312 if (!U->hasOneUse())
4313 return false;
4314 if (U == I)
4315 break;
4316 // Check for a truly no-op truncate.
4317 if (isa<TruncInst>(U) &&
4318 TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType()))
4319 continue;
4320 // Check for a truly no-op bitcast.
4321 if (isa<BitCastInst>(U) &&
4322 (U->getOperand(0)->getType() == U->getType() ||
Duncan Sands1df98592010-02-16 11:11:14 +00004323 (U->getOperand(0)->getType()->isPointerTy() &&
4324 U->getType()->isPointerTy())))
Dan Gohman98ca4f22009-08-05 01:29:28 +00004325 continue;
4326 // Otherwise it's not a true no-op.
4327 return false;
4328 }
4329
4330 return true;
4331}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004332
Dan Gohman2048b852009-11-23 18:04:58 +00004333void SelectionDAGBuilder::LowerCallTo(CallSite CS, SDValue Callee,
4334 bool isTailCall,
4335 MachineBasicBlock *LandingPad) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004336 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4337 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004338 const Type *RetTy = FTy->getReturnType();
Chris Lattner512063d2010-04-05 06:19:28 +00004339 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
Chris Lattner16112732010-03-14 01:41:15 +00004340 MCSymbol *BeginLabel = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004341
4342 TargetLowering::ArgListTy Args;
4343 TargetLowering::ArgListEntry Entry;
4344 Args.reserve(CS.arg_size());
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004345
4346 // Check whether the function can return without sret-demotion.
4347 SmallVector<EVT, 4> OutVTs;
4348 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
4349 SmallVector<uint64_t, 4> Offsets;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004350 getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
Bill Wendlinge80ae832009-12-22 00:50:32 +00004351 OutVTs, OutsFlags, TLI, &Offsets);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004352
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004353 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004354 FTy->isVarArg(), OutVTs, OutsFlags, DAG);
4355
4356 SDValue DemoteStackSlot;
4357
4358 if (!CanLowerReturn) {
4359 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
4360 FTy->getReturnType());
4361 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
4362 FTy->getReturnType());
4363 MachineFunction &MF = DAG.getMachineFunction();
David Greene3f2bf852009-11-12 20:49:22 +00004364 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004365 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
4366
4367 DemoteStackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4368 Entry.Node = DemoteStackSlot;
4369 Entry.Ty = StackSlotPtrType;
4370 Entry.isSExt = false;
4371 Entry.isZExt = false;
4372 Entry.isInReg = false;
4373 Entry.isSRet = true;
4374 Entry.isNest = false;
4375 Entry.isByVal = false;
4376 Entry.Alignment = Align;
4377 Args.push_back(Entry);
4378 RetTy = Type::getVoidTy(FTy->getContext());
4379 }
4380
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004381 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004382 i != e; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004383 SDValue ArgNode = getValue(*i);
4384 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4385
4386 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00004387 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4388 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4389 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4390 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4391 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4392 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004393 Entry.Alignment = CS.getParamAlignment(attrInd);
4394 Args.push_back(Entry);
4395 }
4396
Chris Lattner512063d2010-04-05 06:19:28 +00004397 if (LandingPad) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004398 // Insert a label before the invoke call to mark the try range. This can be
4399 // used to detect deletion of the invoke via the MachineModuleInfo.
Chris Lattner512063d2010-04-05 06:19:28 +00004400 BeginLabel = MMI.getContext().CreateTempSymbol();
Jim Grosbach1b747ad2009-08-11 00:09:57 +00004401
Jim Grosbachca752c92010-01-28 01:45:32 +00004402 // For SjLj, keep track of which landing pads go with which invokes
4403 // so as to maintain the ordering of pads in the LSDA.
Chris Lattner512063d2010-04-05 06:19:28 +00004404 unsigned CallSiteIndex = MMI.getCurrentCallSite();
Jim Grosbachca752c92010-01-28 01:45:32 +00004405 if (CallSiteIndex) {
Chris Lattner512063d2010-04-05 06:19:28 +00004406 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
Jim Grosbachca752c92010-01-28 01:45:32 +00004407 // Now that the call site is handled, stop tracking it.
Chris Lattner512063d2010-04-05 06:19:28 +00004408 MMI.setCurrentCallSite(0);
Jim Grosbachca752c92010-01-28 01:45:32 +00004409 }
4410
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004411 // Both PendingLoads and PendingExports must be flushed here;
4412 // this call might not return.
4413 (void)getRoot();
Chris Lattner7561d482010-03-14 02:33:54 +00004414 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getControlRoot(), BeginLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004415 }
4416
Dan Gohman98ca4f22009-08-05 01:29:28 +00004417 // Check if target-independent constraints permit a tail call here.
4418 // Target-dependent constraints are checked within TLI.LowerCallTo.
4419 if (isTailCall &&
Evan Cheng86809cc2010-02-03 03:28:02 +00004420 !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI))
Dan Gohman98ca4f22009-08-05 01:29:28 +00004421 isTailCall = false;
4422
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004423 std::pair<SDValue,SDValue> Result =
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004424 TLI.LowerCallTo(getRoot(), RetTy,
Devang Patel05988662008-09-25 21:00:45 +00004425 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004426 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
Tilmann Scheller6b61cd12009-07-03 06:44:53 +00004427 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004428 CS.getCallingConv(),
Dan Gohman98ca4f22009-08-05 01:29:28 +00004429 isTailCall,
4430 !CS.getInstruction()->use_empty(),
Bill Wendling46ada192010-03-02 01:55:18 +00004431 Callee, Args, DAG, getCurDebugLoc());
Dan Gohman98ca4f22009-08-05 01:29:28 +00004432 assert((isTailCall || Result.second.getNode()) &&
4433 "Non-null chain expected with non-tail call!");
4434 assert((Result.second.getNode() || !Result.first.getNode()) &&
4435 "Null value expected with tail call!");
Bill Wendlinge80ae832009-12-22 00:50:32 +00004436 if (Result.first.getNode()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004437 setValue(CS.getInstruction(), Result.first);
Bill Wendlinge80ae832009-12-22 00:50:32 +00004438 } else if (!CanLowerReturn && Result.second.getNode()) {
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004439 // The instruction result is the result of loading from the
4440 // hidden sret parameter.
4441 SmallVector<EVT, 1> PVTs;
4442 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
4443
4444 ComputeValueVTs(TLI, PtrRetTy, PVTs);
4445 assert(PVTs.size() == 1 && "Pointers should fit in one register");
4446 EVT PtrVT = PVTs[0];
4447 unsigned NumValues = OutVTs.size();
4448 SmallVector<SDValue, 4> Values(NumValues);
4449 SmallVector<SDValue, 4> Chains(NumValues);
4450
4451 for (unsigned i = 0; i < NumValues; ++i) {
Bill Wendlinge80ae832009-12-22 00:50:32 +00004452 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
4453 DemoteStackSlot,
4454 DAG.getConstant(Offsets[i], PtrVT));
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004455 SDValue L = DAG.getLoad(OutVTs[i], getCurDebugLoc(), Result.second,
David Greene1e559442010-02-15 17:00:31 +00004456 Add, NULL, Offsets[i], false, false, 1);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004457 Values[i] = L;
4458 Chains[i] = L.getValue(1);
4459 }
Bill Wendlinge80ae832009-12-22 00:50:32 +00004460
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004461 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
4462 MVT::Other, &Chains[0], NumValues);
4463 PendingLoads.push_back(Chain);
Kenneth Uildriks93ae4072010-01-16 23:37:33 +00004464
4465 // Collect the legal value parts into potentially illegal values
4466 // that correspond to the original function's return values.
4467 SmallVector<EVT, 4> RetTys;
4468 RetTy = FTy->getReturnType();
4469 ComputeValueVTs(TLI, RetTy, RetTys);
4470 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4471 SmallVector<SDValue, 4> ReturnValues;
4472 unsigned CurReg = 0;
4473 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4474 EVT VT = RetTys[I];
4475 EVT RegisterVT = TLI.getRegisterType(RetTy->getContext(), VT);
4476 unsigned NumRegs = TLI.getNumRegisters(RetTy->getContext(), VT);
4477
4478 SDValue ReturnValue =
Bill Wendling46ada192010-03-02 01:55:18 +00004479 getCopyFromParts(DAG, getCurDebugLoc(), &Values[CurReg], NumRegs,
Kenneth Uildriks93ae4072010-01-16 23:37:33 +00004480 RegisterVT, VT, AssertOp);
4481 ReturnValues.push_back(ReturnValue);
Kenneth Uildriks93ae4072010-01-16 23:37:33 +00004482 CurReg += NumRegs;
4483 }
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004484
Bill Wendling4533cac2010-01-28 21:51:40 +00004485 setValue(CS.getInstruction(),
4486 DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
4487 DAG.getVTList(&RetTys[0], RetTys.size()),
4488 &ReturnValues[0], ReturnValues.size()));
Bill Wendlinge80ae832009-12-22 00:50:32 +00004489
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00004490 }
Bill Wendlinge80ae832009-12-22 00:50:32 +00004491
4492 // As a special case, a null chain means that a tail call has been emitted and
4493 // the DAG root is already updated.
Bill Wendling4533cac2010-01-28 21:51:40 +00004494 if (Result.second.getNode())
Dan Gohman98ca4f22009-08-05 01:29:28 +00004495 DAG.setRoot(Result.second);
Bill Wendling4533cac2010-01-28 21:51:40 +00004496 else
Dan Gohman98ca4f22009-08-05 01:29:28 +00004497 HasTailCall = true;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004498
Chris Lattner512063d2010-04-05 06:19:28 +00004499 if (LandingPad) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004500 // Insert a label at the end of the invoke call to mark the try range. This
4501 // can be used to detect deletion of the invoke via the MachineModuleInfo.
Chris Lattner512063d2010-04-05 06:19:28 +00004502 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
Chris Lattner7561d482010-03-14 02:33:54 +00004503 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getRoot(), EndLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004504
4505 // Inform MachineModuleInfo of range.
Chris Lattner512063d2010-04-05 06:19:28 +00004506 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004507 }
4508}
4509
Chris Lattner8047d9a2009-12-24 00:37:38 +00004510/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
4511/// value is equal or not-equal to zero.
4512static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
4513 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
4514 UI != E; ++UI) {
4515 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
4516 if (IC->isEquality())
4517 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
4518 if (C->isNullValue())
4519 continue;
4520 // Unknown instruction.
4521 return false;
4522 }
4523 return true;
4524}
4525
Chris Lattner04b091a2009-12-24 01:07:17 +00004526static SDValue getMemCmpLoad(Value *PtrVal, MVT LoadVT, const Type *LoadTy,
Chris Lattner8047d9a2009-12-24 00:37:38 +00004527 SelectionDAGBuilder &Builder) {
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004528
Chris Lattner8047d9a2009-12-24 00:37:38 +00004529 // Check to see if this load can be trivially constant folded, e.g. if the
4530 // input is from a string literal.
4531 if (Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
4532 // Cast pointer to the type we really want to load.
4533 LoadInput = ConstantExpr::getBitCast(LoadInput,
4534 PointerType::getUnqual(LoadTy));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004535
Chris Lattner8047d9a2009-12-24 00:37:38 +00004536 if (Constant *LoadCst = ConstantFoldLoadFromConstPtr(LoadInput, Builder.TD))
4537 return Builder.getValue(LoadCst);
4538 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004539
Chris Lattner8047d9a2009-12-24 00:37:38 +00004540 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
4541 // still constant memory, the input chain can be the entry node.
4542 SDValue Root;
4543 bool ConstantMemory = false;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004544
Chris Lattner8047d9a2009-12-24 00:37:38 +00004545 // Do not serialize (non-volatile) loads of constant memory with anything.
4546 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
4547 Root = Builder.DAG.getEntryNode();
4548 ConstantMemory = true;
4549 } else {
4550 // Do not serialize non-volatile loads against each other.
4551 Root = Builder.DAG.getRoot();
4552 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004553
Chris Lattner8047d9a2009-12-24 00:37:38 +00004554 SDValue Ptr = Builder.getValue(PtrVal);
4555 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root,
4556 Ptr, PtrVal /*SrcValue*/, 0/*SVOffset*/,
David Greene1e559442010-02-15 17:00:31 +00004557 false /*volatile*/,
4558 false /*nontemporal*/, 1 /* align=1 */);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004559
Chris Lattner8047d9a2009-12-24 00:37:38 +00004560 if (!ConstantMemory)
4561 Builder.PendingLoads.push_back(LoadVal.getValue(1));
4562 return LoadVal;
4563}
4564
4565
4566/// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
4567/// If so, return true and lower it, otherwise return false and it will be
4568/// lowered like a normal call.
4569bool SelectionDAGBuilder::visitMemCmpCall(CallInst &I) {
4570 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
4571 if (I.getNumOperands() != 4)
4572 return false;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004573
Chris Lattner8047d9a2009-12-24 00:37:38 +00004574 Value *LHS = I.getOperand(1), *RHS = I.getOperand(2);
Duncan Sands1df98592010-02-16 11:11:14 +00004575 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
4576 !I.getOperand(3)->getType()->isIntegerTy() ||
4577 !I.getType()->isIntegerTy())
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004578 return false;
4579
Chris Lattner8047d9a2009-12-24 00:37:38 +00004580 ConstantInt *Size = dyn_cast<ConstantInt>(I.getOperand(3));
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004581
Chris Lattner8047d9a2009-12-24 00:37:38 +00004582 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
4583 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
Chris Lattner04b091a2009-12-24 01:07:17 +00004584 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) {
4585 bool ActuallyDoIt = true;
4586 MVT LoadVT;
4587 const Type *LoadTy;
4588 switch (Size->getZExtValue()) {
4589 default:
4590 LoadVT = MVT::Other;
4591 LoadTy = 0;
4592 ActuallyDoIt = false;
4593 break;
4594 case 2:
4595 LoadVT = MVT::i16;
4596 LoadTy = Type::getInt16Ty(Size->getContext());
4597 break;
4598 case 4:
4599 LoadVT = MVT::i32;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004600 LoadTy = Type::getInt32Ty(Size->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00004601 break;
4602 case 8:
4603 LoadVT = MVT::i64;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004604 LoadTy = Type::getInt64Ty(Size->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00004605 break;
4606 /*
4607 case 16:
4608 LoadVT = MVT::v4i32;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004609 LoadTy = Type::getInt32Ty(Size->getContext());
Chris Lattner04b091a2009-12-24 01:07:17 +00004610 LoadTy = VectorType::get(LoadTy, 4);
4611 break;
4612 */
4613 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004614
Chris Lattner04b091a2009-12-24 01:07:17 +00004615 // This turns into unaligned loads. We only do this if the target natively
4616 // supports the MVT we'll be loading or if it is small enough (<= 4) that
4617 // we'll only produce a small number of byte loads.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004618
Chris Lattner04b091a2009-12-24 01:07:17 +00004619 // Require that we can find a legal MVT, and only do this if the target
4620 // supports unaligned loads of that type. Expanding into byte loads would
4621 // bloat the code.
4622 if (ActuallyDoIt && Size->getZExtValue() > 4) {
4623 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
4624 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
4625 if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT))
4626 ActuallyDoIt = false;
4627 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004628
Chris Lattner04b091a2009-12-24 01:07:17 +00004629 if (ActuallyDoIt) {
4630 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
4631 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004632
Chris Lattner04b091a2009-12-24 01:07:17 +00004633 SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal,
4634 ISD::SETNE);
4635 EVT CallVT = TLI.getValueType(I.getType(), true);
4636 setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT));
4637 return true;
4638 }
Chris Lattner8047d9a2009-12-24 00:37:38 +00004639 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004640
4641
Chris Lattner8047d9a2009-12-24 00:37:38 +00004642 return false;
4643}
4644
4645
Dan Gohman2048b852009-11-23 18:04:58 +00004646void SelectionDAGBuilder::visitCall(CallInst &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004647 const char *RenameFn = 0;
4648 if (Function *F = I.getCalledFunction()) {
4649 if (F->isDeclaration()) {
Dale Johannesen49de9822009-02-05 01:49:45 +00004650 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4651 if (II) {
4652 if (unsigned IID = II->getIntrinsicID(F)) {
4653 RenameFn = visitIntrinsicCall(I, IID);
4654 if (!RenameFn)
4655 return;
4656 }
4657 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004658 if (unsigned IID = F->getIntrinsicID()) {
4659 RenameFn = visitIntrinsicCall(I, IID);
4660 if (!RenameFn)
4661 return;
4662 }
4663 }
4664
4665 // Check for well-known libc/libm calls. If the function is internal, it
4666 // can't be a library call.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004667 if (!F->hasLocalLinkage() && F->hasName()) {
4668 StringRef Name = F->getName();
Duncan Sandsd2c817e2010-03-14 21:08:40 +00004669 if (Name == "copysign" || Name == "copysignf" || Name == "copysignl") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004670 if (I.getNumOperands() == 3 && // Basic sanity checks.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00004671 I.getOperand(1)->getType()->isFloatingPointTy() &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004672 I.getType() == I.getOperand(1)->getType() &&
4673 I.getType() == I.getOperand(2)->getType()) {
4674 SDValue LHS = getValue(I.getOperand(1));
4675 SDValue RHS = getValue(I.getOperand(2));
Bill Wendling0d580132009-12-23 01:28:19 +00004676 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
4677 LHS.getValueType(), LHS, RHS));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004678 return;
4679 }
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004680 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004681 if (I.getNumOperands() == 2 && // Basic sanity checks.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00004682 I.getOperand(1)->getType()->isFloatingPointTy() &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004683 I.getType() == I.getOperand(1)->getType()) {
4684 SDValue Tmp = getValue(I.getOperand(1));
Bill Wendling0d580132009-12-23 01:28:19 +00004685 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
4686 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004687 return;
4688 }
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004689 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004690 if (I.getNumOperands() == 2 && // Basic sanity checks.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00004691 I.getOperand(1)->getType()->isFloatingPointTy() &&
Dale Johannesena45bfd32009-09-25 18:00:35 +00004692 I.getType() == I.getOperand(1)->getType() &&
4693 I.onlyReadsMemory()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004694 SDValue Tmp = getValue(I.getOperand(1));
Bill Wendling0d580132009-12-23 01:28:19 +00004695 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
4696 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004697 return;
4698 }
Daniel Dunbarf0443c12009-07-26 08:34:35 +00004699 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004700 if (I.getNumOperands() == 2 && // Basic sanity checks.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00004701 I.getOperand(1)->getType()->isFloatingPointTy() &&
Dale Johannesena45bfd32009-09-25 18:00:35 +00004702 I.getType() == I.getOperand(1)->getType() &&
4703 I.onlyReadsMemory()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004704 SDValue Tmp = getValue(I.getOperand(1));
Bill Wendling0d580132009-12-23 01:28:19 +00004705 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
4706 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004707 return;
4708 }
Dale Johannesen52fb79b2009-09-25 17:23:22 +00004709 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
4710 if (I.getNumOperands() == 2 && // Basic sanity checks.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00004711 I.getOperand(1)->getType()->isFloatingPointTy() &&
Dale Johannesena45bfd32009-09-25 18:00:35 +00004712 I.getType() == I.getOperand(1)->getType() &&
4713 I.onlyReadsMemory()) {
Dale Johannesen52fb79b2009-09-25 17:23:22 +00004714 SDValue Tmp = getValue(I.getOperand(1));
Bill Wendling0d580132009-12-23 01:28:19 +00004715 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
4716 Tmp.getValueType(), Tmp));
Dale Johannesen52fb79b2009-09-25 17:23:22 +00004717 return;
4718 }
Chris Lattner8047d9a2009-12-24 00:37:38 +00004719 } else if (Name == "memcmp") {
4720 if (visitMemCmpCall(I))
4721 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004722 }
4723 }
4724 } else if (isa<InlineAsm>(I.getOperand(0))) {
4725 visitInlineAsm(&I);
4726 return;
4727 }
4728
4729 SDValue Callee;
4730 if (!RenameFn)
4731 Callee = getValue(I.getOperand(0));
4732 else
Bill Wendling056292f2008-09-16 21:48:12 +00004733 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004734
Bill Wendling0d580132009-12-23 01:28:19 +00004735 // Check if we can potentially perform a tail call. More detailed checking is
4736 // be done within LowerCallTo, after more information about the call is known.
Evan Cheng11e67932010-01-26 23:13:04 +00004737 LowerCallTo(&I, Callee, I.isTailCall());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004738}
4739
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004740/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004741/// this value and returns the result as a ValueVT value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004742/// Chain/Flag as the input and updates them for the output Chain/Flag.
4743/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004744SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
Bill Wendling46ada192010-03-02 01:55:18 +00004745 SDValue &Chain, SDValue *Flag) const {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004746 // Assemble the legal parts into the final values.
4747 SmallVector<SDValue, 4> Values(ValueVTs.size());
4748 SmallVector<SDValue, 8> Parts;
4749 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4750 // Copy the legal parts from the registers.
Owen Andersone50ed302009-08-10 22:56:29 +00004751 EVT ValueVT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00004752 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
Owen Andersone50ed302009-08-10 22:56:29 +00004753 EVT RegisterVT = RegVTs[Value];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004754
4755 Parts.resize(NumRegs);
4756 for (unsigned i = 0; i != NumRegs; ++i) {
4757 SDValue P;
Bill Wendlingec72e322009-12-22 01:11:43 +00004758 if (Flag == 0) {
Dale Johannesena04b7572009-02-03 23:04:43 +00004759 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
Bill Wendlingec72e322009-12-22 01:11:43 +00004760 } else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004761 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004762 *Flag = P.getValue(2);
4763 }
Bill Wendlingec72e322009-12-22 01:11:43 +00004764
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004765 Chain = P.getValue(1);
Bill Wendlingec72e322009-12-22 01:11:43 +00004766
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004767 // If the source register was virtual and if we know something about it,
4768 // add an assert node.
4769 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4770 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4771 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4772 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4773 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4774 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004775
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004776 unsigned RegSize = RegisterVT.getSizeInBits();
4777 unsigned NumSignBits = LOI.NumSignBits;
4778 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004779
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004780 // FIXME: We capture more information than the dag can represent. For
4781 // now, just use the tightest assertzext/assertsext possible.
4782 bool isSExt = true;
Owen Anderson825b72b2009-08-11 20:47:22 +00004783 EVT FromVT(MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004784 if (NumSignBits == RegSize)
Owen Anderson825b72b2009-08-11 20:47:22 +00004785 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004786 else if (NumZeroBits >= RegSize-1)
Owen Anderson825b72b2009-08-11 20:47:22 +00004787 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004788 else if (NumSignBits > RegSize-8)
Owen Anderson825b72b2009-08-11 20:47:22 +00004789 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
Dan Gohman07c26ee2009-03-31 01:38:29 +00004790 else if (NumZeroBits >= RegSize-8)
Owen Anderson825b72b2009-08-11 20:47:22 +00004791 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004792 else if (NumSignBits > RegSize-16)
Owen Anderson825b72b2009-08-11 20:47:22 +00004793 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
Dan Gohman07c26ee2009-03-31 01:38:29 +00004794 else if (NumZeroBits >= RegSize-16)
Owen Anderson825b72b2009-08-11 20:47:22 +00004795 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004796 else if (NumSignBits > RegSize-32)
Owen Anderson825b72b2009-08-11 20:47:22 +00004797 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
Dan Gohman07c26ee2009-03-31 01:38:29 +00004798 else if (NumZeroBits >= RegSize-32)
Owen Anderson825b72b2009-08-11 20:47:22 +00004799 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004800
Bill Wendling4533cac2010-01-28 21:51:40 +00004801 if (FromVT != MVT::Other)
Dale Johannesen66978ee2009-01-31 02:22:37 +00004802 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004803 RegisterVT, P, DAG.getValueType(FromVT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004804 }
4805 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004806
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004807 Parts[i] = P;
4808 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004809
Bill Wendling46ada192010-03-02 01:55:18 +00004810 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00004811 NumRegs, RegisterVT, ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004812 Part += NumRegs;
4813 Parts.clear();
4814 }
4815
Bill Wendling4533cac2010-01-28 21:51:40 +00004816 return DAG.getNode(ISD::MERGE_VALUES, dl,
4817 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4818 &Values[0], ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004819}
4820
4821/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004822/// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004823/// Chain/Flag as the input and updates them for the output Chain/Flag.
4824/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004825void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Bill Wendling46ada192010-03-02 01:55:18 +00004826 SDValue &Chain, SDValue *Flag) const {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004827 // Get the list of the values's legal parts.
4828 unsigned NumRegs = Regs.size();
4829 SmallVector<SDValue, 8> Parts(NumRegs);
4830 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00004831 EVT ValueVT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00004832 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
Owen Andersone50ed302009-08-10 22:56:29 +00004833 EVT RegisterVT = RegVTs[Value];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004834
Bill Wendling46ada192010-03-02 01:55:18 +00004835 getCopyToParts(DAG, dl,
Bill Wendling3ea3c242009-12-22 02:10:19 +00004836 Val.getValue(Val.getResNo() + Value),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004837 &Parts[Part], NumParts, RegisterVT);
4838 Part += NumParts;
4839 }
4840
4841 // Copy the parts into the registers.
4842 SmallVector<SDValue, 8> Chains(NumRegs);
4843 for (unsigned i = 0; i != NumRegs; ++i) {
4844 SDValue Part;
Bill Wendlingec72e322009-12-22 01:11:43 +00004845 if (Flag == 0) {
Dale Johannesena04b7572009-02-03 23:04:43 +00004846 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
Bill Wendlingec72e322009-12-22 01:11:43 +00004847 } else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004848 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004849 *Flag = Part.getValue(1);
4850 }
Bill Wendlingec72e322009-12-22 01:11:43 +00004851
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004852 Chains[i] = Part.getValue(0);
4853 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004854
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004855 if (NumRegs == 1 || Flag)
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004856 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004857 // flagged to it. That is the CopyToReg nodes and the user are considered
4858 // a single scheduling unit. If we create a TokenFactor and return it as
4859 // chain, then the TokenFactor is both a predecessor (operand) of the
4860 // user as well as a successor (the TF operands are flagged to the user).
4861 // c1, f1 = CopyToReg
4862 // c2, f2 = CopyToReg
4863 // c3 = TokenFactor c1, c2
4864 // ...
4865 // = op c3, ..., f2
4866 Chain = Chains[NumRegs-1];
4867 else
Owen Anderson825b72b2009-08-11 20:47:22 +00004868 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004869}
4870
4871/// AddInlineAsmOperands - Add this value to the specified inlineasm node
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004872/// operand list. This adds the code marker and includes the number of
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004873/// values added into it.
Evan Cheng697cbbf2009-03-20 18:03:34 +00004874void RegsForValue::AddInlineAsmOperands(unsigned Code,
4875 bool HasMatching,unsigned MatchingIdx,
Bill Wendling46ada192010-03-02 01:55:18 +00004876 SelectionDAG &DAG,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004877 std::vector<SDValue> &Ops) const {
Evan Cheng697cbbf2009-03-20 18:03:34 +00004878 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
4879 unsigned Flag = Code | (Regs.size() << 3);
4880 if (HasMatching)
4881 Flag |= 0x80000000 | (MatchingIdx << 16);
Dale Johannesen99499332009-12-23 07:32:51 +00004882 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
Bill Wendling651ad132009-12-22 01:25:10 +00004883 Ops.push_back(Res);
4884
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004885 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
Owen Anderson23b9b192009-08-12 00:36:31 +00004886 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
Owen Andersone50ed302009-08-10 22:56:29 +00004887 EVT RegisterVT = RegVTs[Value];
Chris Lattner58f15c42008-10-17 16:21:11 +00004888 for (unsigned i = 0; i != NumRegs; ++i) {
4889 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Bill Wendling4533cac2010-01-28 21:51:40 +00004890 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner58f15c42008-10-17 16:21:11 +00004891 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004892 }
4893}
4894
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004895/// isAllocatableRegister - If the specified register is safe to allocate,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004896/// i.e. it isn't a stack pointer or some other special register, return the
4897/// register class for the register. Otherwise, return null.
4898static const TargetRegisterClass *
4899isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4900 const TargetLowering &TLI,
4901 const TargetRegisterInfo *TRI) {
Owen Anderson825b72b2009-08-11 20:47:22 +00004902 EVT FoundVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004903 const TargetRegisterClass *FoundRC = 0;
4904 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4905 E = TRI->regclass_end(); RCI != E; ++RCI) {
Owen Anderson825b72b2009-08-11 20:47:22 +00004906 EVT ThisVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004907
4908 const TargetRegisterClass *RC = *RCI;
Dan Gohmanf451cb82010-02-10 16:03:48 +00004909 // If none of the value types for this register class are valid, we
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004910 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4911 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4912 I != E; ++I) {
4913 if (TLI.isTypeLegal(*I)) {
4914 // If we have already found this register in a different register class,
4915 // choose the one with the largest VT specified. For example, on
4916 // PowerPC, we favor f64 register classes over f32.
Owen Anderson825b72b2009-08-11 20:47:22 +00004917 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004918 ThisVT = *I;
4919 break;
4920 }
4921 }
4922 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004923
Owen Anderson825b72b2009-08-11 20:47:22 +00004924 if (ThisVT == MVT::Other) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004925
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004926 // NOTE: This isn't ideal. In particular, this might allocate the
4927 // frame pointer in functions that need it (due to them not being taken
4928 // out of allocation, because a variable sized allocation hasn't been seen
4929 // yet). This is a slight code pessimization, but should still work.
4930 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4931 E = RC->allocation_order_end(MF); I != E; ++I)
4932 if (*I == Reg) {
4933 // We found a matching register class. Keep looking at others in case
4934 // we find one with larger registers that this physreg is also in.
4935 FoundRC = RC;
4936 FoundVT = ThisVT;
4937 break;
4938 }
4939 }
4940 return FoundRC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004941}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004942
4943
4944namespace llvm {
4945/// AsmOperandInfo - This contains information for each constraint that we are
4946/// lowering.
Cedric Venetaff9c272009-02-14 16:06:42 +00004947class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
Daniel Dunbarc0c3b9a2008-09-10 04:16:29 +00004948 public TargetLowering::AsmOperandInfo {
Cedric Venetaff9c272009-02-14 16:06:42 +00004949public:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004950 /// CallOperand - If this is the result output operand or a clobber
4951 /// this is null, otherwise it is the incoming operand to the CallInst.
4952 /// This gets modified as the asm is processed.
4953 SDValue CallOperand;
4954
4955 /// AssignedRegs - If this is a register or register class operand, this
4956 /// contains the set of register corresponding to the operand.
4957 RegsForValue AssignedRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004958
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004959 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4960 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4961 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004962
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004963 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4964 /// busy in OutputRegs/InputRegs.
4965 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004966 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004967 std::set<unsigned> &InputRegs,
4968 const TargetRegisterInfo &TRI) const {
4969 if (isOutReg) {
4970 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4971 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4972 }
4973 if (isInReg) {
4974 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4975 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4976 }
4977 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004978
Owen Andersone50ed302009-08-10 22:56:29 +00004979 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
Chris Lattner81249c92008-10-17 17:05:25 +00004980 /// corresponds to. If there is no Value* for this operand, it returns
Owen Anderson825b72b2009-08-11 20:47:22 +00004981 /// MVT::Other.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00004982 EVT getCallOperandValEVT(LLVMContext &Context,
Owen Anderson1d0be152009-08-13 21:58:54 +00004983 const TargetLowering &TLI,
Chris Lattner81249c92008-10-17 17:05:25 +00004984 const TargetData *TD) const {
Owen Anderson825b72b2009-08-11 20:47:22 +00004985 if (CallOperandVal == 0) return MVT::Other;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004986
Chris Lattner81249c92008-10-17 17:05:25 +00004987 if (isa<BasicBlock>(CallOperandVal))
4988 return TLI.getPointerTy();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004989
Chris Lattner81249c92008-10-17 17:05:25 +00004990 const llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004991
Chris Lattner81249c92008-10-17 17:05:25 +00004992 // If this is an indirect operand, the operand is a pointer to the
4993 // accessed type.
Bob Wilsone261b0c2009-12-22 18:34:19 +00004994 if (isIndirect) {
4995 const llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
4996 if (!PtrTy)
4997 llvm_report_error("Indirect operand for inline asm not a pointer!");
4998 OpTy = PtrTy->getElementType();
4999 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005000
Chris Lattner81249c92008-10-17 17:05:25 +00005001 // If OpTy is not a single value, it may be a struct/union that we
5002 // can tile with integers.
5003 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5004 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
5005 switch (BitSize) {
5006 default: break;
5007 case 1:
5008 case 8:
5009 case 16:
5010 case 32:
5011 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00005012 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00005013 OpTy = IntegerType::get(Context, BitSize);
Chris Lattner81249c92008-10-17 17:05:25 +00005014 break;
5015 }
5016 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005017
Chris Lattner81249c92008-10-17 17:05:25 +00005018 return TLI.getValueType(OpTy, true);
5019 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005020
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005021private:
5022 /// MarkRegAndAliases - Mark the specified register and all aliases in the
5023 /// specified set.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005024 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005025 const TargetRegisterInfo &TRI) {
5026 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
5027 Regs.insert(Reg);
5028 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
5029 for (; *Aliases; ++Aliases)
5030 Regs.insert(*Aliases);
5031 }
5032};
5033} // end llvm namespace.
5034
5035
5036/// GetRegistersForValue - Assign registers (virtual or physical) for the
5037/// specified operand. We prefer to assign virtual registers, to allow the
Bob Wilson266d9452009-12-17 05:07:36 +00005038/// register allocator to handle the assignment process. However, if the asm
5039/// uses features that we can't model on machineinstrs, we have SDISel do the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005040/// allocation. This produces generally horrible, but correct, code.
5041///
5042/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005043/// Input and OutputRegs are the set of already allocated physical registers.
5044///
Dan Gohman2048b852009-11-23 18:04:58 +00005045void SelectionDAGBuilder::
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005046GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005047 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005048 std::set<unsigned> &InputRegs) {
Dan Gohman0d24bfb2009-08-15 02:06:22 +00005049 LLVMContext &Context = FuncInfo.Fn->getContext();
Owen Anderson23b9b192009-08-12 00:36:31 +00005050
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005051 // Compute whether this value requires an input register, an output register,
5052 // or both.
5053 bool isOutReg = false;
5054 bool isInReg = false;
5055 switch (OpInfo.Type) {
5056 case InlineAsm::isOutput:
5057 isOutReg = true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005058
5059 // If there is an input constraint that matches this, we need to reserve
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005060 // the input register so no other inputs allocate to it.
Chris Lattner6bdcda32008-10-17 16:47:46 +00005061 isInReg = OpInfo.hasMatchingInput();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005062 break;
5063 case InlineAsm::isInput:
5064 isInReg = true;
5065 isOutReg = false;
5066 break;
5067 case InlineAsm::isClobber:
5068 isOutReg = true;
5069 isInReg = true;
5070 break;
5071 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005072
5073
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005074 MachineFunction &MF = DAG.getMachineFunction();
5075 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005076
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005077 // If this is a constraint for a single physreg, or a constraint for a
5078 // register class, find it.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005079 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005080 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5081 OpInfo.ConstraintVT);
5082
5083 unsigned NumRegs = 1;
Owen Anderson825b72b2009-08-11 20:47:22 +00005084 if (OpInfo.ConstraintVT != MVT::Other) {
Chris Lattner01426e12008-10-21 00:45:36 +00005085 // If this is a FP input in an integer register (or visa versa) insert a bit
5086 // cast of the input value. More generally, handle any case where the input
5087 // value disagrees with the register class we plan to stick this in.
5088 if (OpInfo.Type == InlineAsm::isInput &&
5089 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
Owen Andersone50ed302009-08-10 22:56:29 +00005090 // Try to convert to the first EVT that the reg class contains. If the
Chris Lattner01426e12008-10-21 00:45:36 +00005091 // types are identical size, use a bitcast to convert (e.g. two differing
5092 // vector types).
Owen Andersone50ed302009-08-10 22:56:29 +00005093 EVT RegVT = *PhysReg.second->vt_begin();
Chris Lattner01426e12008-10-21 00:45:36 +00005094 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005095 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005096 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00005097 OpInfo.ConstraintVT = RegVT;
5098 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5099 // If the input is a FP value and we want it in FP registers, do a
5100 // bitcast to the corresponding integer type. This turns an f64 value
5101 // into i64, which can be passed with two i32 values on a 32-bit
5102 // machine.
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005103 RegVT = EVT::getIntegerVT(Context,
Owen Anderson23b9b192009-08-12 00:36:31 +00005104 OpInfo.ConstraintVT.getSizeInBits());
Dale Johannesen66978ee2009-01-31 02:22:37 +00005105 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005106 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00005107 OpInfo.ConstraintVT = RegVT;
5108 }
5109 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005110
Owen Anderson23b9b192009-08-12 00:36:31 +00005111 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00005112 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005113
Owen Andersone50ed302009-08-10 22:56:29 +00005114 EVT RegVT;
5115 EVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005116
5117 // If this is a constraint for a specific physical register, like {r17},
5118 // assign it now.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005119 if (unsigned AssignedReg = PhysReg.first) {
5120 const TargetRegisterClass *RC = PhysReg.second;
Owen Anderson825b72b2009-08-11 20:47:22 +00005121 if (OpInfo.ConstraintVT == MVT::Other)
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005122 ValueVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005123
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005124 // Get the actual register value type. This is important, because the user
5125 // may have asked for (e.g.) the AX register in i32 type. We need to
5126 // remember that AX is actually i16 to get the right extension.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005127 RegVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005128
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005129 // This is a explicit reference to a physical register.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005130 Regs.push_back(AssignedReg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005131
5132 // If this is an expanded reference, add the rest of the regs to Regs.
5133 if (NumRegs != 1) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005134 TargetRegisterClass::iterator I = RC->begin();
5135 for (; *I != AssignedReg; ++I)
5136 assert(I != RC->end() && "Didn't find reg!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005137
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005138 // Already added the first reg.
5139 --NumRegs; ++I;
5140 for (; NumRegs; --NumRegs, ++I) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005141 assert(I != RC->end() && "Ran out of registers to allocate!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005142 Regs.push_back(*I);
5143 }
5144 }
Bill Wendling651ad132009-12-22 01:25:10 +00005145
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005146 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5147 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5148 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5149 return;
5150 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005151
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005152 // Otherwise, if this was a reference to an LLVM register class, create vregs
5153 // for this reference.
Chris Lattnerb3b44842009-03-24 15:25:07 +00005154 if (const TargetRegisterClass *RC = PhysReg.second) {
5155 RegVT = *RC->vt_begin();
Owen Anderson825b72b2009-08-11 20:47:22 +00005156 if (OpInfo.ConstraintVT == MVT::Other)
Evan Chengfb112882009-03-23 08:01:15 +00005157 ValueVT = RegVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005158
Evan Chengfb112882009-03-23 08:01:15 +00005159 // Create the appropriate number of virtual registers.
5160 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5161 for (; NumRegs; --NumRegs)
Chris Lattnerb3b44842009-03-24 15:25:07 +00005162 Regs.push_back(RegInfo.createVirtualRegister(RC));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005163
Evan Chengfb112882009-03-23 08:01:15 +00005164 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5165 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005166 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005167
Chris Lattnerfc9d1612009-03-24 15:22:11 +00005168 // This is a reference to a register class that doesn't directly correspond
5169 // to an LLVM register class. Allocate NumRegs consecutive, available,
5170 // registers from the class.
5171 std::vector<unsigned> RegClassRegs
5172 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5173 OpInfo.ConstraintVT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005174
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005175 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5176 unsigned NumAllocated = 0;
5177 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5178 unsigned Reg = RegClassRegs[i];
5179 // See if this register is available.
5180 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5181 (isInReg && InputRegs.count(Reg))) { // Already used.
5182 // Make sure we find consecutive registers.
5183 NumAllocated = 0;
5184 continue;
5185 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005186
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005187 // Check to see if this register is allocatable (i.e. don't give out the
5188 // stack pointer).
Chris Lattnerfc9d1612009-03-24 15:22:11 +00005189 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5190 if (!RC) { // Couldn't allocate this register.
5191 // Reset NumAllocated to make sure we return consecutive registers.
5192 NumAllocated = 0;
5193 continue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005194 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005195
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005196 // Okay, this register is good, we can use it.
5197 ++NumAllocated;
5198
5199 // If we allocated enough consecutive registers, succeed.
5200 if (NumAllocated == NumRegs) {
5201 unsigned RegStart = (i-NumAllocated)+1;
5202 unsigned RegEnd = i+1;
5203 // Mark all of the allocated registers used.
5204 for (unsigned i = RegStart; i != RegEnd; ++i)
5205 Regs.push_back(RegClassRegs[i]);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005206
5207 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005208 OpInfo.ConstraintVT);
5209 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5210 return;
5211 }
5212 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005213
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005214 // Otherwise, we couldn't allocate enough registers for this.
5215}
5216
Evan Chengda43bcf2008-09-24 00:05:32 +00005217/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5218/// processed uses a memory 'm' constraint.
5219static bool
5220hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
Dan Gohmane9530ec2009-01-15 16:58:17 +00005221 const TargetLowering &TLI) {
Evan Chengda43bcf2008-09-24 00:05:32 +00005222 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5223 InlineAsm::ConstraintInfo &CI = CInfos[i];
5224 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5225 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5226 if (CType == TargetLowering::C_Memory)
5227 return true;
5228 }
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005229
Chris Lattner6c147292009-04-30 00:48:50 +00005230 // Indirect operand accesses access memory.
5231 if (CI.isIndirect)
5232 return true;
Evan Chengda43bcf2008-09-24 00:05:32 +00005233 }
5234
5235 return false;
5236}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005237
5238/// visitInlineAsm - Handle a call to an InlineAsm object.
5239///
Dan Gohman2048b852009-11-23 18:04:58 +00005240void SelectionDAGBuilder::visitInlineAsm(CallSite CS) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005241 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5242
5243 /// ConstraintOperands - Information about all of the constraints.
5244 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005245
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005246 std::set<unsigned> OutputRegs, InputRegs;
5247
5248 // Do a prepass over the constraints, canonicalizing them, and building up the
5249 // ConstraintOperands list.
5250 std::vector<InlineAsm::ConstraintInfo>
5251 ConstraintInfos = IA->ParseConstraints();
5252
Evan Chengda43bcf2008-09-24 00:05:32 +00005253 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005254
Chris Lattner6c147292009-04-30 00:48:50 +00005255 SDValue Chain, Flag;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005256
Chris Lattner6c147292009-04-30 00:48:50 +00005257 // We won't need to flush pending loads if this asm doesn't touch
5258 // memory and is nonvolatile.
5259 if (hasMemory || IA->hasSideEffects())
Dale Johannesen97d14fc2009-04-18 00:09:40 +00005260 Chain = getRoot();
Chris Lattner6c147292009-04-30 00:48:50 +00005261 else
5262 Chain = DAG.getRoot();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005263
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005264 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5265 unsigned ResNo = 0; // ResNo - The result number of the next output.
5266 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5267 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5268 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005269
Owen Anderson825b72b2009-08-11 20:47:22 +00005270 EVT OpVT = MVT::Other;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005271
5272 // Compute the value type for each operand.
5273 switch (OpInfo.Type) {
5274 case InlineAsm::isOutput:
5275 // Indirect outputs just consume an argument.
5276 if (OpInfo.isIndirect) {
5277 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5278 break;
5279 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005280
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005281 // The return value of the call is this value. As such, there is no
5282 // corresponding argument.
Benjamin Kramerf0127052010-01-05 13:12:22 +00005283 assert(!CS.getType()->isVoidTy() &&
Owen Anderson1d0be152009-08-13 21:58:54 +00005284 "Bad inline asm!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005285 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5286 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5287 } else {
5288 assert(ResNo == 0 && "Asm only has one result!");
5289 OpVT = TLI.getValueType(CS.getType());
5290 }
5291 ++ResNo;
5292 break;
5293 case InlineAsm::isInput:
5294 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5295 break;
5296 case InlineAsm::isClobber:
5297 // Nothing to do.
5298 break;
5299 }
5300
5301 // If this is an input or an indirect output, process the call argument.
5302 // BasicBlocks are labels, currently appearing only in asm's.
5303 if (OpInfo.CallOperandVal) {
Dale Johannesen5339c552009-07-20 23:27:39 +00005304 // Strip bitcasts, if any. This mostly comes up for functions.
Dale Johannesen76711242009-08-06 22:45:51 +00005305 OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts();
5306
Chris Lattner81249c92008-10-17 17:05:25 +00005307 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005308 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00005309 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005310 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005311 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005312
Owen Anderson1d0be152009-08-13 21:58:54 +00005313 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005314 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005315
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005316 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005317 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005318
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005319 // Second pass over the constraints: compute which constraint option to use
5320 // and assign registers to constraints that want a specific physreg.
5321 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5322 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005323
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005324 // If this is an output operand with a matching input operand, look up the
Evan Cheng09dc9c02008-12-16 18:21:39 +00005325 // matching input. If their types mismatch, e.g. one is an integer, the
5326 // other is floating point, or their sizes are different, flag it as an
5327 // error.
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005328 if (OpInfo.hasMatchingInput()) {
5329 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5330 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Evan Cheng09dc9c02008-12-16 18:21:39 +00005331 if ((OpInfo.ConstraintVT.isInteger() !=
5332 Input.ConstraintVT.isInteger()) ||
5333 (OpInfo.ConstraintVT.getSizeInBits() !=
5334 Input.ConstraintVT.getSizeInBits())) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005335 llvm_report_error("Unsupported asm: input constraint"
Torok Edwin7d696d82009-07-11 13:10:19 +00005336 " with a matching output constraint of incompatible"
5337 " type!");
Evan Cheng09dc9c02008-12-16 18:21:39 +00005338 }
5339 Input.ConstraintVT = OpInfo.ConstraintVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005340 }
5341 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005342
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005343 // Compute the constraint code and ConstraintType to use.
Evan Chengda43bcf2008-09-24 00:05:32 +00005344 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005345
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005346 // If this is a memory input, and if the operand is not indirect, do what we
5347 // need to to provide an address for the memory input.
5348 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5349 !OpInfo.isIndirect) {
5350 assert(OpInfo.Type == InlineAsm::isInput &&
5351 "Can only indirectify direct input operands!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005352
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005353 // Memory operands really want the address of the value. If we don't have
5354 // an indirect input, put it in the constpool if we can, otherwise spill
5355 // it to a stack slot.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005356
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005357 // If the operand is a float, integer, or vector constant, spill to a
5358 // constant pool entry to get its address.
5359 Value *OpVal = OpInfo.CallOperandVal;
5360 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5361 isa<ConstantVector>(OpVal)) {
5362 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5363 TLI.getPointerTy());
5364 } else {
5365 // Otherwise, create a stack slot and emit a store to it before the
5366 // asm.
5367 const Type *Ty = OpVal->getType();
Duncan Sands777d2302009-05-09 07:06:46 +00005368 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005369 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5370 MachineFunction &MF = DAG.getMachineFunction();
David Greene3f2bf852009-11-12 20:49:22 +00005371 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005372 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Dale Johannesen66978ee2009-01-31 02:22:37 +00005373 Chain = DAG.getStore(Chain, getCurDebugLoc(),
David Greene1e559442010-02-15 17:00:31 +00005374 OpInfo.CallOperand, StackSlot, NULL, 0,
5375 false, false, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005376 OpInfo.CallOperand = StackSlot;
5377 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005378
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005379 // There is no longer a Value* corresponding to this operand.
5380 OpInfo.CallOperandVal = 0;
Bill Wendling651ad132009-12-22 01:25:10 +00005381
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005382 // It is now an indirect operand.
5383 OpInfo.isIndirect = true;
5384 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005385
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005386 // If this constraint is for a specific register, allocate it before
5387 // anything else.
5388 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005389 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005390 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005391
Bill Wendling651ad132009-12-22 01:25:10 +00005392 ConstraintInfos.clear();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005393
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005394 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00005395 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005396 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5397 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005398
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005399 // C_Register operands have already been allocated, Other/Memory don't need
5400 // to be.
5401 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005402 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005403 }
5404
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005405 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5406 std::vector<SDValue> AsmNodeOperands;
5407 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5408 AsmNodeOperands.push_back(
Dan Gohmanf2d7fb32010-01-04 21:00:54 +00005409 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
5410 TLI.getPointerTy()));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005411
5412
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005413 // Loop over all of the inputs, copying the operand values into the
5414 // appropriate registers and processing the output regs.
5415 RegsForValue RetValRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005416
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005417 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5418 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005419
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005420 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5421 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5422
5423 switch (OpInfo.Type) {
5424 case InlineAsm::isOutput: {
5425 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5426 OpInfo.ConstraintType != TargetLowering::C_Register) {
5427 // Memory output, or 'other' output (e.g. 'X' constraint).
5428 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5429
5430 // Add information to the INLINEASM node to know about this output.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005431 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5432 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005433 TLI.getPointerTy()));
5434 AsmNodeOperands.push_back(OpInfo.CallOperand);
5435 break;
5436 }
5437
5438 // Otherwise, this is a register or register class output.
5439
5440 // Copy the output from the appropriate register. Find a register that
5441 // we can use.
5442 if (OpInfo.AssignedRegs.Regs.empty()) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005443 llvm_report_error("Couldn't allocate output reg for"
Torok Edwin7d696d82009-07-11 13:10:19 +00005444 " constraint '" + OpInfo.ConstraintCode + "'!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005445 }
5446
5447 // If this is an indirect operand, store through the pointer after the
5448 // asm.
5449 if (OpInfo.isIndirect) {
5450 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5451 OpInfo.CallOperandVal));
5452 } else {
5453 // This is the result value of the call.
Benjamin Kramerf0127052010-01-05 13:12:22 +00005454 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005455 // Concatenate this output onto the outputs list.
5456 RetValRegs.append(OpInfo.AssignedRegs);
5457 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005458
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005459 // Add information to the INLINEASM node to know that this register is
5460 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00005461 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5462 6 /* EARLYCLOBBER REGDEF */ :
5463 2 /* REGDEF */ ,
Evan Chengfb112882009-03-23 08:01:15 +00005464 false,
5465 0,
Bill Wendling46ada192010-03-02 01:55:18 +00005466 DAG,
Bill Wendling651ad132009-12-22 01:25:10 +00005467 AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005468 break;
5469 }
5470 case InlineAsm::isInput: {
5471 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005472
Chris Lattner6bdcda32008-10-17 16:47:46 +00005473 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005474 // If this is required to match an output register we have already set,
5475 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00005476 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005477
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005478 // Scan until we find the definition we already emitted of this operand.
5479 // When we find it, create a RegsForValue operand.
5480 unsigned CurOp = 2; // The first operand.
5481 for (; OperandNo; --OperandNo) {
5482 // Advance to the next operand.
Evan Cheng697cbbf2009-03-20 18:03:34 +00005483 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005484 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005485 assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5486 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5487 (OpFlag & 7) == 4 /*MEM*/) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005488 "Skipped past definitions?");
Evan Cheng697cbbf2009-03-20 18:03:34 +00005489 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005490 }
5491
Evan Cheng697cbbf2009-03-20 18:03:34 +00005492 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005493 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005494 if ((OpFlag & 7) == 2 /*REGDEF*/
5495 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5496 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
Dan Gohman15480bd2009-06-15 22:32:41 +00005497 if (OpInfo.isIndirect) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005498 llvm_report_error("Don't know how to handle tied indirect "
Torok Edwin7d696d82009-07-11 13:10:19 +00005499 "register inputs yet!");
Dan Gohman15480bd2009-06-15 22:32:41 +00005500 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005501 RegsForValue MatchedRegs;
5502 MatchedRegs.TLI = &TLI;
5503 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
Owen Andersone50ed302009-08-10 22:56:29 +00005504 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
Evan Chengfb112882009-03-23 08:01:15 +00005505 MatchedRegs.RegVTs.push_back(RegVT);
5506 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005507 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
Evan Chengfb112882009-03-23 08:01:15 +00005508 i != e; ++i)
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005509 MatchedRegs.Regs.push_back
5510 (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005511
5512 // Use the produced MatchedRegs object to
Dale Johannesen66978ee2009-01-31 02:22:37 +00005513 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
Bill Wendling46ada192010-03-02 01:55:18 +00005514 Chain, &Flag);
Evan Chengfb112882009-03-23 08:01:15 +00005515 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5516 true, OpInfo.getMatchedOperand(),
Bill Wendling46ada192010-03-02 01:55:18 +00005517 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005518 break;
5519 } else {
Evan Cheng697cbbf2009-03-20 18:03:34 +00005520 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5521 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5522 "Unexpected number of operands");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005523 // Add information to the INLINEASM node to know about this input.
Evan Chengfb112882009-03-23 08:01:15 +00005524 // See InlineAsm.h isUseOperandTiedToDef.
5525 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
Evan Cheng697cbbf2009-03-20 18:03:34 +00005526 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005527 TLI.getPointerTy()));
5528 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5529 break;
5530 }
5531 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005532
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005533 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005534 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005535 "Don't know how to handle indirect other inputs yet!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005536
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005537 std::vector<SDValue> Ops;
5538 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Chengda43bcf2008-09-24 00:05:32 +00005539 hasMemory, Ops, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005540 if (Ops.empty()) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005541 llvm_report_error("Invalid operand for inline asm"
Torok Edwin7d696d82009-07-11 13:10:19 +00005542 " constraint '" + OpInfo.ConstraintCode + "'!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005543 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005544
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005545 // Add information to the INLINEASM node to know about this input.
5546 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005547 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005548 TLI.getPointerTy()));
5549 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5550 break;
5551 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5552 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5553 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5554 "Memory operands expect pointer values");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005555
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005556 // Add information to the INLINEASM node to know about this input.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005557 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5558 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005559 TLI.getPointerTy()));
5560 AsmNodeOperands.push_back(InOperandVal);
5561 break;
5562 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005563
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005564 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5565 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5566 "Unknown constraint type!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005567 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005568 "Don't know how to handle indirect register inputs yet!");
5569
5570 // Copy the input into the appropriate registers.
Evan Cheng8112b532010-02-10 01:21:02 +00005571 if (OpInfo.AssignedRegs.Regs.empty() ||
5572 !OpInfo.AssignedRegs.areValueTypesLegal()) {
Benjamin Kramerd5fe92e2009-08-03 13:33:33 +00005573 llvm_report_error("Couldn't allocate input reg for"
Torok Edwin7d696d82009-07-11 13:10:19 +00005574 " constraint '"+ OpInfo.ConstraintCode +"'!");
Evan Chengaa765b82008-09-25 00:14:04 +00005575 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005576
Dale Johannesen66978ee2009-01-31 02:22:37 +00005577 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
Bill Wendling46ada192010-03-02 01:55:18 +00005578 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005579
Evan Cheng697cbbf2009-03-20 18:03:34 +00005580 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
Bill Wendling46ada192010-03-02 01:55:18 +00005581 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005582 break;
5583 }
5584 case InlineAsm::isClobber: {
5585 // Add the clobbered value to the operand list, so that the register
5586 // allocator is aware that the physreg got clobbered.
5587 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesen91aac102008-09-17 21:13:11 +00005588 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
Bill Wendling46ada192010-03-02 01:55:18 +00005589 false, 0, DAG,
Bill Wendling651ad132009-12-22 01:25:10 +00005590 AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005591 break;
5592 }
5593 }
5594 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005595
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005596 // Finish up input operands.
5597 AsmNodeOperands[0] = Chain;
5598 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005599
Dale Johannesen66978ee2009-01-31 02:22:37 +00005600 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
Owen Anderson825b72b2009-08-11 20:47:22 +00005601 DAG.getVTList(MVT::Other, MVT::Flag),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005602 &AsmNodeOperands[0], AsmNodeOperands.size());
5603 Flag = Chain.getValue(1);
5604
5605 // If this asm returns a register value, copy the result from that register
5606 // and set it as the value of the call.
5607 if (!RetValRegs.Regs.empty()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00005608 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
Bill Wendling46ada192010-03-02 01:55:18 +00005609 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005610
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005611 // FIXME: Why don't we do this for inline asms with MRVs?
5612 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
Owen Andersone50ed302009-08-10 22:56:29 +00005613 EVT ResultType = TLI.getValueType(CS.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005614
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005615 // If any of the results of the inline asm is a vector, it may have the
5616 // wrong width/num elts. This can happen for register classes that can
5617 // contain multiple different value types. The preg or vreg allocated may
5618 // not have the same VT as was expected. Convert it to the right type
5619 // with bit_convert.
5620 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005621 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005622 ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005623
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005624 } else if (ResultType != Val.getValueType() &&
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005625 ResultType.isInteger() && Val.getValueType().isInteger()) {
5626 // If a result value was tied to an input value, the computed result may
5627 // have a wider width than the expected result. Extract the relevant
5628 // portion.
Dale Johannesen66978ee2009-01-31 02:22:37 +00005629 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005630 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005631
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005632 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00005633 }
Dan Gohman95915732008-10-18 01:03:45 +00005634
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005635 setValue(CS.getInstruction(), Val);
Dale Johannesenec65a7d2009-04-14 00:56:56 +00005636 // Don't need to use this as a chain in this case.
5637 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5638 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005639 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005640
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005641 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005642
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005643 // Process indirect outputs, first output all of the flagged copies out of
5644 // physregs.
5645 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5646 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5647 Value *Ptr = IndirectStoresToEmit[i].second;
Dale Johannesen66978ee2009-01-31 02:22:37 +00005648 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
Bill Wendling46ada192010-03-02 01:55:18 +00005649 Chain, &Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005650 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6c147292009-04-30 00:48:50 +00005651
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005652 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005653
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005654 // Emit the non-flagged stores from the physregs.
5655 SmallVector<SDValue, 8> OutChains;
Bill Wendling651ad132009-12-22 01:25:10 +00005656 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
5657 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
5658 StoresToEmit[i].first,
5659 getValue(StoresToEmit[i].second),
David Greene1e559442010-02-15 17:00:31 +00005660 StoresToEmit[i].second, 0,
5661 false, false, 0);
Bill Wendling651ad132009-12-22 01:25:10 +00005662 OutChains.push_back(Val);
Bill Wendling651ad132009-12-22 01:25:10 +00005663 }
5664
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005665 if (!OutChains.empty())
Owen Anderson825b72b2009-08-11 20:47:22 +00005666 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005667 &OutChains[0], OutChains.size());
Bill Wendling651ad132009-12-22 01:25:10 +00005668
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005669 DAG.setRoot(Chain);
5670}
5671
Dan Gohman2048b852009-11-23 18:04:58 +00005672void SelectionDAGBuilder::visitVAStart(CallInst &I) {
Bill Wendlingc1d3c942009-12-23 00:44:51 +00005673 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
5674 MVT::Other, getRoot(),
5675 getValue(I.getOperand(1)),
5676 DAG.getSrcValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005677}
5678
Dan Gohman2048b852009-11-23 18:04:58 +00005679void SelectionDAGBuilder::visitVAArg(VAArgInst &I) {
Dale Johannesena04b7572009-02-03 23:04:43 +00005680 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5681 getRoot(), getValue(I.getOperand(0)),
5682 DAG.getSrcValue(I.getOperand(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005683 setValue(&I, V);
5684 DAG.setRoot(V.getValue(1));
5685}
5686
Dan Gohman2048b852009-11-23 18:04:58 +00005687void SelectionDAGBuilder::visitVAEnd(CallInst &I) {
Bill Wendlingc1d3c942009-12-23 00:44:51 +00005688 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
5689 MVT::Other, getRoot(),
5690 getValue(I.getOperand(1)),
5691 DAG.getSrcValue(I.getOperand(1))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005692}
5693
Dan Gohman2048b852009-11-23 18:04:58 +00005694void SelectionDAGBuilder::visitVACopy(CallInst &I) {
Bill Wendlingc1d3c942009-12-23 00:44:51 +00005695 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
5696 MVT::Other, getRoot(),
5697 getValue(I.getOperand(1)),
5698 getValue(I.getOperand(2)),
5699 DAG.getSrcValue(I.getOperand(1)),
5700 DAG.getSrcValue(I.getOperand(2))));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005701}
5702
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005703/// TargetLowering::LowerCallTo - This is the default LowerCallTo
Dan Gohman98ca4f22009-08-05 01:29:28 +00005704/// implementation, which just calls LowerCall.
5705/// FIXME: When all targets are
5706/// migrated to using LowerCall, this hook should be integrated into SDISel.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005707std::pair<SDValue, SDValue>
5708TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5709 bool RetSExt, bool RetZExt, bool isVarArg,
Tilmann Scheller6b61cd12009-07-03 06:44:53 +00005710 bool isInreg, unsigned NumFixedArgs,
Sandeep Patel65c3c8f2009-09-02 08:44:58 +00005711 CallingConv::ID CallConv, bool isTailCall,
Dan Gohman98ca4f22009-08-05 01:29:28 +00005712 bool isReturnValueUsed,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005713 SDValue Callee,
Bill Wendling46ada192010-03-02 01:55:18 +00005714 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005715 // Handle all of the outgoing arguments.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005716 SmallVector<ISD::OutputArg, 32> Outs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005717 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
Owen Andersone50ed302009-08-10 22:56:29 +00005718 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005719 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5720 for (unsigned Value = 0, NumValues = ValueVTs.size();
5721 Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00005722 EVT VT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00005723 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005724 SDValue Op = SDValue(Args[i].Node.getNode(),
5725 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005726 ISD::ArgFlagsTy Flags;
5727 unsigned OriginalAlignment =
5728 getTargetData()->getABITypeAlignment(ArgTy);
5729
5730 if (Args[i].isZExt)
5731 Flags.setZExt();
5732 if (Args[i].isSExt)
5733 Flags.setSExt();
5734 if (Args[i].isInReg)
5735 Flags.setInReg();
5736 if (Args[i].isSRet)
5737 Flags.setSRet();
5738 if (Args[i].isByVal) {
5739 Flags.setByVal();
5740 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5741 const Type *ElementTy = Ty->getElementType();
5742 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sands777d2302009-05-09 07:06:46 +00005743 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005744 // For ByVal, alignment should come from FE. BE will guess if this
5745 // info is not there but there are cases it cannot get right.
5746 if (Args[i].Alignment)
5747 FrameAlign = Args[i].Alignment;
5748 Flags.setByValAlign(FrameAlign);
5749 Flags.setByValSize(FrameSize);
5750 }
5751 if (Args[i].isNest)
5752 Flags.setNest();
5753 Flags.setOrigAlign(OriginalAlignment);
5754
Owen Anderson23b9b192009-08-12 00:36:31 +00005755 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
5756 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005757 SmallVector<SDValue, 4> Parts(NumParts);
5758 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5759
5760 if (Args[i].isSExt)
5761 ExtendKind = ISD::SIGN_EXTEND;
5762 else if (Args[i].isZExt)
5763 ExtendKind = ISD::ZERO_EXTEND;
5764
Bill Wendling46ada192010-03-02 01:55:18 +00005765 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts,
Bill Wendling3ea3c242009-12-22 02:10:19 +00005766 PartVT, ExtendKind);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005767
Dan Gohman98ca4f22009-08-05 01:29:28 +00005768 for (unsigned j = 0; j != NumParts; ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005769 // if it isn't first piece, alignment must be 1
Dan Gohman98ca4f22009-08-05 01:29:28 +00005770 ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs);
5771 if (NumParts > 1 && j == 0)
5772 MyFlags.Flags.setSplit();
5773 else if (j != 0)
5774 MyFlags.Flags.setOrigAlign(1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005775
Dan Gohman98ca4f22009-08-05 01:29:28 +00005776 Outs.push_back(MyFlags);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005777 }
5778 }
5779 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005780
Dan Gohman98ca4f22009-08-05 01:29:28 +00005781 // Handle the incoming return values from the call.
5782 SmallVector<ISD::InputArg, 32> Ins;
Owen Andersone50ed302009-08-10 22:56:29 +00005783 SmallVector<EVT, 4> RetTys;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005784 ComputeValueVTs(*this, RetTy, RetTys);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005785 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Owen Andersone50ed302009-08-10 22:56:29 +00005786 EVT VT = RetTys[I];
Owen Anderson23b9b192009-08-12 00:36:31 +00005787 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5788 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005789 for (unsigned i = 0; i != NumRegs; ++i) {
5790 ISD::InputArg MyFlags;
5791 MyFlags.VT = RegisterVT;
5792 MyFlags.Used = isReturnValueUsed;
5793 if (RetSExt)
5794 MyFlags.Flags.setSExt();
5795 if (RetZExt)
5796 MyFlags.Flags.setZExt();
5797 if (isInreg)
5798 MyFlags.Flags.setInReg();
5799 Ins.push_back(MyFlags);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005800 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005801 }
5802
Dan Gohman98ca4f22009-08-05 01:29:28 +00005803 SmallVector<SDValue, 4> InVals;
Evan Cheng022d9e12010-02-02 23:55:14 +00005804 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
Dan Gohman98ca4f22009-08-05 01:29:28 +00005805 Outs, Ins, dl, DAG, InVals);
Dan Gohman5e866062009-08-06 15:37:27 +00005806
5807 // Verify that the target's LowerCall behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +00005808 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00005809 "LowerCall didn't return a valid chain!");
5810 assert((!isTailCall || InVals.empty()) &&
5811 "LowerCall emitted a return value for a tail call!");
5812 assert((isTailCall || InVals.size() == Ins.size()) &&
5813 "LowerCall didn't emit the correct number of values!");
Dan Gohman98ca4f22009-08-05 01:29:28 +00005814
5815 // For a tail call, the return value is merely live-out and there aren't
5816 // any nodes in the DAG representing it. Return a special value to
5817 // indicate that a tail call has been emitted and no more Instructions
5818 // should be processed in the current block.
5819 if (isTailCall) {
5820 DAG.setRoot(Chain);
5821 return std::make_pair(SDValue(), SDValue());
5822 }
5823
Evan Chengaf1871f2010-03-11 19:38:18 +00005824 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5825 assert(InVals[i].getNode() &&
5826 "LowerCall emitted a null value!");
5827 assert(Ins[i].VT == InVals[i].getValueType() &&
5828 "LowerCall emitted a value with the wrong type!");
5829 });
5830
Dan Gohman98ca4f22009-08-05 01:29:28 +00005831 // Collect the legal value parts into potentially illegal values
5832 // that correspond to the original function's return values.
5833 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5834 if (RetSExt)
5835 AssertOp = ISD::AssertSext;
5836 else if (RetZExt)
5837 AssertOp = ISD::AssertZext;
5838 SmallVector<SDValue, 4> ReturnValues;
5839 unsigned CurReg = 0;
5840 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
Owen Andersone50ed302009-08-10 22:56:29 +00005841 EVT VT = RetTys[I];
Owen Anderson23b9b192009-08-12 00:36:31 +00005842 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5843 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005844
Bill Wendling46ada192010-03-02 01:55:18 +00005845 ReturnValues.push_back(getCopyFromParts(DAG, dl, &InVals[CurReg],
Bill Wendling4533cac2010-01-28 21:51:40 +00005846 NumRegs, RegisterVT, VT,
5847 AssertOp));
Dan Gohman98ca4f22009-08-05 01:29:28 +00005848 CurReg += NumRegs;
5849 }
5850
5851 // For a function returning void, there is no return value. We can't create
5852 // such a node, so we just return a null return value in that case. In
5853 // that case, nothing will actualy look at the value.
5854 if (ReturnValues.empty())
5855 return std::make_pair(SDValue(), Chain);
5856
5857 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
5858 DAG.getVTList(&RetTys[0], RetTys.size()),
5859 &ReturnValues[0], ReturnValues.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005860 return std::make_pair(Res, Chain);
5861}
5862
Duncan Sands9fbc7e22009-01-21 09:00:29 +00005863void TargetLowering::LowerOperationWrapper(SDNode *N,
5864 SmallVectorImpl<SDValue> &Results,
5865 SelectionDAG &DAG) {
5866 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptabb326bb2009-01-21 04:48:39 +00005867 if (Res.getNode())
5868 Results.push_back(Res);
5869}
5870
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005871SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005872 llvm_unreachable("LowerOperation not implemented for this target!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005873 return SDValue();
5874}
5875
Dan Gohman2048b852009-11-23 18:04:58 +00005876void SelectionDAGBuilder::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005877 SDValue Op = getValue(V);
5878 assert((Op.getOpcode() != ISD::CopyFromReg ||
5879 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5880 "Copy from a reg to the same reg!");
5881 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5882
Owen Anderson23b9b192009-08-12 00:36:31 +00005883 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005884 SDValue Chain = DAG.getEntryNode();
Bill Wendling46ada192010-03-02 01:55:18 +00005885 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005886 PendingExports.push_back(Chain);
5887}
5888
5889#include "llvm/CodeGen/SelectionDAGISel.h"
5890
Dan Gohman8c2b5252009-10-30 01:27:03 +00005891void SelectionDAGISel::LowerArguments(BasicBlock *LLVMBB) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005892 // If this is the entry block, emit arguments.
5893 Function &F = *LLVMBB->getParent();
Dan Gohman2048b852009-11-23 18:04:58 +00005894 SelectionDAG &DAG = SDB->DAG;
Dan Gohman98ca4f22009-08-05 01:29:28 +00005895 SDValue OldRoot = DAG.getRoot();
Dan Gohman2048b852009-11-23 18:04:58 +00005896 DebugLoc dl = SDB->getCurDebugLoc();
Dan Gohman98ca4f22009-08-05 01:29:28 +00005897 const TargetData *TD = TLI.getTargetData();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005898 SmallVector<ISD::InputArg, 16> Ins;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005899
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +00005900 // Check whether the function can return without sret-demotion.
5901 SmallVector<EVT, 4> OutVTs;
5902 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005903 getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005904 OutVTs, OutsFlags, TLI);
5905 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
5906
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00005907 FLI.CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(), F.isVarArg(),
Bill Wendling3ea3c242009-12-22 02:10:19 +00005908 OutVTs, OutsFlags, DAG);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00005909 if (!FLI.CanLowerReturn) {
5910 // Put in an sret pointer parameter before all the other parameters.
5911 SmallVector<EVT, 1> ValueVTs;
5912 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5913
5914 // NOTE: Assuming that a pointer will never break down to more than one VT
5915 // or one register.
5916 ISD::ArgFlagsTy Flags;
5917 Flags.setSRet();
5918 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), ValueVTs[0]);
5919 ISD::InputArg RetArg(Flags, RegisterVT, true);
5920 Ins.push_back(RetArg);
5921 }
Kenneth Uildriksb4997ae2009-11-07 02:11:54 +00005922
Dan Gohman98ca4f22009-08-05 01:29:28 +00005923 // Set up the incoming argument description vector.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005924 unsigned Idx = 1;
5925 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5926 I != E; ++I, ++Idx) {
Owen Andersone50ed302009-08-10 22:56:29 +00005927 SmallVector<EVT, 4> ValueVTs;
Dan Gohman98ca4f22009-08-05 01:29:28 +00005928 ComputeValueVTs(TLI, I->getType(), ValueVTs);
5929 bool isArgValueUsed = !I->use_empty();
5930 for (unsigned Value = 0, NumValues = ValueVTs.size();
5931 Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00005932 EVT VT = ValueVTs[Value];
Owen Anderson1d0be152009-08-13 21:58:54 +00005933 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Dan Gohman98ca4f22009-08-05 01:29:28 +00005934 ISD::ArgFlagsTy Flags;
5935 unsigned OriginalAlignment =
5936 TD->getABITypeAlignment(ArgTy);
5937
5938 if (F.paramHasAttr(Idx, Attribute::ZExt))
5939 Flags.setZExt();
5940 if (F.paramHasAttr(Idx, Attribute::SExt))
5941 Flags.setSExt();
5942 if (F.paramHasAttr(Idx, Attribute::InReg))
5943 Flags.setInReg();
5944 if (F.paramHasAttr(Idx, Attribute::StructRet))
5945 Flags.setSRet();
5946 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
5947 Flags.setByVal();
5948 const PointerType *Ty = cast<PointerType>(I->getType());
5949 const Type *ElementTy = Ty->getElementType();
5950 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
5951 unsigned FrameSize = TD->getTypeAllocSize(ElementTy);
5952 // For ByVal, alignment should be passed from FE. BE will guess if
5953 // this info is not there but there are cases it cannot get right.
5954 if (F.getParamAlignment(Idx))
5955 FrameAlign = F.getParamAlignment(Idx);
5956 Flags.setByValAlign(FrameAlign);
5957 Flags.setByValSize(FrameSize);
5958 }
5959 if (F.paramHasAttr(Idx, Attribute::Nest))
5960 Flags.setNest();
5961 Flags.setOrigAlign(OriginalAlignment);
5962
Owen Anderson23b9b192009-08-12 00:36:31 +00005963 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5964 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00005965 for (unsigned i = 0; i != NumRegs; ++i) {
5966 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
5967 if (NumRegs > 1 && i == 0)
5968 MyFlags.Flags.setSplit();
5969 // if it isn't first piece, alignment must be 1
5970 else if (i > 0)
5971 MyFlags.Flags.setOrigAlign(1);
5972 Ins.push_back(MyFlags);
5973 }
5974 }
5975 }
5976
5977 // Call the target to set up the argument values.
5978 SmallVector<SDValue, 8> InVals;
5979 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
5980 F.isVarArg(), Ins,
5981 dl, DAG, InVals);
Dan Gohman5e866062009-08-06 15:37:27 +00005982
5983 // Verify that the target's LowerFormalArguments behaved as expected.
Owen Anderson825b72b2009-08-11 20:47:22 +00005984 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
Dan Gohman5e866062009-08-06 15:37:27 +00005985 "LowerFormalArguments didn't return a valid chain!");
5986 assert(InVals.size() == Ins.size() &&
5987 "LowerFormalArguments didn't emit the correct number of values!");
Bill Wendling3ea58b62009-12-22 21:35:02 +00005988 DEBUG({
5989 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5990 assert(InVals[i].getNode() &&
5991 "LowerFormalArguments emitted a null value!");
5992 assert(Ins[i].VT == InVals[i].getValueType() &&
5993 "LowerFormalArguments emitted a value with the wrong type!");
5994 }
5995 });
Bill Wendling3ea3c242009-12-22 02:10:19 +00005996
Dan Gohman5e866062009-08-06 15:37:27 +00005997 // Update the DAG with the new chain value resulting from argument lowering.
Dan Gohman98ca4f22009-08-05 01:29:28 +00005998 DAG.setRoot(NewRoot);
5999
6000 // Set up the argument values.
6001 unsigned i = 0;
6002 Idx = 1;
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006003 if (!FLI.CanLowerReturn) {
6004 // Create a virtual register for the sret pointer, and put in a copy
6005 // from the sret argument into it.
6006 SmallVector<EVT, 1> ValueVTs;
6007 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6008 EVT VT = ValueVTs[0];
6009 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6010 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Bill Wendling46ada192010-03-02 01:55:18 +00006011 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
Bill Wendling3ea3c242009-12-22 02:10:19 +00006012 RegVT, VT, AssertOp);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006013
Dan Gohman2048b852009-11-23 18:04:58 +00006014 MachineFunction& MF = SDB->DAG.getMachineFunction();
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006015 MachineRegisterInfo& RegInfo = MF.getRegInfo();
6016 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
6017 FLI.DemoteRegister = SRetReg;
Mikhail Glushenkovb3c01992010-01-01 04:41:22 +00006018 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(),
6019 SRetReg, ArgValue);
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006020 DAG.setRoot(NewRoot);
Bill Wendling3ea3c242009-12-22 02:10:19 +00006021
Kenneth Uildriksc158dde2009-11-11 19:59:24 +00006022 // i indexes lowered arguments. Bump it past the hidden sret argument.
6023 // Idx indexes LLVM arguments. Don't touch it.
6024 ++i;
6025 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006026
Dan Gohman98ca4f22009-08-05 01:29:28 +00006027 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
6028 ++I, ++Idx) {
6029 SmallVector<SDValue, 4> ArgValues;
Owen Andersone50ed302009-08-10 22:56:29 +00006030 SmallVector<EVT, 4> ValueVTs;
Dan Gohman98ca4f22009-08-05 01:29:28 +00006031 ComputeValueVTs(TLI, I->getType(), ValueVTs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006032 unsigned NumValues = ValueVTs.size();
Dan Gohman98ca4f22009-08-05 01:29:28 +00006033 for (unsigned Value = 0; Value != NumValues; ++Value) {
Owen Andersone50ed302009-08-10 22:56:29 +00006034 EVT VT = ValueVTs[Value];
Owen Anderson23b9b192009-08-12 00:36:31 +00006035 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6036 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohman98ca4f22009-08-05 01:29:28 +00006037
6038 if (!I->use_empty()) {
6039 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6040 if (F.paramHasAttr(Idx, Attribute::SExt))
6041 AssertOp = ISD::AssertSext;
6042 else if (F.paramHasAttr(Idx, Attribute::ZExt))
6043 AssertOp = ISD::AssertZext;
6044
Bill Wendling46ada192010-03-02 01:55:18 +00006045 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
Bill Wendling3ea3c242009-12-22 02:10:19 +00006046 NumParts, PartVT, VT,
6047 AssertOp));
Dan Gohman98ca4f22009-08-05 01:29:28 +00006048 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006049
Dan Gohman98ca4f22009-08-05 01:29:28 +00006050 i += NumParts;
6051 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006052
Dan Gohman98ca4f22009-08-05 01:29:28 +00006053 if (!I->use_empty()) {
Evan Cheng8e36a5c2010-03-29 21:27:30 +00006054 SDValue Res;
6055 if (!ArgValues.empty())
6056 Res = DAG.getMergeValues(&ArgValues[0], NumValues,
6057 SDB->getCurDebugLoc());
Bill Wendling3ea3c242009-12-22 02:10:19 +00006058 SDB->setValue(I, Res);
6059
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006060 // If this argument is live outside of the entry block, insert a copy from
6061 // whereever we got it to the vreg that other BB's will reference it as.
Dan Gohman2048b852009-11-23 18:04:58 +00006062 SDB->CopyToExportRegsIfNeeded(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006063 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006064 }
Bill Wendling3ea3c242009-12-22 02:10:19 +00006065
Dan Gohman98ca4f22009-08-05 01:29:28 +00006066 assert(i == InVals.size() && "Argument register count mismatch!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006067
6068 // Finally, if the target has anything special to do, allow it to do so.
6069 // FIXME: this should insert code into the DAG!
Dan Gohman2048b852009-11-23 18:04:58 +00006070 EmitFunctionEntryCode(F, SDB->DAG.getMachineFunction());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006071}
6072
6073/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
6074/// ensure constants are generated when needed. Remember the virtual registers
6075/// that need to be added to the Machine PHI nodes as input. We cannot just
6076/// directly add them, because expansion might result in multiple MBB's for one
6077/// BB. As such, the start of the BB might correspond to a different MBB than
6078/// the end.
6079///
6080void
6081SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
6082 TerminatorInst *TI = LLVMBB->getTerminator();
6083
6084 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6085
6086 // Check successor nodes' PHI nodes that expect a constant to be available
6087 // from this block.
6088 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6089 BasicBlock *SuccBB = TI->getSuccessor(succ);
6090 if (!isa<PHINode>(SuccBB->begin())) continue;
6091 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006092
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006093 // If this terminator has multiple identical successors (common for
6094 // switches), only handle each succ once.
6095 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006096
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006097 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6098 PHINode *PN;
6099
6100 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6101 // nodes and Machine PHI nodes, but the incoming operands have not been
6102 // emitted yet.
6103 for (BasicBlock::iterator I = SuccBB->begin();
6104 (PN = dyn_cast<PHINode>(I)); ++I) {
6105 // Ignore dead phi's.
6106 if (PN->use_empty()) continue;
6107
6108 unsigned Reg;
6109 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6110
6111 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
Dan Gohman2048b852009-11-23 18:04:58 +00006112 unsigned &RegOut = SDB->ConstantsOut[C];
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006113 if (RegOut == 0) {
6114 RegOut = FuncInfo->CreateRegForValue(C);
Dan Gohman2048b852009-11-23 18:04:58 +00006115 SDB->CopyValueToVirtualRegister(C, RegOut);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006116 }
6117 Reg = RegOut;
6118 } else {
6119 Reg = FuncInfo->ValueMap[PHIOp];
6120 if (Reg == 0) {
6121 assert(isa<AllocaInst>(PHIOp) &&
6122 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
6123 "Didn't codegen value into a register!??");
6124 Reg = FuncInfo->CreateRegForValue(PHIOp);
Dan Gohman2048b852009-11-23 18:04:58 +00006125 SDB->CopyValueToVirtualRegister(PHIOp, Reg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006126 }
6127 }
6128
6129 // Remember that this register needs to added to the machine PHI node as
6130 // the input for this MBB.
Owen Andersone50ed302009-08-10 22:56:29 +00006131 SmallVector<EVT, 4> ValueVTs;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006132 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6133 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
Owen Andersone50ed302009-08-10 22:56:29 +00006134 EVT VT = ValueVTs[vti];
Owen Anderson23b9b192009-08-12 00:36:31 +00006135 unsigned NumRegisters = TLI.getNumRegisters(*CurDAG->getContext(), VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006136 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
Dan Gohman2048b852009-11-23 18:04:58 +00006137 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006138 Reg += NumRegisters;
6139 }
6140 }
6141 }
Dan Gohman2048b852009-11-23 18:04:58 +00006142 SDB->ConstantsOut.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006143}
6144
Dan Gohman3df24e62008-09-03 23:12:08 +00006145/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
6146/// supports legal types, and it emits MachineInstrs directly instead of
6147/// creating SelectionDAG nodes.
6148///
6149bool
6150SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
6151 FastISel *F) {
6152 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006153
Dan Gohman3df24e62008-09-03 23:12:08 +00006154 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
Dan Gohman2048b852009-11-23 18:04:58 +00006155 unsigned OrigNumPHINodesToUpdate = SDB->PHINodesToUpdate.size();
Dan Gohman3df24e62008-09-03 23:12:08 +00006156
6157 // Check successor nodes' PHI nodes that expect a constant to be available
6158 // from this block.
6159 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6160 BasicBlock *SuccBB = TI->getSuccessor(succ);
6161 if (!isa<PHINode>(SuccBB->begin())) continue;
6162 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006163
Dan Gohman3df24e62008-09-03 23:12:08 +00006164 // If this terminator has multiple identical successors (common for
6165 // switches), only handle each succ once.
6166 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006167
Dan Gohman3df24e62008-09-03 23:12:08 +00006168 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6169 PHINode *PN;
6170
6171 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6172 // nodes and Machine PHI nodes, but the incoming operands have not been
6173 // emitted yet.
6174 for (BasicBlock::iterator I = SuccBB->begin();
6175 (PN = dyn_cast<PHINode>(I)); ++I) {
6176 // Ignore dead phi's.
6177 if (PN->use_empty()) continue;
6178
6179 // Only handle legal types. Two interesting things to note here. First,
6180 // by bailing out early, we may leave behind some dead instructions,
6181 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
6182 // own moves. Second, this check is necessary becuase FastISel doesn't
6183 // use CreateRegForValue to create registers, so it always creates
6184 // exactly one register for each non-void instruction.
Owen Andersone50ed302009-08-10 22:56:29 +00006185 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
Owen Anderson825b72b2009-08-11 20:47:22 +00006186 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
6187 // Promote MVT::i1.
6188 if (VT == MVT::i1)
Owen Anderson23b9b192009-08-12 00:36:31 +00006189 VT = TLI.getTypeToTransformTo(*CurDAG->getContext(), VT);
Dan Gohman74321ab2008-09-10 21:01:31 +00006190 else {
Dan Gohman2048b852009-11-23 18:04:58 +00006191 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
Dan Gohman74321ab2008-09-10 21:01:31 +00006192 return false;
6193 }
Dan Gohman3df24e62008-09-03 23:12:08 +00006194 }
6195
6196 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6197
6198 unsigned Reg = F->getRegForValue(PHIOp);
6199 if (Reg == 0) {
Dan Gohman2048b852009-11-23 18:04:58 +00006200 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
Dan Gohman3df24e62008-09-03 23:12:08 +00006201 return false;
6202 }
Dan Gohman2048b852009-11-23 18:04:58 +00006203 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
Dan Gohman3df24e62008-09-03 23:12:08 +00006204 }
6205 }
6206
6207 return true;
6208}