blob: 982177cf61e5ac240641b0b8a6ac0f3ed5ee492d [file] [log] [blame]
Dan Gohman13aeef92008-09-03 16:12:24 +00001//===-- SelectionDAGBuild.cpp - Selection-DAG building --------------------===//
2//
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"
15#include "SelectionDAGBuild.h"
16#include "llvm/ADT/BitVector.h"
Dan Gohmana76b3592008-09-04 20:49:27 +000017#include "llvm/ADT/SmallSet.h"
Dan Gohman13aeef92008-09-03 16:12:24 +000018#include "llvm/Analysis/AliasAnalysis.h"
19#include "llvm/Constants.h"
20#include "llvm/CallingConv.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/Function.h"
23#include "llvm/GlobalVariable.h"
24#include "llvm/InlineAsm.h"
25#include "llvm/Instructions.h"
26#include "llvm/Intrinsics.h"
27#include "llvm/IntrinsicInst.h"
Bill Wendling6d54ef92008-11-06 02:29:10 +000028#include "llvm/Module.h"
Dan Gohman13aeef92008-09-03 16:12:24 +000029#include "llvm/CodeGen/FastISel.h"
30#include "llvm/CodeGen/GCStrategy.h"
31#include "llvm/CodeGen/GCMetadata.h"
32#include "llvm/CodeGen/MachineFunction.h"
33#include "llvm/CodeGen/MachineFrameInfo.h"
34#include "llvm/CodeGen/MachineInstrBuilder.h"
35#include "llvm/CodeGen/MachineJumpTableInfo.h"
36#include "llvm/CodeGen/MachineModuleInfo.h"
37#include "llvm/CodeGen/MachineRegisterInfo.h"
Bill Wendling6d54ef92008-11-06 02:29:10 +000038#include "llvm/CodeGen/PseudoSourceValue.h"
Dan Gohman13aeef92008-09-03 16:12:24 +000039#include "llvm/CodeGen/SelectionDAG.h"
Devang Patelfcf1c752009-01-13 00:35:13 +000040#include "llvm/CodeGen/DwarfWriter.h"
41#include "llvm/Analysis/DebugInfo.h"
Dan Gohman13aeef92008-09-03 16:12:24 +000042#include "llvm/Target/TargetRegisterInfo.h"
43#include "llvm/Target/TargetData.h"
44#include "llvm/Target/TargetFrameInfo.h"
45#include "llvm/Target/TargetInstrInfo.h"
46#include "llvm/Target/TargetLowering.h"
47#include "llvm/Target/TargetMachine.h"
48#include "llvm/Target/TargetOptions.h"
49#include "llvm/Support/Compiler.h"
Mikhail Glushenkov61fc6c82009-01-16 07:02:28 +000050#include "llvm/Support/CommandLine.h"
Dan Gohman13aeef92008-09-03 16:12:24 +000051#include "llvm/Support/Debug.h"
52#include "llvm/Support/MathExtras.h"
Anton Korobeynikovf5b5f6b2008-12-23 22:26:18 +000053#include "llvm/Support/raw_ostream.h"
Dan Gohman13aeef92008-09-03 16:12:24 +000054#include <algorithm>
55using namespace llvm;
56
Dale Johannesend93d7992008-09-05 01:48:15 +000057/// LimitFloatPrecision - Generate low-precision inline sequences for
58/// some float libcalls (6, 8 or 12 bits).
59static unsigned LimitFloatPrecision;
60
61static cl::opt<unsigned, true>
62LimitFPPrecision("limit-float-precision",
63 cl::desc("Generate low-precision inline sequences "
64 "for some float libcalls"),
65 cl::location(LimitFloatPrecision),
66 cl::init(0));
67
Dan Gohman13aeef92008-09-03 16:12:24 +000068/// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
Dan Gohmanfe3972f2009-01-06 22:53:52 +000069/// of insertvalue or extractvalue indices that identify a member, return
Dan Gohman13aeef92008-09-03 16:12:24 +000070/// the linearized index of the start of the member.
71///
72static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
73 const unsigned *Indices,
74 const unsigned *IndicesEnd,
75 unsigned CurIndex = 0) {
76 // Base case: We're done.
77 if (Indices && Indices == IndicesEnd)
78 return CurIndex;
79
80 // Given a struct type, recursively traverse the elements.
81 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
82 for (StructType::element_iterator EB = STy->element_begin(),
83 EI = EB,
84 EE = STy->element_end();
85 EI != EE; ++EI) {
86 if (Indices && *Indices == unsigned(EI - EB))
87 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
88 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
89 }
Dan Gohmanfe3972f2009-01-06 22:53:52 +000090 return CurIndex;
Dan Gohman13aeef92008-09-03 16:12:24 +000091 }
92 // Given an array type, recursively traverse the elements.
93 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
94 const Type *EltTy = ATy->getElementType();
95 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
96 if (Indices && *Indices == i)
97 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
98 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
99 }
Dan Gohmanfe3972f2009-01-06 22:53:52 +0000100 return CurIndex;
Dan Gohman13aeef92008-09-03 16:12:24 +0000101 }
102 // We haven't found the type we're looking for, so keep searching.
103 return CurIndex + 1;
104}
105
106/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
107/// MVTs that represent all the individual underlying
108/// non-aggregate types that comprise it.
109///
110/// If Offsets is non-null, it points to a vector to be filled in
111/// with the in-memory offsets of each of the individual values.
112///
113static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
114 SmallVectorImpl<MVT> &ValueVTs,
115 SmallVectorImpl<uint64_t> *Offsets = 0,
116 uint64_t StartingOffset = 0) {
117 // Given a struct type, recursively traverse the elements.
118 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
119 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
120 for (StructType::element_iterator EB = STy->element_begin(),
121 EI = EB,
122 EE = STy->element_end();
123 EI != EE; ++EI)
124 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
125 StartingOffset + SL->getElementOffset(EI - EB));
126 return;
127 }
128 // Given an array type, recursively traverse the elements.
129 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
130 const Type *EltTy = ATy->getElementType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000131 uint64_t EltSize = TLI.getTargetData()->getTypePaddedSize(EltTy);
Dan Gohman13aeef92008-09-03 16:12:24 +0000132 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
133 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
134 StartingOffset + i * EltSize);
135 return;
136 }
137 // Base case: we can get an MVT for this LLVM IR type.
138 ValueVTs.push_back(TLI.getValueType(Ty));
139 if (Offsets)
140 Offsets->push_back(StartingOffset);
141}
142
Dan Gohman92f8b6c2008-09-03 23:18:39 +0000143namespace llvm {
Dan Gohman13aeef92008-09-03 16:12:24 +0000144 /// RegsForValue - This struct represents the registers (physical or virtual)
145 /// that a particular set of values is assigned, and the type information about
146 /// the value. The most common situation is to represent one value at a time,
147 /// but struct or array values are handled element-wise as multiple values.
148 /// The splitting of aggregates is performed recursively, so that we never
149 /// have aggregate-typed registers. The values at this point do not necessarily
150 /// have legal types, so each value may require one or more registers of some
151 /// legal type.
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000152 ///
Dan Gohman13aeef92008-09-03 16:12:24 +0000153 struct VISIBILITY_HIDDEN RegsForValue {
154 /// TLI - The TargetLowering object.
155 ///
156 const TargetLowering *TLI;
157
158 /// ValueVTs - The value types of the values, which may not be legal, and
159 /// may need be promoted or synthesized from one or more registers.
160 ///
161 SmallVector<MVT, 4> ValueVTs;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000162
Dan Gohman13aeef92008-09-03 16:12:24 +0000163 /// RegVTs - The value types of the registers. This is the same size as
164 /// ValueVTs and it records, for each value, what the type of the assigned
165 /// register or registers are. (Individual values are never synthesized
166 /// from more than one type of register.)
167 ///
168 /// With virtual registers, the contents of RegVTs is redundant with TLI's
169 /// getRegisterType member function, however when with physical registers
170 /// it is necessary to have a separate record of the types.
171 ///
172 SmallVector<MVT, 4> RegVTs;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000173
Dan Gohman13aeef92008-09-03 16:12:24 +0000174 /// Regs - This list holds the registers assigned to the values.
175 /// Each legal or promoted value requires one register, and each
176 /// expanded value requires multiple registers.
177 ///
178 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000179
Dan Gohman13aeef92008-09-03 16:12:24 +0000180 RegsForValue() : TLI(0) {}
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000181
Dan Gohman13aeef92008-09-03 16:12:24 +0000182 RegsForValue(const TargetLowering &tli,
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000183 const SmallVector<unsigned, 4> &regs,
Dan Gohman13aeef92008-09-03 16:12:24 +0000184 MVT regvt, MVT valuevt)
185 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
186 RegsForValue(const TargetLowering &tli,
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000187 const SmallVector<unsigned, 4> &regs,
Dan Gohman13aeef92008-09-03 16:12:24 +0000188 const SmallVector<MVT, 4> &regvts,
189 const SmallVector<MVT, 4> &valuevts)
190 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
191 RegsForValue(const TargetLowering &tli,
192 unsigned Reg, const Type *Ty) : TLI(&tli) {
193 ComputeValueVTs(tli, Ty, ValueVTs);
194
195 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
196 MVT ValueVT = ValueVTs[Value];
197 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
198 MVT RegisterVT = TLI->getRegisterType(ValueVT);
199 for (unsigned i = 0; i != NumRegs; ++i)
200 Regs.push_back(Reg + i);
201 RegVTs.push_back(RegisterVT);
202 Reg += NumRegs;
203 }
204 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000205
Dan Gohman13aeef92008-09-03 16:12:24 +0000206 /// append - Add the specified values to this one.
207 void append(const RegsForValue &RHS) {
208 TLI = RHS.TLI;
209 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
210 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
211 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
212 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000213
214
Dan Gohman13aeef92008-09-03 16:12:24 +0000215 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000216 /// this value and returns the result as a ValueVTs value. This uses
Dan Gohman13aeef92008-09-03 16:12:24 +0000217 /// Chain/Flag as the input and updates them for the output Chain/Flag.
218 /// If the Flag pointer is NULL, no flag is used.
219 SDValue getCopyFromRegs(SelectionDAG &DAG,
220 SDValue &Chain, SDValue *Flag) const;
221
222 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000223 /// specified value into the registers specified by this object. This uses
Dan Gohman13aeef92008-09-03 16:12:24 +0000224 /// Chain/Flag as the input and updates them for the output Chain/Flag.
225 /// If the Flag pointer is NULL, no flag is used.
226 void getCopyToRegs(SDValue Val, SelectionDAG &DAG,
227 SDValue &Chain, SDValue *Flag) const;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000228
Dan Gohman13aeef92008-09-03 16:12:24 +0000229 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000230 /// operand list. This adds the code marker and includes the number of
Dan Gohman13aeef92008-09-03 16:12:24 +0000231 /// values added into it.
232 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
233 std::vector<SDValue> &Ops) const;
234 };
235}
236
237/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000238/// PHI nodes or outside of the basic block that defines it, or used by a
Dan Gohman13aeef92008-09-03 16:12:24 +0000239/// switch or atomic instruction, which may expand to multiple basic blocks.
240static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
241 if (isa<PHINode>(I)) return true;
242 BasicBlock *BB = I->getParent();
243 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
244 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
245 // FIXME: Remove switchinst special case.
246 isa<SwitchInst>(*UI))
247 return true;
248 return false;
249}
250
251/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
252/// entry block, return true. This includes arguments used by switches, since
253/// the switch may expand into multiple basic blocks.
254static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
255 // With FastISel active, we may be splitting blocks, so force creation
256 // of virtual registers for all non-dead arguments.
Dan Gohman78ae76d2008-09-25 17:05:24 +0000257 // Don't force virtual registers for byval arguments though, because
258 // fast-isel can't handle those in all cases.
259 if (EnableFastISel && !A->hasByValAttr())
Dan Gohman13aeef92008-09-03 16:12:24 +0000260 return A->use_empty();
261
262 BasicBlock *Entry = A->getParent()->begin();
263 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
264 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
265 return false; // Use not in entry block.
266 return true;
267}
268
269FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
270 : TLI(tli) {
271}
272
273void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
274 bool EnableFastISel) {
275 Fn = &fn;
276 MF = &mf;
277 RegInfo = &MF->getRegInfo();
278
279 // Create a vreg for each argument register that is not dead and is used
280 // outside of the entry block for the function.
281 for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
282 AI != E; ++AI)
283 if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
284 InitializeRegForValue(AI);
285
286 // Initialize the mapping of values to registers. This is only set up for
287 // instruction values that are used outside of the block that defines
288 // them.
289 Function::iterator BB = Fn->begin(), EB = Fn->end();
290 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
291 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
292 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
293 const Type *Ty = AI->getAllocatedType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +0000294 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000295 unsigned Align =
Dan Gohman13aeef92008-09-03 16:12:24 +0000296 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
297 AI->getAlignment());
298
299 TySize *= CUI->getZExtValue(); // Get total allocated size.
300 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
301 StaticAllocaMap[AI] =
302 MF->getFrameInfo()->CreateStackObject(TySize, Align);
303 }
304
305 for (; BB != EB; ++BB)
306 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
307 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
308 if (!isa<AllocaInst>(I) ||
309 !StaticAllocaMap.count(cast<AllocaInst>(I)))
310 InitializeRegForValue(I);
311
312 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
313 // also creates the initial PHI MachineInstrs, though none of the input
314 // operands are populated.
315 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
316 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
317 MBBMap[BB] = MBB;
318 MF->push_back(MBB);
319
320 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
321 // appropriate.
322 PHINode *PN;
323 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
324 if (PN->use_empty()) continue;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000325
Dan Gohman13aeef92008-09-03 16:12:24 +0000326 unsigned PHIReg = ValueMap[PN];
327 assert(PHIReg && "PHI node does not have an assigned virtual register!");
328
329 SmallVector<MVT, 4> ValueVTs;
330 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
331 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
332 MVT VT = ValueVTs[vti];
333 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohman404e8542008-09-04 15:39:15 +0000334 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Dan Gohman13aeef92008-09-03 16:12:24 +0000335 for (unsigned i = 0; i != NumRegisters; ++i)
336 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
337 PHIReg += NumRegisters;
338 }
339 }
340 }
341}
342
343unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
344 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
345}
346
347/// CreateRegForValue - Allocate the appropriate number of virtual registers of
348/// the correctly promoted or expanded types. Assign these registers
349/// consecutive vreg numbers and return the first assigned number.
350///
351/// In the case that the given value has struct or array type, this function
352/// will assign registers for each member or element.
353///
354unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
355 SmallVector<MVT, 4> ValueVTs;
356 ComputeValueVTs(TLI, V->getType(), ValueVTs);
357
358 unsigned FirstReg = 0;
359 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
360 MVT ValueVT = ValueVTs[Value];
361 MVT RegisterVT = TLI.getRegisterType(ValueVT);
362
363 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
364 for (unsigned i = 0; i != NumRegs; ++i) {
365 unsigned R = MakeReg(RegisterVT);
366 if (!FirstReg) FirstReg = R;
367 }
368 }
369 return FirstReg;
370}
371
372/// getCopyFromParts - Create a value that contains the specified legal parts
373/// combined into the value they represent. If the parts combine to a type
374/// larger then ValueVT then AssertOp can be used to specify whether the extra
375/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
376/// (ISD::AssertSext).
377static SDValue getCopyFromParts(SelectionDAG &DAG,
378 const SDValue *Parts,
379 unsigned NumParts,
380 MVT PartVT,
381 MVT ValueVT,
382 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
383 assert(NumParts > 0 && "No parts to assemble!");
Dan Gohmana0c429e2009-01-15 16:58:17 +0000384 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman13aeef92008-09-03 16:12:24 +0000385 SDValue Val = Parts[0];
386
387 if (NumParts > 1) {
388 // Assemble the value from multiple parts.
389 if (!ValueVT.isVector()) {
390 unsigned PartBits = PartVT.getSizeInBits();
391 unsigned ValueBits = ValueVT.getSizeInBits();
392
393 // Assemble the power of 2 part.
394 unsigned RoundParts = NumParts & (NumParts - 1) ?
395 1 << Log2_32(NumParts) : NumParts;
396 unsigned RoundBits = PartBits * RoundParts;
397 MVT RoundVT = RoundBits == ValueBits ?
398 ValueVT : MVT::getIntegerVT(RoundBits);
399 SDValue Lo, Hi;
400
Duncan Sands70269a72008-10-29 14:22:20 +0000401 MVT HalfVT = ValueVT.isInteger() ?
402 MVT::getIntegerVT(RoundBits/2) :
403 MVT::getFloatingPointVT(RoundBits/2);
404
Dan Gohman13aeef92008-09-03 16:12:24 +0000405 if (RoundParts > 2) {
Dan Gohman13aeef92008-09-03 16:12:24 +0000406 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
407 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
408 PartVT, HalfVT);
409 } else {
Duncan Sands70269a72008-10-29 14:22:20 +0000410 Lo = DAG.getNode(ISD::BIT_CONVERT, HalfVT, Parts[0]);
411 Hi = DAG.getNode(ISD::BIT_CONVERT, HalfVT, Parts[1]);
Dan Gohman13aeef92008-09-03 16:12:24 +0000412 }
413 if (TLI.isBigEndian())
414 std::swap(Lo, Hi);
415 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
416
417 if (RoundParts < NumParts) {
418 // Assemble the trailing non-power-of-2 part.
419 unsigned OddParts = NumParts - RoundParts;
420 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
421 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
422
423 // Combine the round and odd parts.
424 Lo = Val;
425 if (TLI.isBigEndian())
426 std::swap(Lo, Hi);
427 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
428 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
429 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
430 DAG.getConstant(Lo.getValueType().getSizeInBits(),
431 TLI.getShiftAmountTy()));
432 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
433 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
434 }
435 } else {
436 // Handle a multi-element vector.
437 MVT IntermediateVT, RegisterVT;
438 unsigned NumIntermediates;
439 unsigned NumRegs =
440 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
441 RegisterVT);
442 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
443 NumParts = NumRegs; // Silence a compiler warning.
444 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
445 assert(RegisterVT == Parts[0].getValueType() &&
446 "Part type doesn't match part!");
447
448 // Assemble the parts into intermediate operands.
449 SmallVector<SDValue, 8> Ops(NumIntermediates);
450 if (NumIntermediates == NumParts) {
451 // If the register was not expanded, truncate or copy the value,
452 // as appropriate.
453 for (unsigned i = 0; i != NumParts; ++i)
454 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
455 PartVT, IntermediateVT);
456 } else if (NumParts > 0) {
457 // If the intermediate type was expanded, build the intermediate operands
458 // from the parts.
459 assert(NumParts % NumIntermediates == 0 &&
460 "Must expand into a divisible number of parts!");
461 unsigned Factor = NumParts / NumIntermediates;
462 for (unsigned i = 0; i != NumIntermediates; ++i)
463 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
464 PartVT, IntermediateVT);
465 }
466
467 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
468 // operands.
469 Val = DAG.getNode(IntermediateVT.isVector() ?
470 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
471 ValueVT, &Ops[0], NumIntermediates);
472 }
473 }
474
475 // There is now one part, held in Val. Correct it to match ValueVT.
476 PartVT = Val.getValueType();
477
478 if (PartVT == ValueVT)
479 return Val;
480
481 if (PartVT.isVector()) {
482 assert(ValueVT.isVector() && "Unknown vector conversion!");
483 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
484 }
485
486 if (ValueVT.isVector()) {
487 assert(ValueVT.getVectorElementType() == PartVT &&
488 ValueVT.getVectorNumElements() == 1 &&
489 "Only trivial scalar-to-vector conversions should get here!");
490 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
491 }
492
493 if (PartVT.isInteger() &&
494 ValueVT.isInteger()) {
495 if (ValueVT.bitsLT(PartVT)) {
496 // For a truncate, see if we have any information to
497 // indicate whether the truncated bits will always be
498 // zero or sign-extension.
499 if (AssertOp != ISD::DELETED_NODE)
500 Val = DAG.getNode(AssertOp, PartVT, Val,
501 DAG.getValueType(ValueVT));
502 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
503 } else {
504 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
505 }
506 }
507
508 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
509 if (ValueVT.bitsLT(Val.getValueType()))
510 // FP_ROUND's are always exact here.
511 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
512 DAG.getIntPtrConstant(1));
513 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
514 }
515
516 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
517 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
518
519 assert(0 && "Unknown mismatch!");
520 return SDValue();
521}
522
523/// getCopyToParts - Create a series of nodes that contain the specified value
524/// split into legal parts. If the parts contain more bits than Val, then, for
525/// integers, ExtendKind can be used to specify how to generate the extra bits.
Chris Lattnerea90c032008-10-21 00:45:36 +0000526static void getCopyToParts(SelectionDAG &DAG, SDValue Val,
527 SDValue *Parts, unsigned NumParts, MVT PartVT,
Dan Gohman13aeef92008-09-03 16:12:24 +0000528 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohmana0c429e2009-01-15 16:58:17 +0000529 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohman13aeef92008-09-03 16:12:24 +0000530 MVT PtrVT = TLI.getPointerTy();
531 MVT ValueVT = Val.getValueType();
532 unsigned PartBits = PartVT.getSizeInBits();
533 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
534
535 if (!NumParts)
536 return;
537
538 if (!ValueVT.isVector()) {
539 if (PartVT == ValueVT) {
540 assert(NumParts == 1 && "No-op copy with multiple parts!");
541 Parts[0] = Val;
542 return;
543 }
544
545 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
546 // If the parts cover more bits than the value has, promote the value.
547 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
548 assert(NumParts == 1 && "Do not know what to promote to!");
549 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
550 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
551 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
552 Val = DAG.getNode(ExtendKind, ValueVT, Val);
553 } else {
554 assert(0 && "Unknown mismatch!");
555 }
556 } else if (PartBits == ValueVT.getSizeInBits()) {
557 // Different types of the same size.
558 assert(NumParts == 1 && PartVT != ValueVT);
559 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
560 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
561 // If the parts cover less bits than value has, truncate the value.
562 if (PartVT.isInteger() && ValueVT.isInteger()) {
563 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
564 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
565 } else {
566 assert(0 && "Unknown mismatch!");
567 }
568 }
569
570 // The value may have changed - recompute ValueVT.
571 ValueVT = Val.getValueType();
572 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
573 "Failed to tile the value with PartVT!");
574
575 if (NumParts == 1) {
576 assert(PartVT == ValueVT && "Type conversion failed!");
577 Parts[0] = Val;
578 return;
579 }
580
581 // Expand the value into multiple parts.
582 if (NumParts & (NumParts - 1)) {
583 // The number of parts is not a power of 2. Split off and copy the tail.
584 assert(PartVT.isInteger() && ValueVT.isInteger() &&
585 "Do not know what to expand to!");
586 unsigned RoundParts = 1 << Log2_32(NumParts);
587 unsigned RoundBits = RoundParts * PartBits;
588 unsigned OddParts = NumParts - RoundParts;
589 SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
590 DAG.getConstant(RoundBits,
591 TLI.getShiftAmountTy()));
592 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
593 if (TLI.isBigEndian())
594 // The odd parts were reversed by getCopyToParts - unreverse them.
595 std::reverse(Parts + RoundParts, Parts + NumParts);
596 NumParts = RoundParts;
597 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
598 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
599 }
600
601 // The number of parts is a power of 2. Repeatedly bisect the value using
602 // EXTRACT_ELEMENT.
603 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
604 MVT::getIntegerVT(ValueVT.getSizeInBits()),
605 Val);
606 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
607 for (unsigned i = 0; i < NumParts; i += StepSize) {
608 unsigned ThisBits = StepSize * PartBits / 2;
609 MVT ThisVT = MVT::getIntegerVT (ThisBits);
610 SDValue &Part0 = Parts[i];
611 SDValue &Part1 = Parts[i+StepSize/2];
612
613 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
614 DAG.getConstant(1, PtrVT));
615 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
616 DAG.getConstant(0, PtrVT));
617
618 if (ThisBits == PartBits && ThisVT != PartVT) {
619 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
620 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
621 }
622 }
623 }
624
625 if (TLI.isBigEndian())
626 std::reverse(Parts, Parts + NumParts);
627
628 return;
629 }
630
631 // Vector ValueVT.
632 if (NumParts == 1) {
633 if (PartVT != ValueVT) {
634 if (PartVT.isVector()) {
635 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
636 } else {
637 assert(ValueVT.getVectorElementType() == PartVT &&
638 ValueVT.getVectorNumElements() == 1 &&
639 "Only trivial vector-to-scalar conversions should get here!");
640 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
641 DAG.getConstant(0, PtrVT));
642 }
643 }
644
645 Parts[0] = Val;
646 return;
647 }
648
649 // Handle a multi-element vector.
650 MVT IntermediateVT, RegisterVT;
651 unsigned NumIntermediates;
Dan Gohmana0c429e2009-01-15 16:58:17 +0000652 unsigned NumRegs = TLI
Dan Gohman13aeef92008-09-03 16:12:24 +0000653 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
654 RegisterVT);
655 unsigned NumElements = ValueVT.getVectorNumElements();
656
657 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
658 NumParts = NumRegs; // Silence a compiler warning.
659 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
660
661 // Split the vector into intermediate operands.
662 SmallVector<SDValue, 8> Ops(NumIntermediates);
663 for (unsigned i = 0; i != NumIntermediates; ++i)
664 if (IntermediateVT.isVector())
665 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
666 IntermediateVT, Val,
667 DAG.getConstant(i * (NumElements / NumIntermediates),
668 PtrVT));
669 else
670 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000671 IntermediateVT, Val,
Dan Gohman13aeef92008-09-03 16:12:24 +0000672 DAG.getConstant(i, PtrVT));
673
674 // Split the intermediate operands into legal parts.
675 if (NumParts == NumIntermediates) {
676 // If the register was not expanded, promote or copy the value,
677 // as appropriate.
678 for (unsigned i = 0; i != NumParts; ++i)
679 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
680 } else if (NumParts > 0) {
681 // If the intermediate type was expanded, split each the value into
682 // legal parts.
683 assert(NumParts % NumIntermediates == 0 &&
684 "Must expand into a divisible number of parts!");
685 unsigned Factor = NumParts / NumIntermediates;
686 for (unsigned i = 0; i != NumIntermediates; ++i)
687 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
688 }
689}
690
691
692void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
693 AA = &aa;
694 GFI = gfi;
695 TD = DAG.getTarget().getTargetData();
696}
697
698/// clear - Clear out the curret SelectionDAG and the associated
699/// state and prepare this SelectionDAGLowering object to be used
700/// for a new block. This doesn't clear out information about
701/// additional blocks that are needed to complete switch lowering
702/// or PHI node updating; that information is cleared out as it is
703/// consumed.
704void SelectionDAGLowering::clear() {
705 NodeMap.clear();
706 PendingLoads.clear();
707 PendingExports.clear();
708 DAG.clear();
709}
710
711/// getRoot - Return the current virtual root of the Selection DAG,
712/// flushing any PendingLoad items. This must be done before emitting
713/// a store or any other node that may need to be ordered after any
714/// prior load instructions.
715///
716SDValue SelectionDAGLowering::getRoot() {
717 if (PendingLoads.empty())
718 return DAG.getRoot();
719
720 if (PendingLoads.size() == 1) {
721 SDValue Root = PendingLoads[0];
722 DAG.setRoot(Root);
723 PendingLoads.clear();
724 return Root;
725 }
726
727 // Otherwise, we have to make a token factor node.
728 SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
729 &PendingLoads[0], PendingLoads.size());
730 PendingLoads.clear();
731 DAG.setRoot(Root);
732 return Root;
733}
734
735/// getControlRoot - Similar to getRoot, but instead of flushing all the
736/// PendingLoad items, flush all the PendingExports items. It is necessary
737/// to do this before emitting a terminator instruction.
738///
739SDValue SelectionDAGLowering::getControlRoot() {
740 SDValue Root = DAG.getRoot();
741
742 if (PendingExports.empty())
743 return Root;
744
745 // Turn all of the CopyToReg chains into one factored node.
746 if (Root.getOpcode() != ISD::EntryToken) {
747 unsigned i = 0, e = PendingExports.size();
748 for (; i != e; ++i) {
749 assert(PendingExports[i].getNode()->getNumOperands() > 1);
750 if (PendingExports[i].getNode()->getOperand(0) == Root)
751 break; // Don't add the root if we already indirectly depend on it.
752 }
753
754 if (i == e)
755 PendingExports.push_back(Root);
756 }
757
758 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
759 &PendingExports[0],
760 PendingExports.size());
761 PendingExports.clear();
762 DAG.setRoot(Root);
763 return Root;
764}
765
766void SelectionDAGLowering::visit(Instruction &I) {
767 visit(I.getOpcode(), I);
768}
769
770void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
771 // Note: this doesn't use InstVisitor, because it has to work with
772 // ConstantExpr's in addition to instructions.
773 switch (Opcode) {
774 default: assert(0 && "Unknown instruction type encountered!");
775 abort();
776 // Build the switch statement using the Instruction.def file.
777#define HANDLE_INST(NUM, OPCODE, CLASS) \
778 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
779#include "llvm/Instruction.def"
780 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000781}
Dan Gohman13aeef92008-09-03 16:12:24 +0000782
783void SelectionDAGLowering::visitAdd(User &I) {
784 if (I.getType()->isFPOrFPVector())
785 visitBinary(I, ISD::FADD);
786 else
787 visitBinary(I, ISD::ADD);
788}
789
790void SelectionDAGLowering::visitMul(User &I) {
791 if (I.getType()->isFPOrFPVector())
792 visitBinary(I, ISD::FMUL);
793 else
794 visitBinary(I, ISD::MUL);
795}
796
797SDValue SelectionDAGLowering::getValue(const Value *V) {
798 SDValue &N = NodeMap[V];
799 if (N.getNode()) return N;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000800
Dan Gohman13aeef92008-09-03 16:12:24 +0000801 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
802 MVT VT = TLI.getValueType(V->getType(), true);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000803
Dan Gohman13aeef92008-09-03 16:12:24 +0000804 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohmanc1f3a072008-09-12 18:08:03 +0000805 return N = DAG.getConstant(*CI, VT);
Dan Gohman13aeef92008-09-03 16:12:24 +0000806
807 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
808 return N = DAG.getGlobalAddress(GV, VT);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000809
Dan Gohman13aeef92008-09-03 16:12:24 +0000810 if (isa<ConstantPointerNull>(C))
811 return N = DAG.getConstant(0, TLI.getPointerTy());
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000812
Dan Gohman13aeef92008-09-03 16:12:24 +0000813 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohmanc1f3a072008-09-12 18:08:03 +0000814 return N = DAG.getConstantFP(*CFP, VT);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000815
Dan Gohman13aeef92008-09-03 16:12:24 +0000816 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
817 !V->getType()->isAggregateType())
818 return N = DAG.getNode(ISD::UNDEF, VT);
819
820 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
821 visit(CE->getOpcode(), *CE);
822 SDValue N1 = NodeMap[V];
823 assert(N1.getNode() && "visit didn't populate the ValueMap!");
824 return N1;
825 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000826
Dan Gohman13aeef92008-09-03 16:12:24 +0000827 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
828 SmallVector<SDValue, 4> Constants;
829 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
830 OI != OE; ++OI) {
831 SDNode *Val = getValue(*OI).getNode();
832 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
833 Constants.push_back(SDValue(Val, i));
834 }
835 return DAG.getMergeValues(&Constants[0], Constants.size());
836 }
837
838 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
839 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
840 "Unknown struct or array constant!");
841
842 SmallVector<MVT, 4> ValueVTs;
843 ComputeValueVTs(TLI, C->getType(), ValueVTs);
844 unsigned NumElts = ValueVTs.size();
845 if (NumElts == 0)
846 return SDValue(); // empty struct
847 SmallVector<SDValue, 4> Constants(NumElts);
848 for (unsigned i = 0; i != NumElts; ++i) {
849 MVT EltVT = ValueVTs[i];
850 if (isa<UndefValue>(C))
851 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
852 else if (EltVT.isFloatingPoint())
853 Constants[i] = DAG.getConstantFP(0, EltVT);
854 else
855 Constants[i] = DAG.getConstant(0, EltVT);
856 }
857 return DAG.getMergeValues(&Constants[0], NumElts);
858 }
859
860 const VectorType *VecTy = cast<VectorType>(V->getType());
861 unsigned NumElements = VecTy->getNumElements();
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000862
Dan Gohman13aeef92008-09-03 16:12:24 +0000863 // Now that we know the number and type of the elements, get that number of
864 // elements into the Ops array based on what kind of constant it is.
865 SmallVector<SDValue, 16> Ops;
866 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
867 for (unsigned i = 0; i != NumElements; ++i)
868 Ops.push_back(getValue(CP->getOperand(i)));
869 } else {
870 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
871 "Unknown vector constant!");
872 MVT EltVT = TLI.getValueType(VecTy->getElementType());
873
874 SDValue Op;
875 if (isa<UndefValue>(C))
876 Op = DAG.getNode(ISD::UNDEF, EltVT);
877 else if (EltVT.isFloatingPoint())
878 Op = DAG.getConstantFP(0, EltVT);
879 else
880 Op = DAG.getConstant(0, EltVT);
881 Ops.assign(NumElements, Op);
882 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000883
Dan Gohman13aeef92008-09-03 16:12:24 +0000884 // Create a BUILD_VECTOR node.
885 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
886 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000887
Dan Gohman13aeef92008-09-03 16:12:24 +0000888 // If this is a static alloca, generate it as the frameindex instead of
889 // computation.
890 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
891 DenseMap<const AllocaInst*, int>::iterator SI =
892 FuncInfo.StaticAllocaMap.find(AI);
893 if (SI != FuncInfo.StaticAllocaMap.end())
894 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
895 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000896
Dan Gohman13aeef92008-09-03 16:12:24 +0000897 unsigned InReg = FuncInfo.ValueMap[V];
898 assert(InReg && "Value not in map!");
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000899
Dan Gohman13aeef92008-09-03 16:12:24 +0000900 RegsForValue RFV(TLI, InReg, V->getType());
901 SDValue Chain = DAG.getEntryNode();
902 return RFV.getCopyFromRegs(DAG, Chain, NULL);
903}
904
905
906void SelectionDAGLowering::visitRet(ReturnInst &I) {
907 if (I.getNumOperands() == 0) {
908 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
909 return;
910 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000911
Dan Gohman13aeef92008-09-03 16:12:24 +0000912 SmallVector<SDValue, 8> NewValues;
913 NewValues.push_back(getControlRoot());
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000914 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Dan Gohman13aeef92008-09-03 16:12:24 +0000915 SmallVector<MVT, 4> ValueVTs;
916 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
Dan Gohman79160592008-10-21 20:00:42 +0000917 unsigned NumValues = ValueVTs.size();
918 if (NumValues == 0) continue;
919
920 SDValue RetOp = getValue(I.getOperand(i));
921 for (unsigned j = 0, f = NumValues; j != f; ++j) {
Dan Gohman13aeef92008-09-03 16:12:24 +0000922 MVT VT = ValueVTs[j];
923
924 // FIXME: C calling convention requires the return type to be promoted to
Dale Johannesenc08a0e22008-09-25 20:47:45 +0000925 // at least 32-bit. But this is not necessary for non-C calling
926 // conventions.
Dan Gohman13aeef92008-09-03 16:12:24 +0000927 if (VT.isInteger()) {
928 MVT MinVT = TLI.getRegisterType(MVT::i32);
929 if (VT.bitsLT(MinVT))
930 VT = MinVT;
931 }
932
933 unsigned NumParts = TLI.getNumRegisters(VT);
934 MVT PartVT = TLI.getRegisterType(VT);
935 SmallVector<SDValue, 4> Parts(NumParts);
936 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000937
Dan Gohman13aeef92008-09-03 16:12:24 +0000938 const Function *F = I.getParent()->getParent();
Devang Pateld222f862008-09-25 21:00:45 +0000939 if (F->paramHasAttr(0, Attribute::SExt))
Dan Gohman13aeef92008-09-03 16:12:24 +0000940 ExtendKind = ISD::SIGN_EXTEND;
Devang Pateld222f862008-09-25 21:00:45 +0000941 else if (F->paramHasAttr(0, Attribute::ZExt))
Dan Gohman13aeef92008-09-03 16:12:24 +0000942 ExtendKind = ISD::ZERO_EXTEND;
943
944 getCopyToParts(DAG, SDValue(RetOp.getNode(), RetOp.getResNo() + j),
945 &Parts[0], NumParts, PartVT, ExtendKind);
946
Dale Johannesenc08a0e22008-09-25 20:47:45 +0000947 // 'inreg' on function refers to return value
948 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Devang Pateld222f862008-09-25 21:00:45 +0000949 if (F->paramHasAttr(0, Attribute::InReg))
Dale Johannesenc08a0e22008-09-25 20:47:45 +0000950 Flags.setInReg();
Dan Gohman13aeef92008-09-03 16:12:24 +0000951 for (unsigned i = 0; i < NumParts; ++i) {
952 NewValues.push_back(Parts[i]);
Dale Johannesenc08a0e22008-09-25 20:47:45 +0000953 NewValues.push_back(DAG.getArgFlags(Flags));
Dan Gohman13aeef92008-09-03 16:12:24 +0000954 }
955 }
956 }
957 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
958 &NewValues[0], NewValues.size()));
959}
960
961/// ExportFromCurrentBlock - If this condition isn't known to be exported from
962/// the current basic block, add it to ValueMap now so that we'll get a
963/// CopyTo/FromReg.
964void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
965 // No need to export constants.
966 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000967
Dan Gohman13aeef92008-09-03 16:12:24 +0000968 // Already exported?
969 if (FuncInfo.isExportedInst(V)) return;
970
971 unsigned Reg = FuncInfo.InitializeRegForValue(V);
972 CopyValueToVirtualRegister(V, Reg);
973}
974
975bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
976 const BasicBlock *FromBB) {
977 // The operands of the setcc have to be in this block. We don't know
978 // how to export them from some other block.
979 if (Instruction *VI = dyn_cast<Instruction>(V)) {
980 // Can export from current BB.
981 if (VI->getParent() == FromBB)
982 return true;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000983
Dan Gohman13aeef92008-09-03 16:12:24 +0000984 // Is already exported, noop.
985 return FuncInfo.isExportedInst(V);
986 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000987
Dan Gohman13aeef92008-09-03 16:12:24 +0000988 // If this is an argument, we can export it if the BB is the entry block or
989 // if it is already exported.
990 if (isa<Argument>(V)) {
991 if (FromBB == &FromBB->getParent()->getEntryBlock())
992 return true;
993
994 // Otherwise, can only export this if it is already exported.
995 return FuncInfo.isExportedInst(V);
996 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +0000997
Dan Gohman13aeef92008-09-03 16:12:24 +0000998 // Otherwise, constants can always be exported.
999 return true;
1000}
1001
1002static bool InBlock(const Value *V, const BasicBlock *BB) {
1003 if (const Instruction *I = dyn_cast<Instruction>(V))
1004 return I->getParent() == BB;
1005 return true;
1006}
1007
Dan Gohman9a1b1c42008-10-17 18:18:45 +00001008/// getFCmpCondCode - Return the ISD condition code corresponding to
1009/// the given LLVM IR floating-point condition code. This includes
1010/// consideration of global floating-point math flags.
1011///
1012static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1013 ISD::CondCode FPC, FOC;
1014 switch (Pred) {
1015 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1016 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1017 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1018 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1019 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1020 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1021 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1022 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1023 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1024 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1025 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1026 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1027 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1028 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1029 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1030 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1031 default:
1032 assert(0 && "Invalid FCmp predicate opcode!");
1033 FOC = FPC = ISD::SETFALSE;
1034 break;
1035 }
1036 if (FiniteOnlyFPMath())
1037 return FOC;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00001038 else
Dan Gohman9a1b1c42008-10-17 18:18:45 +00001039 return FPC;
1040}
1041
1042/// getICmpCondCode - Return the ISD condition code corresponding to
1043/// the given LLVM IR integer condition code.
1044///
1045static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1046 switch (Pred) {
1047 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1048 case ICmpInst::ICMP_NE: return ISD::SETNE;
1049 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1050 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1051 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1052 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1053 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1054 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1055 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1056 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1057 default:
1058 assert(0 && "Invalid ICmp predicate opcode!");
1059 return ISD::SETNE;
1060 }
1061}
1062
Dan Gohman001eaee2008-10-17 21:16:08 +00001063/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1064/// This function emits a branch and is used at the leaves of an OR or an
1065/// AND operator tree.
1066///
1067void
1068SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1069 MachineBasicBlock *TBB,
1070 MachineBasicBlock *FBB,
1071 MachineBasicBlock *CurBB) {
1072 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohman13aeef92008-09-03 16:12:24 +00001073
Dan Gohman001eaee2008-10-17 21:16:08 +00001074 // If the leaf of the tree is a comparison, merge the condition into
1075 // the caseblock.
1076 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1077 // The operands of the cmp have to be in this block. We don't know
1078 // how to export them from some other block. If this is the first block
1079 // of the sequence, no exporting is needed.
1080 if (CurBB == CurMBB ||
1081 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1082 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohman13aeef92008-09-03 16:12:24 +00001083 ISD::CondCode Condition;
1084 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman9a1b1c42008-10-17 18:18:45 +00001085 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohman13aeef92008-09-03 16:12:24 +00001086 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman9a1b1c42008-10-17 18:18:45 +00001087 Condition = getFCmpCondCode(FC->getPredicate());
Dan Gohman13aeef92008-09-03 16:12:24 +00001088 } else {
1089 Condition = ISD::SETEQ; // silence warning.
1090 assert(0 && "Unknown compare instruction");
1091 }
Dan Gohman001eaee2008-10-17 21:16:08 +00001092
1093 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohman13aeef92008-09-03 16:12:24 +00001094 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1095 SwitchCases.push_back(CB);
1096 return;
1097 }
Dan Gohman001eaee2008-10-17 21:16:08 +00001098 }
1099
1100 // Create a CaseBlock record representing this branch.
1101 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1102 NULL, TBB, FBB, CurBB);
1103 SwitchCases.push_back(CB);
1104}
1105
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00001106/// FindMergedConditions - If Cond is an expression like
Dan Gohman001eaee2008-10-17 21:16:08 +00001107void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1108 MachineBasicBlock *TBB,
1109 MachineBasicBlock *FBB,
1110 MachineBasicBlock *CurBB,
1111 unsigned Opc) {
1112 // If this node is not part of the or/and tree, emit it as a branch.
1113 Instruction *BOp = dyn_cast<Instruction>(Cond);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00001114 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohman001eaee2008-10-17 21:16:08 +00001115 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1116 BOp->getParent() != CurBB->getBasicBlock() ||
1117 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1118 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1119 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
Dan Gohman13aeef92008-09-03 16:12:24 +00001120 return;
1121 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00001122
Dan Gohman13aeef92008-09-03 16:12:24 +00001123 // Create TmpBB after CurBB.
1124 MachineFunction::iterator BBI = CurBB;
1125 MachineFunction &MF = DAG.getMachineFunction();
1126 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1127 CurBB->getParent()->insert(++BBI, TmpBB);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00001128
Dan Gohman13aeef92008-09-03 16:12:24 +00001129 if (Opc == Instruction::Or) {
1130 // Codegen X | Y as:
1131 // jmp_if_X TBB
1132 // jmp TmpBB
1133 // TmpBB:
1134 // jmp_if_Y TBB
1135 // jmp FBB
1136 //
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00001137
Dan Gohman13aeef92008-09-03 16:12:24 +00001138 // Emit the LHS condition.
1139 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00001140
Dan Gohman13aeef92008-09-03 16:12:24 +00001141 // Emit the RHS condition into TmpBB.
1142 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1143 } else {
1144 assert(Opc == Instruction::And && "Unknown merge op!");
1145 // Codegen X & Y as:
1146 // jmp_if_X TmpBB
1147 // jmp FBB
1148 // TmpBB:
1149 // jmp_if_Y TBB
1150 // jmp FBB
1151 //
1152 // This requires creation of TmpBB after CurBB.
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00001153
Dan Gohman13aeef92008-09-03 16:12:24 +00001154 // Emit the LHS condition.
1155 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00001156
Dan Gohman13aeef92008-09-03 16:12:24 +00001157 // Emit the RHS condition into TmpBB.
1158 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1159 }
1160}
1161
1162/// If the set of cases should be emitted as a series of branches, return true.
1163/// If we should emit this as a bunch of and/or'd together conditions, return
1164/// false.
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00001165bool
Dan Gohman13aeef92008-09-03 16:12:24 +00001166SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1167 if (Cases.size() != 2) return true;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00001168
Dan Gohman13aeef92008-09-03 16:12:24 +00001169 // If this is two comparisons of the same values or'd or and'd together, they
1170 // will get folded into a single comparison, so don't emit two blocks.
1171 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1172 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1173 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1174 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1175 return false;
1176 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00001177
Dan Gohman13aeef92008-09-03 16:12:24 +00001178 return true;
1179}
1180
1181void SelectionDAGLowering::visitBr(BranchInst &I) {
1182 // Update machine-CFG edges.
1183 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1184
1185 // Figure out which block is immediately after the current one.
1186 MachineBasicBlock *NextBlock = 0;
1187 MachineFunction::iterator BBI = CurMBB;
1188 if (++BBI != CurMBB->getParent()->end())
1189 NextBlock = BBI;
1190
1191 if (I.isUnconditional()) {
1192 // Update machine-CFG edges.
1193 CurMBB->addSuccessor(Succ0MBB);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00001194
Dan Gohman13aeef92008-09-03 16:12:24 +00001195 // If this is not a fall-through branch, emit the branch.
1196 if (Succ0MBB != NextBlock)
1197 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1198 DAG.getBasicBlock(Succ0MBB)));
1199 return;
1200 }
1201
1202 // If this condition is one of the special cases we handle, do special stuff
1203 // now.
1204 Value *CondVal = I.getCondition();
1205 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1206
1207 // If this is a series of conditions that are or'd or and'd together, emit
1208 // this as a sequence of branches instead of setcc's with and/or operations.
1209 // For example, instead of something like:
1210 // cmp A, B
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00001211 // C = seteq
Dan Gohman13aeef92008-09-03 16:12:24 +00001212 // cmp D, E
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00001213 // F = setle
Dan Gohman13aeef92008-09-03 16:12:24 +00001214 // or C, F
1215 // jnz foo
1216 // Emit:
1217 // cmp A, B
1218 // je foo
1219 // cmp D, E
1220 // jle foo
1221 //
1222 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00001223 if (BOp->hasOneUse() &&
Dan Gohman13aeef92008-09-03 16:12:24 +00001224 (BOp->getOpcode() == Instruction::And ||
1225 BOp->getOpcode() == Instruction::Or)) {
1226 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1227 // If the compares in later blocks need to use values not currently
1228 // exported from this block, export them now. This block should always
1229 // be the first entry.
1230 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00001231
Dan Gohman13aeef92008-09-03 16:12:24 +00001232 // Allow some cases to be rejected.
1233 if (ShouldEmitAsBranches(SwitchCases)) {
1234 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1235 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1236 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1237 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00001238
Dan Gohman13aeef92008-09-03 16:12:24 +00001239 // Emit the branch for this block.
1240 visitSwitchCase(SwitchCases[0]);
1241 SwitchCases.erase(SwitchCases.begin());
1242 return;
1243 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00001244
Dan Gohman13aeef92008-09-03 16:12:24 +00001245 // Okay, we decided not to do this, remove any inserted MBB's and clear
1246 // SwitchCases.
1247 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1248 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00001249
Dan Gohman13aeef92008-09-03 16:12:24 +00001250 SwitchCases.clear();
1251 }
1252 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00001253
Dan Gohman13aeef92008-09-03 16:12:24 +00001254 // Create a CaseBlock record representing this branch.
1255 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1256 NULL, Succ0MBB, Succ1MBB, CurMBB);
1257 // Use visitSwitchCase to actually insert the fast branch sequence for this
1258 // cond branch.
1259 visitSwitchCase(CB);
1260}
1261
1262/// visitSwitchCase - Emits the necessary code to represent a single node in
1263/// the binary search tree resulting from lowering a switch instruction.
1264void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1265 SDValue Cond;
1266 SDValue CondLHS = getValue(CB.CmpLHS);
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001267
1268 // Build the setcc now.
Dan Gohman13aeef92008-09-03 16:12:24 +00001269 if (CB.CmpMHS == NULL) {
1270 // Fold "(X == true)" to X and "(X == false)" to !X to
1271 // handle common cases produced by branch lowering.
1272 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1273 Cond = CondLHS;
1274 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1275 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1276 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1277 } else
1278 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1279 } else {
1280 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1281
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001282 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1283 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohman13aeef92008-09-03 16:12:24 +00001284
1285 SDValue CmpOp = getValue(CB.CmpMHS);
1286 MVT VT = CmpOp.getValueType();
1287
1288 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1289 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1290 } else {
1291 SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1292 Cond = DAG.getSetCC(MVT::i1, SUB,
1293 DAG.getConstant(High-Low, VT), ISD::SETULE);
1294 }
1295 }
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001296
Dan Gohman13aeef92008-09-03 16:12:24 +00001297 // Update successor info
1298 CurMBB->addSuccessor(CB.TrueBB);
1299 CurMBB->addSuccessor(CB.FalseBB);
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001300
Dan Gohman13aeef92008-09-03 16:12:24 +00001301 // Set NextBlock to be the MBB immediately after the current one, if any.
1302 // This is used to avoid emitting unnecessary branches to the next block.
1303 MachineBasicBlock *NextBlock = 0;
1304 MachineFunction::iterator BBI = CurMBB;
1305 if (++BBI != CurMBB->getParent()->end())
1306 NextBlock = BBI;
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001307
Dan Gohman13aeef92008-09-03 16:12:24 +00001308 // If the lhs block is the next block, invert the condition so that we can
1309 // fall through to the lhs instead of the rhs block.
1310 if (CB.TrueBB == NextBlock) {
1311 std::swap(CB.TrueBB, CB.FalseBB);
1312 SDValue True = DAG.getConstant(1, Cond.getValueType());
1313 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1314 }
1315 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1316 DAG.getBasicBlock(CB.TrueBB));
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001317
Dan Gohman13aeef92008-09-03 16:12:24 +00001318 // If the branch was constant folded, fix up the CFG.
1319 if (BrCond.getOpcode() == ISD::BR) {
1320 CurMBB->removeSuccessor(CB.FalseBB);
1321 DAG.setRoot(BrCond);
1322 } else {
1323 // Otherwise, go ahead and insert the false branch.
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001324 if (BrCond == getControlRoot())
Dan Gohman13aeef92008-09-03 16:12:24 +00001325 CurMBB->removeSuccessor(CB.TrueBB);
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001326
Dan Gohman13aeef92008-09-03 16:12:24 +00001327 if (CB.FalseBB == NextBlock)
1328 DAG.setRoot(BrCond);
1329 else
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001330 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Dan Gohman13aeef92008-09-03 16:12:24 +00001331 DAG.getBasicBlock(CB.FalseBB)));
1332 }
1333}
1334
1335/// visitJumpTable - Emit JumpTable node in the current MBB
1336void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1337 // Emit the code for the jump table
1338 assert(JT.Reg != -1U && "Should lower JT Header first!");
1339 MVT PTy = TLI.getPointerTy();
1340 SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1341 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1342 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1343 Table, Index));
Dan Gohman13aeef92008-09-03 16:12:24 +00001344}
1345
1346/// visitJumpTableHeader - This function emits necessary code to produce index
1347/// in the JumpTable from switch case.
1348void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1349 JumpTableHeader &JTH) {
Anton Korobeynikov1718d3a2008-12-23 22:25:45 +00001350 // Subtract the lowest switch case value from the value being switched on and
1351 // conditional branch to default mbb if the result is greater than the
Dan Gohman13aeef92008-09-03 16:12:24 +00001352 // difference between smallest and largest cases.
1353 SDValue SwitchOp = getValue(JTH.SValue);
1354 MVT VT = SwitchOp.getValueType();
1355 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
Anton Korobeynikov1718d3a2008-12-23 22:25:45 +00001356 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001357
Anton Korobeynikov1718d3a2008-12-23 22:25:45 +00001358 // The SDNode we just created, which holds the value being switched on minus
1359 // the the smallest case value, needs to be copied to a virtual register so it
1360 // can be used as an index into the jump table in a subsequent basic block.
1361 // This value may be smaller or larger than the target's pointer type, and
1362 // therefore require extension or truncating.
Dan Gohman13aeef92008-09-03 16:12:24 +00001363 if (VT.bitsGT(TLI.getPointerTy()))
1364 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1365 else
1366 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001367
Dan Gohman13aeef92008-09-03 16:12:24 +00001368 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1369 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1370 JT.Reg = JumpTableReg;
1371
Anton Korobeynikov1718d3a2008-12-23 22:25:45 +00001372 // Emit the range check for the jump table, and branch to the default block
1373 // for the switch statement if the value being switched on exceeds the largest
1374 // case in the switch.
Duncan Sands4a361272009-01-01 15:52:00 +00001375 SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB.getValueType()), SUB,
Anton Korobeynikov1718d3a2008-12-23 22:25:45 +00001376 DAG.getConstant(JTH.Last-JTH.First,VT),
1377 ISD::SETUGT);
Dan Gohman13aeef92008-09-03 16:12:24 +00001378
1379 // Set NextBlock to be the MBB immediately after the current one, if any.
1380 // This is used to avoid emitting unnecessary branches to the next block.
1381 MachineBasicBlock *NextBlock = 0;
1382 MachineFunction::iterator BBI = CurMBB;
1383 if (++BBI != CurMBB->getParent()->end())
1384 NextBlock = BBI;
1385
1386 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
Anton Korobeynikov1718d3a2008-12-23 22:25:45 +00001387 DAG.getBasicBlock(JT.Default));
Dan Gohman13aeef92008-09-03 16:12:24 +00001388
1389 if (JT.MBB == NextBlock)
1390 DAG.setRoot(BrCond);
1391 else
Anton Korobeynikov1718d3a2008-12-23 22:25:45 +00001392 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Dan Gohman13aeef92008-09-03 16:12:24 +00001393 DAG.getBasicBlock(JT.MBB)));
Dan Gohman13aeef92008-09-03 16:12:24 +00001394}
1395
1396/// visitBitTestHeader - This function emits necessary code to produce value
1397/// suitable for "bit tests"
1398void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1399 // Subtract the minimum value
1400 SDValue SwitchOp = getValue(B.SValue);
1401 MVT VT = SwitchOp.getValueType();
1402 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
Anton Korobeynikov1718d3a2008-12-23 22:25:45 +00001403 DAG.getConstant(B.First, VT));
Dan Gohman13aeef92008-09-03 16:12:24 +00001404
1405 // Check range
Duncan Sands4a361272009-01-01 15:52:00 +00001406 SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB.getValueType()), SUB,
Anton Korobeynikov1718d3a2008-12-23 22:25:45 +00001407 DAG.getConstant(B.Range, VT),
1408 ISD::SETUGT);
Dan Gohman13aeef92008-09-03 16:12:24 +00001409
1410 SDValue ShiftOp;
1411 if (VT.bitsGT(TLI.getShiftAmountTy()))
1412 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1413 else
1414 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1415
aslbb1518f2009-01-26 19:26:01 +00001416 B.Reg = FuncInfo.MakeReg(TLI.getShiftAmountTy());
1417 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), B.Reg, ShiftOp);
Dan Gohman13aeef92008-09-03 16:12:24 +00001418
1419 // Set NextBlock to be the MBB immediately after the current one, if any.
1420 // This is used to avoid emitting unnecessary branches to the next block.
1421 MachineBasicBlock *NextBlock = 0;
1422 MachineFunction::iterator BBI = CurMBB;
1423 if (++BBI != CurMBB->getParent()->end())
1424 NextBlock = BBI;
1425
1426 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1427
1428 CurMBB->addSuccessor(B.Default);
1429 CurMBB->addSuccessor(MBB);
1430
1431 SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov1718d3a2008-12-23 22:25:45 +00001432 DAG.getBasicBlock(B.Default));
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001433
Dan Gohman13aeef92008-09-03 16:12:24 +00001434 if (MBB == NextBlock)
1435 DAG.setRoot(BrRange);
1436 else
1437 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1438 DAG.getBasicBlock(MBB)));
Dan Gohman13aeef92008-09-03 16:12:24 +00001439}
1440
1441/// visitBitTestCase - this function produces one "bit test"
1442void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1443 unsigned Reg,
1444 BitTestCase &B) {
aslbb1518f2009-01-26 19:26:01 +00001445 // Make desired shift
1446 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), Reg,
1447 TLI.getShiftAmountTy());
1448 SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1449 DAG.getConstant(1, TLI.getPointerTy()),
1450 ShiftOp);
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001451
aslbb1518f2009-01-26 19:26:01 +00001452 // Emit bit tests and jumps
Dan Gohman13aeef92008-09-03 16:12:24 +00001453 SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
Anton Korobeynikov1718d3a2008-12-23 22:25:45 +00001454 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Duncan Sands4a361272009-01-01 15:52:00 +00001455 SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp.getValueType()),
1456 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
Anton Korobeynikov1718d3a2008-12-23 22:25:45 +00001457 ISD::SETNE);
Dan Gohman13aeef92008-09-03 16:12:24 +00001458
1459 CurMBB->addSuccessor(B.TargetBB);
1460 CurMBB->addSuccessor(NextMBB);
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001461
Dan Gohman13aeef92008-09-03 16:12:24 +00001462 SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
Anton Korobeynikov1718d3a2008-12-23 22:25:45 +00001463 AndCmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohman13aeef92008-09-03 16:12:24 +00001464
1465 // Set NextBlock to be the MBB immediately after the current one, if any.
1466 // This is used to avoid emitting unnecessary branches to the next block.
1467 MachineBasicBlock *NextBlock = 0;
1468 MachineFunction::iterator BBI = CurMBB;
1469 if (++BBI != CurMBB->getParent()->end())
1470 NextBlock = BBI;
1471
1472 if (NextMBB == NextBlock)
1473 DAG.setRoot(BrAnd);
1474 else
1475 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1476 DAG.getBasicBlock(NextMBB)));
Dan Gohman13aeef92008-09-03 16:12:24 +00001477}
1478
1479void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1480 // Retrieve successors.
1481 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1482 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1483
Gabor Greif4c99d822009-01-15 11:10:44 +00001484 const Value *Callee(I.getCalledValue());
1485 if (isa<InlineAsm>(Callee))
Dan Gohman13aeef92008-09-03 16:12:24 +00001486 visitInlineAsm(&I);
1487 else
Gabor Greif4c99d822009-01-15 11:10:44 +00001488 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohman13aeef92008-09-03 16:12:24 +00001489
1490 // If the value of the invoke is used outside of its defining block, make it
1491 // available as a virtual register.
1492 if (!I.use_empty()) {
1493 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1494 if (VMI != FuncInfo.ValueMap.end())
1495 CopyValueToVirtualRegister(&I, VMI->second);
1496 }
1497
1498 // Update successor info
1499 CurMBB->addSuccessor(Return);
1500 CurMBB->addSuccessor(LandingPad);
1501
1502 // Drop into normal successor.
1503 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1504 DAG.getBasicBlock(Return)));
1505}
1506
1507void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1508}
1509
1510/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1511/// small case ranges).
1512bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1513 CaseRecVector& WorkList,
1514 Value* SV,
1515 MachineBasicBlock* Default) {
1516 Case& BackCase = *(CR.Range.second-1);
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001517
Dan Gohman13aeef92008-09-03 16:12:24 +00001518 // Size is the number of Cases represented by this range.
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001519 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohman13aeef92008-09-03 16:12:24 +00001520 if (Size > 3)
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001521 return false;
1522
Dan Gohman13aeef92008-09-03 16:12:24 +00001523 // Get the MachineFunction which holds the current MBB. This is used when
1524 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001525 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohman13aeef92008-09-03 16:12:24 +00001526
1527 // Figure out which block is immediately after the current one.
1528 MachineBasicBlock *NextBlock = 0;
1529 MachineFunction::iterator BBI = CR.CaseBB;
1530
1531 if (++BBI != CurMBB->getParent()->end())
1532 NextBlock = BBI;
1533
1534 // TODO: If any two of the cases has the same destination, and if one value
1535 // is the same as the other, but has one bit unset that the other has set,
1536 // use bit manipulation to do two compares at once. For example:
1537 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001538
Dan Gohman13aeef92008-09-03 16:12:24 +00001539 // Rearrange the case blocks so that the last one falls through if possible.
1540 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1541 // The last case block won't fall through into 'NextBlock' if we emit the
1542 // branches in this order. See if rearranging a case value would help.
1543 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1544 if (I->BB == NextBlock) {
1545 std::swap(*I, BackCase);
1546 break;
1547 }
1548 }
1549 }
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001550
Dan Gohman13aeef92008-09-03 16:12:24 +00001551 // Create a CaseBlock record representing a conditional branch to
1552 // the Case's target mbb if the value being switched on SV is equal
1553 // to C.
1554 MachineBasicBlock *CurBlock = CR.CaseBB;
1555 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1556 MachineBasicBlock *FallThrough;
1557 if (I != E-1) {
1558 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1559 CurMF->insert(BBI, FallThrough);
1560 } else {
1561 // If the last case doesn't match, go to the default block.
1562 FallThrough = Default;
1563 }
1564
1565 Value *RHS, *LHS, *MHS;
1566 ISD::CondCode CC;
1567 if (I->High == I->Low) {
1568 // This is just small small case range :) containing exactly 1 case
1569 CC = ISD::SETEQ;
1570 LHS = SV; RHS = I->High; MHS = NULL;
1571 } else {
1572 CC = ISD::SETLE;
1573 LHS = I->Low; MHS = SV; RHS = I->High;
1574 }
1575 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001576
Dan Gohman13aeef92008-09-03 16:12:24 +00001577 // If emitting the first comparison, just call visitSwitchCase to emit the
1578 // code into the current block. Otherwise, push the CaseBlock onto the
1579 // vector to be later processed by SDISel, and insert the node's MBB
1580 // before the next MBB.
1581 if (CurBlock == CurMBB)
1582 visitSwitchCase(CB);
1583 else
1584 SwitchCases.push_back(CB);
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001585
Dan Gohman13aeef92008-09-03 16:12:24 +00001586 CurBlock = FallThrough;
1587 }
1588
1589 return true;
1590}
1591
1592static inline bool areJTsAllowed(const TargetLowering &TLI) {
1593 return !DisableJumpTables &&
1594 (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1595 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1596}
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001597
Anton Korobeynikov6981ab22008-12-23 22:26:01 +00001598static APInt ComputeRange(const APInt &First, const APInt &Last) {
1599 APInt LastExt(Last), FirstExt(First);
1600 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1601 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1602 return (LastExt - FirstExt + 1ULL);
1603}
1604
Dan Gohman13aeef92008-09-03 16:12:24 +00001605/// handleJTSwitchCase - Emit jumptable for current switch case range
1606bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1607 CaseRecVector& WorkList,
1608 Value* SV,
1609 MachineBasicBlock* Default) {
1610 Case& FrontCase = *CR.Range.first;
1611 Case& BackCase = *(CR.Range.second-1);
1612
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001613 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1614 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohman13aeef92008-09-03 16:12:24 +00001615
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001616 size_t TSize = 0;
Dan Gohman13aeef92008-09-03 16:12:24 +00001617 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1618 I!=E; ++I)
1619 TSize += I->size();
1620
1621 if (!areJTsAllowed(TLI) || TSize <= 3)
1622 return false;
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001623
Anton Korobeynikov6981ab22008-12-23 22:26:01 +00001624 APInt Range = ComputeRange(First, Last);
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001625 double Density = (double)TSize / Range.roundToDouble();
Dan Gohman13aeef92008-09-03 16:12:24 +00001626 if (Density < 0.4)
1627 return false;
1628
Anton Korobeynikovf5b5f6b2008-12-23 22:26:18 +00001629 DEBUG(errs() << "Lowering jump table\n"
1630 << "First entry: " << First << ". Last entry: " << Last << '\n'
1631 << "Range: " << Range
1632 << "Size: " << TSize << ". Density: " << Density << "\n\n");
Dan Gohman13aeef92008-09-03 16:12:24 +00001633
1634 // Get the MachineFunction which holds the current MBB. This is used when
1635 // inserting any additional MBBs necessary to represent the switch.
1636 MachineFunction *CurMF = CurMBB->getParent();
1637
1638 // Figure out which block is immediately after the current one.
1639 MachineBasicBlock *NextBlock = 0;
1640 MachineFunction::iterator BBI = CR.CaseBB;
1641
1642 if (++BBI != CurMBB->getParent()->end())
1643 NextBlock = BBI;
1644
1645 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1646
1647 // Create a new basic block to hold the code for loading the address
1648 // of the jump table, and jumping to it. Update successor information;
1649 // we will either branch to the default case for the switch, or the jump
1650 // table.
1651 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1652 CurMF->insert(BBI, JumpTableBB);
1653 CR.CaseBB->addSuccessor(Default);
1654 CR.CaseBB->addSuccessor(JumpTableBB);
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001655
Dan Gohman13aeef92008-09-03 16:12:24 +00001656 // Build a vector of destination BBs, corresponding to each target
1657 // of the jump table. If the value of the jump table slot corresponds to
1658 // a case statement, push the case's BB onto the vector, otherwise, push
1659 // the default BB.
1660 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001661 APInt TEI = First;
Dan Gohman13aeef92008-09-03 16:12:24 +00001662 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001663 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1664 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1665
1666 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohman13aeef92008-09-03 16:12:24 +00001667 DestBBs.push_back(I->BB);
1668 if (TEI==High)
1669 ++I;
1670 } else {
1671 DestBBs.push_back(Default);
1672 }
1673 }
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001674
Dan Gohman13aeef92008-09-03 16:12:24 +00001675 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001676 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1677 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohman13aeef92008-09-03 16:12:24 +00001678 E = DestBBs.end(); I != E; ++I) {
1679 if (!SuccsHandled[(*I)->getNumber()]) {
1680 SuccsHandled[(*I)->getNumber()] = true;
1681 JumpTableBB->addSuccessor(*I);
1682 }
1683 }
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001684
Dan Gohman13aeef92008-09-03 16:12:24 +00001685 // Create a jump table index for this jump table, or return an existing
1686 // one.
1687 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001688
Dan Gohman13aeef92008-09-03 16:12:24 +00001689 // Set the jump table information so that we can codegen it as a second
1690 // MachineBasicBlock
1691 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1692 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1693 if (CR.CaseBB == CurMBB)
1694 visitJumpTableHeader(JT, JTH);
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001695
Dan Gohman13aeef92008-09-03 16:12:24 +00001696 JTCases.push_back(JumpTableBlock(JTH, JT));
1697
1698 return true;
1699}
1700
1701/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1702/// 2 subtrees.
1703bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1704 CaseRecVector& WorkList,
1705 Value* SV,
1706 MachineBasicBlock* Default) {
1707 // Get the MachineFunction which holds the current MBB. This is used when
1708 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001709 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohman13aeef92008-09-03 16:12:24 +00001710
1711 // Figure out which block is immediately after the current one.
1712 MachineBasicBlock *NextBlock = 0;
1713 MachineFunction::iterator BBI = CR.CaseBB;
1714
1715 if (++BBI != CurMBB->getParent()->end())
1716 NextBlock = BBI;
1717
1718 Case& FrontCase = *CR.Range.first;
1719 Case& BackCase = *(CR.Range.second-1);
1720 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1721
1722 // Size is the number of Cases represented by this range.
1723 unsigned Size = CR.Range.second - CR.Range.first;
1724
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001725 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1726 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohman13aeef92008-09-03 16:12:24 +00001727 double FMetric = 0;
1728 CaseItr Pivot = CR.Range.first + Size/2;
1729
1730 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1731 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001732 size_t TSize = 0;
Dan Gohman13aeef92008-09-03 16:12:24 +00001733 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1734 I!=E; ++I)
1735 TSize += I->size();
1736
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001737 size_t LSize = FrontCase.size();
1738 size_t RSize = TSize-LSize;
Anton Korobeynikovf5b5f6b2008-12-23 22:26:18 +00001739 DEBUG(errs() << "Selecting best pivot: \n"
1740 << "First: " << First << ", Last: " << Last <<'\n'
1741 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohman13aeef92008-09-03 16:12:24 +00001742 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1743 J!=E; ++I, ++J) {
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001744 const APInt& LEnd = cast<ConstantInt>(I->High)->getValue();
1745 const APInt& RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikov6981ab22008-12-23 22:26:01 +00001746 APInt Range = ComputeRange(LEnd, RBegin);
1747 assert((Range - 2ULL).isNonNegative() &&
1748 "Invalid case distance");
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001749 double LDensity = (double)LSize / (LEnd - First + 1ULL).roundToDouble();
1750 double RDensity = (double)RSize / (Last - RBegin + 1ULL).roundToDouble();
Anton Korobeynikov6981ab22008-12-23 22:26:01 +00001751 double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohman13aeef92008-09-03 16:12:24 +00001752 // Should always split in some non-trivial place
Anton Korobeynikovf5b5f6b2008-12-23 22:26:18 +00001753 DEBUG(errs() <<"=>Step\n"
1754 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1755 << "LDensity: " << LDensity
1756 << ", RDensity: " << RDensity << '\n'
1757 << "Metric: " << Metric << '\n');
Dan Gohman13aeef92008-09-03 16:12:24 +00001758 if (FMetric < Metric) {
1759 Pivot = J;
1760 FMetric = Metric;
Anton Korobeynikovf5b5f6b2008-12-23 22:26:18 +00001761 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
Dan Gohman13aeef92008-09-03 16:12:24 +00001762 }
1763
1764 LSize += J->size();
1765 RSize -= J->size();
1766 }
1767 if (areJTsAllowed(TLI)) {
1768 // If our case is dense we *really* should handle it earlier!
1769 assert((FMetric > 0) && "Should handle dense range earlier!");
1770 } else {
1771 Pivot = CR.Range.first + Size/2;
1772 }
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001773
Dan Gohman13aeef92008-09-03 16:12:24 +00001774 CaseRange LHSR(CR.Range.first, Pivot);
1775 CaseRange RHSR(Pivot, CR.Range.second);
1776 Constant *C = Pivot->Low;
1777 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001778
Dan Gohman13aeef92008-09-03 16:12:24 +00001779 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00001780 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohman13aeef92008-09-03 16:12:24 +00001781 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00001782 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohman13aeef92008-09-03 16:12:24 +00001783 // Pivot's Value, then we can branch directly to the LHS's Target,
1784 // rather than creating a leaf node for it.
1785 if ((LHSR.second - LHSR.first) == 1 &&
1786 LHSR.first->High == CR.GE &&
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001787 cast<ConstantInt>(C)->getValue() ==
1788 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohman13aeef92008-09-03 16:12:24 +00001789 TrueBB = LHSR.first->BB;
1790 } else {
1791 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1792 CurMF->insert(BBI, TrueBB);
1793 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1794 }
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001795
Dan Gohman13aeef92008-09-03 16:12:24 +00001796 // Similar to the optimization above, if the Value being switched on is
1797 // known to be less than the Constant CR.LT, and the current Case Value
1798 // is CR.LT - 1, then we can branch directly to the target block for
1799 // the current Case Value, rather than emitting a RHS leaf node for it.
1800 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001801 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1802 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohman13aeef92008-09-03 16:12:24 +00001803 FalseBB = RHSR.first->BB;
1804 } else {
1805 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1806 CurMF->insert(BBI, FalseBB);
1807 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1808 }
1809
1810 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00001811 // the LHS node if the value being switched on SV is less than C.
Dan Gohman13aeef92008-09-03 16:12:24 +00001812 // Otherwise, branch to LHS.
1813 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1814
1815 if (CR.CaseBB == CurMBB)
1816 visitSwitchCase(CB);
1817 else
1818 SwitchCases.push_back(CB);
1819
1820 return true;
1821}
1822
1823/// handleBitTestsSwitchCase - if current case range has few destination and
1824/// range span less, than machine word bitwidth, encode case range into series
1825/// of masks and emit bit tests with these masks.
1826bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1827 CaseRecVector& WorkList,
1828 Value* SV,
1829 MachineBasicBlock* Default){
1830 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1831
1832 Case& FrontCase = *CR.Range.first;
1833 Case& BackCase = *(CR.Range.second-1);
1834
1835 // Get the MachineFunction which holds the current MBB. This is used when
1836 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001837 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohman13aeef92008-09-03 16:12:24 +00001838
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001839 size_t numCmps = 0;
Dan Gohman13aeef92008-09-03 16:12:24 +00001840 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1841 I!=E; ++I) {
1842 // Single case counts one, case range - two.
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001843 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohman13aeef92008-09-03 16:12:24 +00001844 }
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001845
Dan Gohman13aeef92008-09-03 16:12:24 +00001846 // Count unique destinations
1847 SmallSet<MachineBasicBlock*, 4> Dests;
1848 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1849 Dests.insert(I->BB);
1850 if (Dests.size() > 3)
1851 // Don't bother the code below, if there are too much unique destinations
1852 return false;
1853 }
Anton Korobeynikovf5b5f6b2008-12-23 22:26:18 +00001854 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1855 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001856
Dan Gohman13aeef92008-09-03 16:12:24 +00001857 // Compute span of values.
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001858 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1859 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikov6981ab22008-12-23 22:26:01 +00001860 APInt cmpRange = maxValue - minValue;
1861
Anton Korobeynikovf5b5f6b2008-12-23 22:26:18 +00001862 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1863 << "Low bound: " << minValue << '\n'
1864 << "High bound: " << maxValue << '\n');
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001865
1866 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
Dan Gohman13aeef92008-09-03 16:12:24 +00001867 (!(Dests.size() == 1 && numCmps >= 3) &&
1868 !(Dests.size() == 2 && numCmps >= 5) &&
1869 !(Dests.size() >= 3 && numCmps >= 6)))
1870 return false;
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001871
Anton Korobeynikovf5b5f6b2008-12-23 22:26:18 +00001872 DEBUG(errs() << "Emitting bit tests\n");
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001873 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1874
Dan Gohman13aeef92008-09-03 16:12:24 +00001875 // Optimize the case where all the case values fit in a
1876 // word without having to subtract minValue. In this case,
1877 // we can optimize away the subtraction.
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001878 if (minValue.isNonNegative() &&
1879 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1880 cmpRange = maxValue;
Dan Gohman13aeef92008-09-03 16:12:24 +00001881 } else {
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001882 lowBound = minValue;
Dan Gohman13aeef92008-09-03 16:12:24 +00001883 }
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001884
Dan Gohman13aeef92008-09-03 16:12:24 +00001885 CaseBitsVector CasesBits;
1886 unsigned i, count = 0;
1887
1888 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1889 MachineBasicBlock* Dest = I->BB;
1890 for (i = 0; i < count; ++i)
1891 if (Dest == CasesBits[i].BB)
1892 break;
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001893
Dan Gohman13aeef92008-09-03 16:12:24 +00001894 if (i == count) {
1895 assert((count < 3) && "Too much destinations to test!");
1896 CasesBits.push_back(CaseBits(0, Dest, 0));
1897 count++;
1898 }
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001899
1900 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1901 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1902
1903 uint64_t lo = (lowValue - lowBound).getZExtValue();
1904 uint64_t hi = (highValue - lowBound).getZExtValue();
1905
Dan Gohman13aeef92008-09-03 16:12:24 +00001906 for (uint64_t j = lo; j <= hi; j++) {
1907 CasesBits[i].Mask |= 1ULL << j;
1908 CasesBits[i].Bits++;
1909 }
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001910
Dan Gohman13aeef92008-09-03 16:12:24 +00001911 }
1912 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001913
Dan Gohman13aeef92008-09-03 16:12:24 +00001914 BitTestInfo BTC;
1915
1916 // Figure out which block is immediately after the current one.
1917 MachineFunction::iterator BBI = CR.CaseBB;
1918 ++BBI;
1919
1920 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1921
Anton Korobeynikovf5b5f6b2008-12-23 22:26:18 +00001922 DEBUG(errs() << "Cases:\n");
Dan Gohman13aeef92008-09-03 16:12:24 +00001923 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
Anton Korobeynikovf5b5f6b2008-12-23 22:26:18 +00001924 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
1925 << ", Bits: " << CasesBits[i].Bits
1926 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohman13aeef92008-09-03 16:12:24 +00001927
1928 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1929 CurMF->insert(BBI, CaseBB);
1930 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1931 CaseBB,
1932 CasesBits[i].BB));
1933 }
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001934
1935 BitTestBlock BTB(lowBound, cmpRange, SV,
Dan Gohman13aeef92008-09-03 16:12:24 +00001936 -1U, (CR.CaseBB == CurMBB),
1937 CR.CaseBB, Default, BTC);
1938
1939 if (CR.CaseBB == CurMBB)
1940 visitBitTestHeader(BTB);
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001941
Dan Gohman13aeef92008-09-03 16:12:24 +00001942 BitTestCases.push_back(BTB);
1943
1944 return true;
1945}
1946
1947
1948/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001949size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
Dan Gohman13aeef92008-09-03 16:12:24 +00001950 const SwitchInst& SI) {
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001951 size_t numCmps = 0;
Dan Gohman13aeef92008-09-03 16:12:24 +00001952
1953 // Start with "simple" cases
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001954 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
Dan Gohman13aeef92008-09-03 16:12:24 +00001955 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1956 Cases.push_back(Case(SI.getSuccessorValue(i),
1957 SI.getSuccessorValue(i),
1958 SMBB));
1959 }
1960 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1961
1962 // Merge case into clusters
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001963 if (Cases.size() >= 2)
Dan Gohman13aeef92008-09-03 16:12:24 +00001964 // Must recompute end() each iteration because it may be
1965 // invalidated by erase if we hold on to it
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001966 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
1967 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
1968 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
Dan Gohman13aeef92008-09-03 16:12:24 +00001969 MachineBasicBlock* nextBB = J->BB;
1970 MachineBasicBlock* currentBB = I->BB;
1971
1972 // If the two neighboring cases go to the same destination, merge them
1973 // into a single case.
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001974 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
Dan Gohman13aeef92008-09-03 16:12:24 +00001975 I->High = J->High;
1976 J = Cases.erase(J);
1977 } else {
1978 I = J++;
1979 }
1980 }
1981
1982 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1983 if (I->Low != I->High)
1984 // A range counts double, since it requires two compares.
1985 ++numCmps;
1986 }
1987
1988 return numCmps;
1989}
1990
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00001991void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Dan Gohman13aeef92008-09-03 16:12:24 +00001992 // Figure out which block is immediately after the current one.
1993 MachineBasicBlock *NextBlock = 0;
1994 MachineFunction::iterator BBI = CurMBB;
1995
1996 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1997
1998 // If there is only the default destination, branch to it if it is not the
1999 // next basic block. Otherwise, just fall through.
2000 if (SI.getNumOperands() == 2) {
2001 // Update machine-CFG edges.
2002
2003 // If this is not a fall-through branch, emit the branch.
2004 CurMBB->addSuccessor(Default);
2005 if (Default != NextBlock)
2006 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
2007 DAG.getBasicBlock(Default)));
Dan Gohman13aeef92008-09-03 16:12:24 +00002008 return;
2009 }
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00002010
Dan Gohman13aeef92008-09-03 16:12:24 +00002011 // If there are any non-default case statements, create a vector of Cases
2012 // representing each one, and sort the vector so that we can efficiently
2013 // create a binary search tree from them.
2014 CaseVector Cases;
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00002015 size_t numCmps = Clusterify(Cases, SI);
Anton Korobeynikovf5b5f6b2008-12-23 22:26:18 +00002016 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2017 << ". Total compares: " << numCmps << '\n');
Devang Patelf3707e82009-01-05 17:31:22 +00002018 numCmps = 0;
Dan Gohman13aeef92008-09-03 16:12:24 +00002019
2020 // Get the Value to be switched on and default basic blocks, which will be
2021 // inserted into CaseBlock records, representing basic blocks in the binary
2022 // search tree.
2023 Value *SV = SI.getOperand(0);
2024
2025 // Push the initial CaseRec onto the worklist
2026 CaseRecVector WorkList;
2027 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2028
2029 while (!WorkList.empty()) {
2030 // Grab a record representing a case range to process off the worklist
2031 CaseRec CR = WorkList.back();
2032 WorkList.pop_back();
2033
2034 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2035 continue;
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00002036
Dan Gohman13aeef92008-09-03 16:12:24 +00002037 // If the range has few cases (two or less) emit a series of specific
2038 // tests.
2039 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2040 continue;
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00002041
Anton Korobeynikov6981ab22008-12-23 22:26:01 +00002042 // If the switch has more than 5 blocks, and at least 40% dense, and the
2043 // target supports indirect branches, then emit a jump table rather than
Dan Gohman13aeef92008-09-03 16:12:24 +00002044 // lowering the switch to a binary tree of conditional branches.
2045 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2046 continue;
Anton Korobeynikov7e50c0d2008-12-23 22:25:27 +00002047
Dan Gohman13aeef92008-09-03 16:12:24 +00002048 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2049 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2050 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2051 }
2052}
2053
2054
2055void SelectionDAGLowering::visitSub(User &I) {
2056 // -0.0 - X --> fneg
2057 const Type *Ty = I.getType();
2058 if (isa<VectorType>(Ty)) {
2059 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2060 const VectorType *DestTy = cast<VectorType>(I.getType());
2061 const Type *ElTy = DestTy->getElementType();
2062 if (ElTy->isFloatingPoint()) {
2063 unsigned VL = DestTy->getNumElements();
2064 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2065 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2066 if (CV == CNZ) {
2067 SDValue Op2 = getValue(I.getOperand(1));
2068 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2069 return;
2070 }
2071 }
2072 }
2073 }
2074 if (Ty->isFloatingPoint()) {
2075 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2076 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2077 SDValue Op2 = getValue(I.getOperand(1));
2078 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2079 return;
2080 }
2081 }
2082
2083 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2084}
2085
2086void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2087 SDValue Op1 = getValue(I.getOperand(0));
2088 SDValue Op2 = getValue(I.getOperand(1));
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002089
Dan Gohman13aeef92008-09-03 16:12:24 +00002090 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2091}
2092
2093void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2094 SDValue Op1 = getValue(I.getOperand(0));
2095 SDValue Op2 = getValue(I.getOperand(1));
2096 if (!isa<VectorType>(I.getType())) {
2097 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2098 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2099 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2100 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2101 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002102
Dan Gohman13aeef92008-09-03 16:12:24 +00002103 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2104}
2105
2106void SelectionDAGLowering::visitICmp(User &I) {
2107 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2108 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2109 predicate = IC->getPredicate();
2110 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2111 predicate = ICmpInst::Predicate(IC->getPredicate());
2112 SDValue Op1 = getValue(I.getOperand(0));
2113 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman9a1b1c42008-10-17 18:18:45 +00002114 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dan Gohman13aeef92008-09-03 16:12:24 +00002115 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2116}
2117
2118void SelectionDAGLowering::visitFCmp(User &I) {
2119 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2120 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2121 predicate = FC->getPredicate();
2122 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2123 predicate = FCmpInst::Predicate(FC->getPredicate());
2124 SDValue Op1 = getValue(I.getOperand(0));
2125 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman9a1b1c42008-10-17 18:18:45 +00002126 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohman13aeef92008-09-03 16:12:24 +00002127 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2128}
2129
2130void SelectionDAGLowering::visitVICmp(User &I) {
2131 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2132 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2133 predicate = IC->getPredicate();
2134 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2135 predicate = ICmpInst::Predicate(IC->getPredicate());
2136 SDValue Op1 = getValue(I.getOperand(0));
2137 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman9a1b1c42008-10-17 18:18:45 +00002138 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dan Gohman13aeef92008-09-03 16:12:24 +00002139 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2140}
2141
2142void SelectionDAGLowering::visitVFCmp(User &I) {
2143 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2144 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2145 predicate = FC->getPredicate();
2146 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2147 predicate = FCmpInst::Predicate(FC->getPredicate());
2148 SDValue Op1 = getValue(I.getOperand(0));
2149 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman9a1b1c42008-10-17 18:18:45 +00002150 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohman13aeef92008-09-03 16:12:24 +00002151 MVT DestVT = TLI.getValueType(I.getType());
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002152
Dan Gohman13aeef92008-09-03 16:12:24 +00002153 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2154}
2155
2156void SelectionDAGLowering::visitSelect(User &I) {
Dan Gohman79160592008-10-21 20:00:42 +00002157 SmallVector<MVT, 4> ValueVTs;
2158 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2159 unsigned NumValues = ValueVTs.size();
2160 if (NumValues != 0) {
2161 SmallVector<SDValue, 4> Values(NumValues);
2162 SDValue Cond = getValue(I.getOperand(0));
2163 SDValue TrueVal = getValue(I.getOperand(1));
2164 SDValue FalseVal = getValue(I.getOperand(2));
2165
2166 for (unsigned i = 0; i != NumValues; ++i)
2167 Values[i] = DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2168 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2169 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2170
Duncan Sands42d7bb82008-12-01 11:41:29 +00002171 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2172 DAG.getVTList(&ValueVTs[0], NumValues),
2173 &Values[0], NumValues));
Dan Gohman79160592008-10-21 20:00:42 +00002174 }
Dan Gohman13aeef92008-09-03 16:12:24 +00002175}
2176
2177
2178void SelectionDAGLowering::visitTrunc(User &I) {
2179 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2180 SDValue N = getValue(I.getOperand(0));
2181 MVT DestVT = TLI.getValueType(I.getType());
2182 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2183}
2184
2185void SelectionDAGLowering::visitZExt(User &I) {
2186 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2187 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2188 SDValue N = getValue(I.getOperand(0));
2189 MVT DestVT = TLI.getValueType(I.getType());
2190 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2191}
2192
2193void SelectionDAGLowering::visitSExt(User &I) {
2194 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2195 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2196 SDValue N = getValue(I.getOperand(0));
2197 MVT DestVT = TLI.getValueType(I.getType());
2198 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2199}
2200
2201void SelectionDAGLowering::visitFPTrunc(User &I) {
2202 // FPTrunc is never a no-op cast, no need to check
2203 SDValue N = getValue(I.getOperand(0));
2204 MVT DestVT = TLI.getValueType(I.getType());
2205 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2206}
2207
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002208void SelectionDAGLowering::visitFPExt(User &I){
Dan Gohman13aeef92008-09-03 16:12:24 +00002209 // FPTrunc is never a no-op cast, no need to check
2210 SDValue N = getValue(I.getOperand(0));
2211 MVT DestVT = TLI.getValueType(I.getType());
2212 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2213}
2214
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002215void SelectionDAGLowering::visitFPToUI(User &I) {
Dan Gohman13aeef92008-09-03 16:12:24 +00002216 // FPToUI is never a no-op cast, no need to check
2217 SDValue N = getValue(I.getOperand(0));
2218 MVT DestVT = TLI.getValueType(I.getType());
2219 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2220}
2221
2222void SelectionDAGLowering::visitFPToSI(User &I) {
2223 // FPToSI is never a no-op cast, no need to check
2224 SDValue N = getValue(I.getOperand(0));
2225 MVT DestVT = TLI.getValueType(I.getType());
2226 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2227}
2228
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002229void SelectionDAGLowering::visitUIToFP(User &I) {
Dan Gohman13aeef92008-09-03 16:12:24 +00002230 // UIToFP is never a no-op cast, no need to check
2231 SDValue N = getValue(I.getOperand(0));
2232 MVT DestVT = TLI.getValueType(I.getType());
2233 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2234}
2235
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002236void SelectionDAGLowering::visitSIToFP(User &I){
Bill Wendling22922462008-10-19 20:34:04 +00002237 // SIToFP is never a no-op cast, no need to check
Dan Gohman13aeef92008-09-03 16:12:24 +00002238 SDValue N = getValue(I.getOperand(0));
2239 MVT DestVT = TLI.getValueType(I.getType());
2240 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2241}
2242
2243void SelectionDAGLowering::visitPtrToInt(User &I) {
2244 // What to do depends on the size of the integer and the size of the pointer.
2245 // We can either truncate, zero extend, or no-op, accordingly.
2246 SDValue N = getValue(I.getOperand(0));
2247 MVT SrcVT = N.getValueType();
2248 MVT DestVT = TLI.getValueType(I.getType());
2249 SDValue Result;
2250 if (DestVT.bitsLT(SrcVT))
2251 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002252 else
Dan Gohman13aeef92008-09-03 16:12:24 +00002253 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2254 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2255 setValue(&I, Result);
2256}
2257
2258void SelectionDAGLowering::visitIntToPtr(User &I) {
2259 // What to do depends on the size of the integer and the size of the pointer.
2260 // We can either truncate, zero extend, or no-op, accordingly.
2261 SDValue N = getValue(I.getOperand(0));
2262 MVT SrcVT = N.getValueType();
2263 MVT DestVT = TLI.getValueType(I.getType());
2264 if (DestVT.bitsLT(SrcVT))
2265 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002266 else
Dan Gohman13aeef92008-09-03 16:12:24 +00002267 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2268 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2269}
2270
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002271void SelectionDAGLowering::visitBitCast(User &I) {
Dan Gohman13aeef92008-09-03 16:12:24 +00002272 SDValue N = getValue(I.getOperand(0));
2273 MVT DestVT = TLI.getValueType(I.getType());
2274
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002275 // BitCast assures us that source and destination are the same size so this
Dan Gohman13aeef92008-09-03 16:12:24 +00002276 // is either a BIT_CONVERT or a no-op.
2277 if (DestVT != N.getValueType())
2278 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2279 else
2280 setValue(&I, N); // noop cast.
2281}
2282
2283void SelectionDAGLowering::visitInsertElement(User &I) {
2284 SDValue InVec = getValue(I.getOperand(0));
2285 SDValue InVal = getValue(I.getOperand(1));
2286 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2287 getValue(I.getOperand(2)));
2288
2289 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2290 TLI.getValueType(I.getType()),
2291 InVec, InVal, InIdx));
2292}
2293
2294void SelectionDAGLowering::visitExtractElement(User &I) {
2295 SDValue InVec = getValue(I.getOperand(0));
2296 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2297 getValue(I.getOperand(1)));
2298 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2299 TLI.getValueType(I.getType()), InVec, InIdx));
2300}
2301
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002302
2303// Utility for visitShuffleVector - Returns true if the mask is mask starting
2304// from SIndx and increasing to the element length (undefs are allowed).
2305static bool SequentialMask(SDValue Mask, unsigned SIndx) {
Mon P Wang7bfa4642008-11-16 05:06:27 +00002306 unsigned MaskNumElts = Mask.getNumOperands();
2307 for (unsigned i = 0; i != MaskNumElts; ++i) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002308 if (Mask.getOperand(i).getOpcode() != ISD::UNDEF) {
2309 unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2310 if (Idx != i + SIndx)
2311 return false;
2312 }
2313 }
2314 return true;
2315}
2316
Dan Gohman13aeef92008-09-03 16:12:24 +00002317void SelectionDAGLowering::visitShuffleVector(User &I) {
Mon P Wang67227c22008-11-21 04:25:21 +00002318 SDValue Src1 = getValue(I.getOperand(0));
2319 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohman13aeef92008-09-03 16:12:24 +00002320 SDValue Mask = getValue(I.getOperand(2));
2321
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002322 MVT VT = TLI.getValueType(I.getType());
Mon P Wang67227c22008-11-21 04:25:21 +00002323 MVT SrcVT = Src1.getValueType();
Mon P Wang7bfa4642008-11-16 05:06:27 +00002324 int MaskNumElts = Mask.getNumOperands();
2325 int SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002326
Mon P Wang7bfa4642008-11-16 05:06:27 +00002327 if (SrcNumElts == MaskNumElts) {
Mon P Wang67227c22008-11-21 04:25:21 +00002328 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002329 return;
2330 }
2331
2332 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wang7bfa4642008-11-16 05:06:27 +00002333 MVT MaskEltVT = Mask.getValueType().getVectorElementType();
2334
2335 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2336 // Mask is longer than the source vectors and is a multiple of the source
2337 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang67227c22008-11-21 04:25:21 +00002338 // lengths match.
Mon P Wang7bfa4642008-11-16 05:06:27 +00002339 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2340 // The shuffle is concatenating two vectors together.
Mon P Wang67227c22008-11-21 04:25:21 +00002341 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, VT, Src1, Src2));
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002342 return;
2343 }
2344
Mon P Wang7bfa4642008-11-16 05:06:27 +00002345 // Pad both vectors with undefs to make them the same length as the mask.
2346 unsigned NumConcat = MaskNumElts / SrcNumElts;
2347 SDValue UndefVal = DAG.getNode(ISD::UNDEF, SrcVT);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002348
Mon P Wang67227c22008-11-21 04:25:21 +00002349 SDValue* MOps1 = new SDValue[NumConcat];
2350 SDValue* MOps2 = new SDValue[NumConcat];
2351 MOps1[0] = Src1;
2352 MOps2[0] = Src2;
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002353 for (unsigned i = 1; i != NumConcat; ++i) {
Mon P Wang67227c22008-11-21 04:25:21 +00002354 MOps1[i] = UndefVal;
2355 MOps2[i] = UndefVal;
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002356 }
Mon P Wang67227c22008-11-21 04:25:21 +00002357 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, VT, MOps1, NumConcat);
2358 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, VT, MOps2, NumConcat);
2359
2360 delete [] MOps1;
2361 delete [] MOps2;
2362
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002363 // Readjust mask for new input vector length.
2364 SmallVector<SDValue, 8> MappedOps;
Mon P Wang7bfa4642008-11-16 05:06:27 +00002365 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002366 if (Mask.getOperand(i).getOpcode() == ISD::UNDEF) {
2367 MappedOps.push_back(Mask.getOperand(i));
2368 } else {
Mon P Wang7bfa4642008-11-16 05:06:27 +00002369 int Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2370 if (Idx < SrcNumElts)
2371 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2372 else
2373 MappedOps.push_back(DAG.getConstant(Idx + MaskNumElts - SrcNumElts,
2374 MaskEltVT));
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002375 }
2376 }
2377 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2378 &MappedOps[0], MappedOps.size());
2379
Mon P Wang67227c22008-11-21 04:25:21 +00002380 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002381 return;
2382 }
2383
Mon P Wang7bfa4642008-11-16 05:06:27 +00002384 if (SrcNumElts > MaskNumElts) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002385 // Resulting vector is shorter than the incoming vector.
Mon P Wang7bfa4642008-11-16 05:06:27 +00002386 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,0)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002387 // Shuffle extracts 1st vector.
Mon P Wang67227c22008-11-21 04:25:21 +00002388 setValue(&I, Src1);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002389 return;
2390 }
2391
Mon P Wang7bfa4642008-11-16 05:06:27 +00002392 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,MaskNumElts)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002393 // Shuffle extracts 2nd vector.
Mon P Wang67227c22008-11-21 04:25:21 +00002394 setValue(&I, Src2);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002395 return;
2396 }
2397
Mon P Wang7bfa4642008-11-16 05:06:27 +00002398 // Analyze the access pattern of the vector to see if we can extract
2399 // two subvectors and do the shuffle. The analysis is done by calculating
2400 // the range of elements the mask access on both vectors.
2401 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2402 int MaxRange[2] = {-1, -1};
2403
2404 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002405 SDValue Arg = Mask.getOperand(i);
2406 if (Arg.getOpcode() != ISD::UNDEF) {
2407 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Mon P Wang7bfa4642008-11-16 05:06:27 +00002408 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2409 int Input = 0;
2410 if (Idx >= SrcNumElts) {
2411 Input = 1;
2412 Idx -= SrcNumElts;
2413 }
2414 if (Idx > MaxRange[Input])
2415 MaxRange[Input] = Idx;
2416 if (Idx < MinRange[Input])
2417 MinRange[Input] = Idx;
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002418 }
2419 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002420
Mon P Wang7bfa4642008-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.
Mon P Wang67227c22008-11-21 04:25:21 +00002423 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
Mon P Wang7bfa4642008-11-16 05:06:27 +00002424 int StartIdx[2]; // StartIdx to extract from
2425 for (int Input=0; Input < 2; ++Input) {
2426 if (MinRange[Input] == SrcNumElts+1 && MaxRange[Input] == -1) {
2427 RangeUse[Input] = 0; // Unused
2428 StartIdx[Input] = 0;
2429 } else if (MaxRange[Input] - MinRange[Input] < MaskNumElts) {
2430 // Fits within range but we should see if we can find a good
Mon P Wang67227c22008-11-21 04:25:21 +00002431 // start index that is a multiple of the mask length.
Mon P Wang7bfa4642008-11-16 05:06:27 +00002432 if (MaxRange[Input] < MaskNumElts) {
2433 RangeUse[Input] = 1; // Extract from beginning of the vector
2434 StartIdx[Input] = 0;
2435 } else {
2436 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
Mon P Wang87d4dd52008-11-23 04:35:05 +00002437 if (MaxRange[Input] - StartIdx[Input] < MaskNumElts &&
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002438 StartIdx[Input] + MaskNumElts < SrcNumElts)
Mon P Wang7bfa4642008-11-16 05:06:27 +00002439 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wang7bfa4642008-11-16 05:06:27 +00002440 }
Mon P Wang67227c22008-11-21 04:25:21 +00002441 }
Mon P Wang7bfa4642008-11-16 05:06:27 +00002442 }
2443
2444 if (RangeUse[0] == 0 && RangeUse[0] == 0) {
2445 setValue(&I, DAG.getNode(ISD::UNDEF, VT)); // Vectors are not used.
2446 return;
2447 }
2448 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2449 // Extract appropriate subvector and generate a vector shuffle
2450 for (int Input=0; Input < 2; ++Input) {
Mon P Wang67227c22008-11-21 04:25:21 +00002451 SDValue& Src = Input == 0 ? Src1 : Src2;
Mon P Wang7bfa4642008-11-16 05:06:27 +00002452 if (RangeUse[Input] == 0) {
Mon P Wang67227c22008-11-21 04:25:21 +00002453 Src = DAG.getNode(ISD::UNDEF, VT);
Mon P Wang7bfa4642008-11-16 05:06:27 +00002454 } else {
Mon P Wang67227c22008-11-21 04:25:21 +00002455 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, VT, Src,
2456 DAG.getIntPtrConstant(StartIdx[Input]));
Mon P Wang7bfa4642008-11-16 05:06:27 +00002457 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002458 }
Mon P Wang7bfa4642008-11-16 05:06:27 +00002459 // Calculate new mask.
2460 SmallVector<SDValue, 8> MappedOps;
2461 for (int i = 0; i != MaskNumElts; ++i) {
2462 SDValue Arg = Mask.getOperand(i);
2463 if (Arg.getOpcode() == ISD::UNDEF) {
2464 MappedOps.push_back(Arg);
2465 } else {
2466 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2467 if (Idx < SrcNumElts)
2468 MappedOps.push_back(DAG.getConstant(Idx - StartIdx[0], MaskEltVT));
2469 else {
2470 Idx = Idx - SrcNumElts - StartIdx[1] + MaskNumElts;
2471 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002472 }
Mon P Wang7bfa4642008-11-16 05:06:27 +00002473 }
2474 }
2475 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2476 &MappedOps[0], MappedOps.size());
Mon P Wang67227c22008-11-21 04:25:21 +00002477 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
Mon P Wang7bfa4642008-11-16 05:06:27 +00002478 return;
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002479 }
2480 }
2481
Mon P Wang7bfa4642008-11-16 05:06:27 +00002482 // We can't use either concat vectors or extract subvectors so fall back to
2483 // replacing the shuffle with extract and build vector.
2484 // to insert and build vector.
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002485 MVT EltVT = VT.getVectorElementType();
2486 MVT PtrVT = TLI.getPointerTy();
2487 SmallVector<SDValue,8> Ops;
Mon P Wang7bfa4642008-11-16 05:06:27 +00002488 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002489 SDValue Arg = Mask.getOperand(i);
2490 if (Arg.getOpcode() == ISD::UNDEF) {
2491 Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2492 } else {
2493 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Mon P Wang7bfa4642008-11-16 05:06:27 +00002494 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2495 if (Idx < SrcNumElts)
Mon P Wang67227c22008-11-21 04:25:21 +00002496 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Src1,
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002497 DAG.getConstant(Idx, PtrVT)));
2498 else
Mon P Wang67227c22008-11-21 04:25:21 +00002499 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Src2,
Mon P Wang7bfa4642008-11-16 05:06:27 +00002500 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
Mon P Wangbff5d9c2008-11-10 04:46:22 +00002501 }
2502 }
2503 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size()));
Dan Gohman13aeef92008-09-03 16:12:24 +00002504}
2505
2506void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2507 const Value *Op0 = I.getOperand(0);
2508 const Value *Op1 = I.getOperand(1);
2509 const Type *AggTy = I.getType();
2510 const Type *ValTy = Op1->getType();
2511 bool IntoUndef = isa<UndefValue>(Op0);
2512 bool FromUndef = isa<UndefValue>(Op1);
2513
2514 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2515 I.idx_begin(), I.idx_end());
2516
2517 SmallVector<MVT, 4> AggValueVTs;
2518 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2519 SmallVector<MVT, 4> ValValueVTs;
2520 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2521
2522 unsigned NumAggValues = AggValueVTs.size();
2523 unsigned NumValValues = ValValueVTs.size();
2524 SmallVector<SDValue, 4> Values(NumAggValues);
2525
2526 SDValue Agg = getValue(Op0);
2527 SDValue Val = getValue(Op1);
2528 unsigned i = 0;
2529 // Copy the beginning value(s) from the original aggregate.
2530 for (; i != LinearIndex; ++i)
2531 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2532 SDValue(Agg.getNode(), Agg.getResNo() + i);
2533 // Copy values from the inserted value(s).
2534 for (; i != LinearIndex + NumValValues; ++i)
2535 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2536 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2537 // Copy remaining value(s) from the original aggregate.
2538 for (; i != NumAggValues; ++i)
2539 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2540 SDValue(Agg.getNode(), Agg.getResNo() + i);
2541
Duncan Sands42d7bb82008-12-01 11:41:29 +00002542 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2543 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2544 &Values[0], NumAggValues));
Dan Gohman13aeef92008-09-03 16:12:24 +00002545}
2546
2547void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2548 const Value *Op0 = I.getOperand(0);
2549 const Type *AggTy = Op0->getType();
2550 const Type *ValTy = I.getType();
2551 bool OutOfUndef = isa<UndefValue>(Op0);
2552
2553 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2554 I.idx_begin(), I.idx_end());
2555
2556 SmallVector<MVT, 4> ValValueVTs;
2557 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2558
2559 unsigned NumValValues = ValValueVTs.size();
2560 SmallVector<SDValue, 4> Values(NumValValues);
2561
2562 SDValue Agg = getValue(Op0);
2563 // Copy out the selected value(s).
2564 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2565 Values[i - LinearIndex] =
Bill Wendling90e1e4f2008-11-20 07:24:30 +00002566 OutOfUndef ?
2567 DAG.getNode(ISD::UNDEF,
2568 Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2569 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohman13aeef92008-09-03 16:12:24 +00002570
Duncan Sands42d7bb82008-12-01 11:41:29 +00002571 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2572 DAG.getVTList(&ValValueVTs[0], NumValValues),
2573 &Values[0], NumValValues));
Dan Gohman13aeef92008-09-03 16:12:24 +00002574}
2575
2576
2577void SelectionDAGLowering::visitGetElementPtr(User &I) {
2578 SDValue N = getValue(I.getOperand(0));
2579 const Type *Ty = I.getOperand(0)->getType();
2580
2581 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2582 OI != E; ++OI) {
2583 Value *Idx = *OI;
2584 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2585 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2586 if (Field) {
2587 // N = N + Offset
2588 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2589 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2590 DAG.getIntPtrConstant(Offset));
2591 }
2592 Ty = StTy->getElementType(Field);
2593 } else {
2594 Ty = cast<SequentialType>(Ty)->getElementType();
2595
2596 // If this is a constant subscript, handle it quickly.
2597 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2598 if (CI->getZExtValue() == 0) continue;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002599 uint64_t Offs =
Duncan Sandsd68f13b2009-01-12 20:38:59 +00002600 TD->getTypePaddedSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Dan Gohman13aeef92008-09-03 16:12:24 +00002601 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2602 DAG.getIntPtrConstant(Offs));
2603 continue;
2604 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002605
Dan Gohman13aeef92008-09-03 16:12:24 +00002606 // N = N + Idx * ElementSize;
Duncan Sandsd68f13b2009-01-12 20:38:59 +00002607 uint64_t ElementSize = TD->getTypePaddedSize(Ty);
Dan Gohman13aeef92008-09-03 16:12:24 +00002608 SDValue IdxN = getValue(Idx);
2609
2610 // If the index is smaller or larger than intptr_t, truncate or extend
2611 // it.
2612 if (IdxN.getValueType().bitsLT(N.getValueType()))
2613 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2614 else if (IdxN.getValueType().bitsGT(N.getValueType()))
2615 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2616
2617 // If this is a multiply by a power of two, turn it into a shl
2618 // immediately. This is a very common case.
2619 if (ElementSize != 1) {
2620 if (isPowerOf2_64(ElementSize)) {
2621 unsigned Amt = Log2_64(ElementSize);
2622 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2623 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2624 } else {
2625 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2626 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2627 }
2628 }
2629
2630 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2631 }
2632 }
2633 setValue(&I, N);
2634}
2635
2636void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2637 // If this is a fixed sized alloca in the entry block of the function,
2638 // allocate it statically on the stack.
2639 if (FuncInfo.StaticAllocaMap.count(&I))
2640 return; // getValue will auto-populate this.
2641
2642 const Type *Ty = I.getAllocatedType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +00002643 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
Dan Gohman13aeef92008-09-03 16:12:24 +00002644 unsigned Align =
2645 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2646 I.getAlignment());
2647
2648 SDValue AllocSize = getValue(I.getArraySize());
2649 MVT IntPtr = TLI.getPointerTy();
2650 if (IntPtr.bitsLT(AllocSize.getValueType()))
2651 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2652 else if (IntPtr.bitsGT(AllocSize.getValueType()))
2653 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2654
2655 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2656 DAG.getIntPtrConstant(TySize));
2657
2658 // Handle alignment. If the requested alignment is less than or equal to
2659 // the stack alignment, ignore it. If the size is greater than or equal to
2660 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2661 unsigned StackAlign =
2662 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2663 if (Align <= StackAlign)
2664 Align = 0;
2665
2666 // Round the size of the allocation up to the stack alignment size
2667 // by add SA-1 to the size.
2668 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2669 DAG.getIntPtrConstant(StackAlign-1));
2670 // Mask out the low bits for alignment purposes.
2671 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2672 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2673
2674 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2675 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2676 MVT::Other);
2677 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2678 setValue(&I, DSA);
2679 DAG.setRoot(DSA.getValue(1));
2680
2681 // Inform the Frame Information that we have just allocated a variable-sized
2682 // object.
2683 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2684}
2685
2686void SelectionDAGLowering::visitLoad(LoadInst &I) {
2687 const Value *SV = I.getOperand(0);
2688 SDValue Ptr = getValue(SV);
2689
2690 const Type *Ty = I.getType();
2691 bool isVolatile = I.isVolatile();
2692 unsigned Alignment = I.getAlignment();
2693
2694 SmallVector<MVT, 4> ValueVTs;
2695 SmallVector<uint64_t, 4> Offsets;
2696 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2697 unsigned NumValues = ValueVTs.size();
2698 if (NumValues == 0)
2699 return;
2700
2701 SDValue Root;
2702 bool ConstantMemory = false;
2703 if (I.isVolatile())
2704 // Serialize volatile loads with other side effects.
2705 Root = getRoot();
2706 else if (AA->pointsToConstantMemory(SV)) {
2707 // Do not serialize (non-volatile) loads of constant memory with anything.
2708 Root = DAG.getEntryNode();
2709 ConstantMemory = true;
2710 } else {
2711 // Do not serialize non-volatile loads against each other.
2712 Root = DAG.getRoot();
2713 }
2714
2715 SmallVector<SDValue, 4> Values(NumValues);
2716 SmallVector<SDValue, 4> Chains(NumValues);
2717 MVT PtrVT = Ptr.getValueType();
2718 for (unsigned i = 0; i != NumValues; ++i) {
2719 SDValue L = DAG.getLoad(ValueVTs[i], Root,
2720 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2721 DAG.getConstant(Offsets[i], PtrVT)),
2722 SV, Offsets[i],
2723 isVolatile, Alignment);
2724 Values[i] = L;
2725 Chains[i] = L.getValue(1);
2726 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002727
Dan Gohman13aeef92008-09-03 16:12:24 +00002728 if (!ConstantMemory) {
2729 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2730 &Chains[0], NumValues);
2731 if (isVolatile)
2732 DAG.setRoot(Chain);
2733 else
2734 PendingLoads.push_back(Chain);
2735 }
2736
Duncan Sands42d7bb82008-12-01 11:41:29 +00002737 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2738 DAG.getVTList(&ValueVTs[0], NumValues),
2739 &Values[0], NumValues));
Dan Gohman13aeef92008-09-03 16:12:24 +00002740}
2741
2742
2743void SelectionDAGLowering::visitStore(StoreInst &I) {
2744 Value *SrcV = I.getOperand(0);
2745 Value *PtrV = I.getOperand(1);
2746
2747 SmallVector<MVT, 4> ValueVTs;
2748 SmallVector<uint64_t, 4> Offsets;
2749 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2750 unsigned NumValues = ValueVTs.size();
2751 if (NumValues == 0)
2752 return;
2753
2754 // Get the lowered operands. Note that we do this after
2755 // checking if NumResults is zero, because with zero results
2756 // the operands won't have values in the map.
2757 SDValue Src = getValue(SrcV);
2758 SDValue Ptr = getValue(PtrV);
2759
2760 SDValue Root = getRoot();
2761 SmallVector<SDValue, 4> Chains(NumValues);
2762 MVT PtrVT = Ptr.getValueType();
2763 bool isVolatile = I.isVolatile();
2764 unsigned Alignment = I.getAlignment();
2765 for (unsigned i = 0; i != NumValues; ++i)
2766 Chains[i] = DAG.getStore(Root, SDValue(Src.getNode(), Src.getResNo() + i),
2767 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2768 DAG.getConstant(Offsets[i], PtrVT)),
2769 PtrV, Offsets[i],
2770 isVolatile, Alignment);
2771
2772 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2773}
2774
2775/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2776/// node.
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002777void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
Dan Gohman13aeef92008-09-03 16:12:24 +00002778 unsigned Intrinsic) {
2779 bool HasChain = !I.doesNotAccessMemory();
2780 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2781
2782 // Build the operand list.
2783 SmallVector<SDValue, 8> Ops;
2784 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2785 if (OnlyLoad) {
2786 // We don't need to serialize loads against other loads.
2787 Ops.push_back(DAG.getRoot());
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002788 } else {
Dan Gohman13aeef92008-09-03 16:12:24 +00002789 Ops.push_back(getRoot());
2790 }
2791 }
Mon P Wang9de70a12008-11-01 20:24:53 +00002792
2793 // Info is set by getTgtMemInstrinsic
2794 TargetLowering::IntrinsicInfo Info;
2795 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2796
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002797 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Mon P Wang9de70a12008-11-01 20:24:53 +00002798 if (!IsTgtIntrinsic)
2799 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohman13aeef92008-09-03 16:12:24 +00002800
2801 // Add all operands of the call to the operand list.
2802 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2803 SDValue Op = getValue(I.getOperand(i));
2804 assert(TLI.isTypeLegal(Op.getValueType()) &&
2805 "Intrinsic uses a non-legal type?");
2806 Ops.push_back(Op);
2807 }
2808
2809 std::vector<MVT> VTs;
2810 if (I.getType() != Type::VoidTy) {
2811 MVT VT = TLI.getValueType(I.getType());
2812 if (VT.isVector()) {
2813 const VectorType *DestTy = cast<VectorType>(I.getType());
2814 MVT EltVT = TLI.getValueType(DestTy->getElementType());
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002815
Dan Gohman13aeef92008-09-03 16:12:24 +00002816 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2817 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2818 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002819
Dan Gohman13aeef92008-09-03 16:12:24 +00002820 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2821 VTs.push_back(VT);
2822 }
2823 if (HasChain)
2824 VTs.push_back(MVT::Other);
2825
2826 const MVT *VTList = DAG.getNodeValueTypes(VTs);
2827
2828 // Create the node.
2829 SDValue Result;
Mon P Wang9de70a12008-11-01 20:24:53 +00002830 if (IsTgtIntrinsic) {
2831 // This is target intrinsic that touches memory
2832 Result = DAG.getMemIntrinsicNode(Info.opc, VTList, VTs.size(),
2833 &Ops[0], Ops.size(),
2834 Info.memVT, Info.ptrVal, Info.offset,
2835 Info.align, Info.vol,
2836 Info.readMem, Info.writeMem);
2837 }
2838 else if (!HasChain)
Dan Gohman13aeef92008-09-03 16:12:24 +00002839 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2840 &Ops[0], Ops.size());
2841 else if (I.getType() != Type::VoidTy)
2842 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2843 &Ops[0], Ops.size());
2844 else
2845 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2846 &Ops[0], Ops.size());
2847
2848 if (HasChain) {
2849 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2850 if (OnlyLoad)
2851 PendingLoads.push_back(Chain);
2852 else
2853 DAG.setRoot(Chain);
2854 }
2855 if (I.getType() != Type::VoidTy) {
2856 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2857 MVT VT = TLI.getValueType(PTy);
2858 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002859 }
Dan Gohman13aeef92008-09-03 16:12:24 +00002860 setValue(&I, Result);
2861 }
2862}
2863
2864/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2865static GlobalVariable *ExtractTypeInfo(Value *V) {
2866 V = V->stripPointerCasts();
2867 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2868 assert ((GV || isa<ConstantPointerNull>(V)) &&
2869 "TypeInfo must be a global variable or NULL");
2870 return GV;
2871}
2872
2873namespace llvm {
2874
2875/// AddCatchInfo - Extract the personality and type infos from an eh.selector
2876/// call, and add them to the specified machine basic block.
2877void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2878 MachineBasicBlock *MBB) {
2879 // Inform the MachineModuleInfo of the personality for this landing pad.
2880 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2881 assert(CE->getOpcode() == Instruction::BitCast &&
2882 isa<Function>(CE->getOperand(0)) &&
2883 "Personality should be a function");
2884 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2885
2886 // Gather all the type infos for this landing pad and pass them along to
2887 // MachineModuleInfo.
2888 std::vector<GlobalVariable *> TyInfo;
2889 unsigned N = I.getNumOperands();
2890
2891 for (unsigned i = N - 1; i > 2; --i) {
2892 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2893 unsigned FilterLength = CI->getZExtValue();
2894 unsigned FirstCatch = i + FilterLength + !FilterLength;
2895 assert (FirstCatch <= N && "Invalid filter length");
2896
2897 if (FirstCatch < N) {
2898 TyInfo.reserve(N - FirstCatch);
2899 for (unsigned j = FirstCatch; j < N; ++j)
2900 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2901 MMI->addCatchTypeInfo(MBB, TyInfo);
2902 TyInfo.clear();
2903 }
2904
2905 if (!FilterLength) {
2906 // Cleanup.
2907 MMI->addCleanup(MBB);
2908 } else {
2909 // Filter.
2910 TyInfo.reserve(FilterLength - 1);
2911 for (unsigned j = i + 1; j < FirstCatch; ++j)
2912 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2913 MMI->addFilterTypeInfo(MBB, TyInfo);
2914 TyInfo.clear();
2915 }
2916
2917 N = i;
2918 }
2919 }
2920
2921 if (N > 3) {
2922 TyInfo.reserve(N - 3);
2923 for (unsigned j = 3; j < N; ++j)
2924 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2925 MMI->addCatchTypeInfo(MBB, TyInfo);
2926 }
2927}
2928
2929}
2930
Bill Wendling8b2e2d82008-09-22 00:44:35 +00002931/// GetSignificand - Get the significand and build it into a floating-point
2932/// number with exponent of 1:
2933///
2934/// Op = (Op & 0x007fffff) | 0x3f800000;
2935///
2936/// where Op is the hexidecimal representation of floating point value.
Bill Wendlingf590a042008-09-09 20:39:27 +00002937static SDValue
2938GetSignificand(SelectionDAG &DAG, SDValue Op) {
Bill Wendling8e76c342009-01-20 21:17:57 +00002939 SDValue t1 = DAG.getNode(ISD::AND, MVT::i32, Op,
2940 DAG.getConstant(0x007fffff, MVT::i32));
2941 SDValue t2 = DAG.getNode(ISD::OR, MVT::i32, t1,
2942 DAG.getConstant(0x3f800000, MVT::i32));
2943 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t2);
Bill Wendlingf590a042008-09-09 20:39:27 +00002944}
2945
Bill Wendling8b2e2d82008-09-22 00:44:35 +00002946/// GetExponent - Get the exponent:
2947///
Bill Wendling8e76c342009-01-20 21:17:57 +00002948/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendling8b2e2d82008-09-22 00:44:35 +00002949///
2950/// where Op is the hexidecimal representation of floating point value.
Bill Wendlingf590a042008-09-09 20:39:27 +00002951static SDValue
Bill Wendling583c9c42009-01-20 06:10:42 +00002952GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI) {
Bill Wendling8e76c342009-01-20 21:17:57 +00002953 SDValue t0 = DAG.getNode(ISD::AND, MVT::i32, Op,
2954 DAG.getConstant(0x7f800000, MVT::i32));
2955 SDValue t1 = DAG.getNode(ISD::SRL, MVT::i32, t0,
2956 DAG.getConstant(23, TLI.getShiftAmountTy()));
2957 SDValue t2 = DAG.getNode(ISD::SUB, MVT::i32, t1,
2958 DAG.getConstant(127, MVT::i32));
2959 return DAG.getNode(ISD::SINT_TO_FP, MVT::f32, t2);
Bill Wendlingf590a042008-09-09 20:39:27 +00002960}
2961
Bill Wendling8b2e2d82008-09-22 00:44:35 +00002962/// getF32Constant - Get 32-bit floating point constant.
2963static SDValue
2964getF32Constant(SelectionDAG &DAG, unsigned Flt) {
2965 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
2966}
2967
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002968/// Inlined utility function to implement binary input atomic intrinsics for
Dan Gohman13aeef92008-09-03 16:12:24 +00002969/// visitIntrinsicCall: I is a call instruction
2970/// Op is the associated NodeType for I
2971const char *
2972SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002973 SDValue Root = getRoot();
Dan Gohmanbebba8d2008-12-23 21:37:04 +00002974 SDValue L =
2975 DAG.getAtomic(Op, getValue(I.getOperand(2)).getValueType().getSimpleVT(),
2976 Root,
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00002977 getValue(I.getOperand(1)),
Dan Gohmanbebba8d2008-12-23 21:37:04 +00002978 getValue(I.getOperand(2)),
2979 I.getOperand(1));
Dan Gohman13aeef92008-09-03 16:12:24 +00002980 setValue(&I, L);
2981 DAG.setRoot(L.getValue(1));
2982 return 0;
2983}
2984
Bill Wendlingea340c72008-12-10 00:28:22 +00002985// implVisitAluOverflow - Lower arithmetic overflow instrinsics.
Bill Wendling7e04be62008-12-09 22:08:41 +00002986const char *
2987SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
Bill Wendlingea340c72008-12-10 00:28:22 +00002988 SDValue Op1 = getValue(I.getOperand(1));
2989 SDValue Op2 = getValue(I.getOperand(2));
Bill Wendling7e04be62008-12-09 22:08:41 +00002990
Bill Wendlingea340c72008-12-10 00:28:22 +00002991 MVT ValueVTs[] = { Op1.getValueType(), MVT::i1 };
2992 SDValue Ops[] = { Op1, Op2 };
Bill Wendling7e04be62008-12-09 22:08:41 +00002993
Bill Wendlingea340c72008-12-10 00:28:22 +00002994 SDValue Result = DAG.getNode(Op, DAG.getVTList(&ValueVTs[0], 2), &Ops[0], 2);
Bill Wendling7e04be62008-12-09 22:08:41 +00002995
Bill Wendlingea340c72008-12-10 00:28:22 +00002996 setValue(&I, Result);
2997 return 0;
2998}
Bill Wendling7e04be62008-12-09 22:08:41 +00002999
Bill Wendling25893a32008-09-09 22:13:54 +00003000/// visitExp - Lower an exp intrinsic. Handles the special sequences for
3001/// limited-precision mode.
Dale Johannesen062bb5d2008-09-05 18:38:42 +00003002void
3003SelectionDAGLowering::visitExp(CallInst &I) {
3004 SDValue result;
Bill Wendling25893a32008-09-09 22:13:54 +00003005
3006 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3007 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3008 SDValue Op = getValue(I.getOperand(1));
3009
3010 // Put the exponent in the right bit position for later addition to the
3011 // final result:
3012 //
3013 // #define LOG2OFe 1.4426950f
3014 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3015 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003016 getF32Constant(DAG, 0x3fb8aa3b));
Bill Wendling25893a32008-09-09 22:13:54 +00003017 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3018
3019 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3020 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3021 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3022
3023 // IntegerPartOfX <<= 23;
3024 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
Bill Wendling583c9c42009-01-20 06:10:42 +00003025 DAG.getConstant(23, TLI.getShiftAmountTy()));
Bill Wendling25893a32008-09-09 22:13:54 +00003026
3027 if (LimitFloatPrecision <= 6) {
3028 // For floating-point precision of 6:
3029 //
3030 // TwoToFractionalPartOfX =
3031 // 0.997535578f +
3032 // (0.735607626f + 0.252464424f * x) * x;
3033 //
3034 // error 0.0144103317, which is 6 bits
3035 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003036 getF32Constant(DAG, 0x3e814304));
Bill Wendling25893a32008-09-09 22:13:54 +00003037 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003038 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendling25893a32008-09-09 22:13:54 +00003039 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3040 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003041 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendling25893a32008-09-09 22:13:54 +00003042 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3043
3044 // Add the exponent into the result in integer domain.
3045 SDValue t6 = DAG.getNode(ISD::ADD, MVT::i32,
3046 TwoToFracPartOfX, IntegerPartOfX);
3047
3048 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t6);
3049 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3050 // For floating-point precision of 12:
3051 //
3052 // TwoToFractionalPartOfX =
3053 // 0.999892986f +
3054 // (0.696457318f +
3055 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3056 //
3057 // 0.000107046256 error, which is 13 to 14 bits
3058 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003059 getF32Constant(DAG, 0x3da235e3));
Bill Wendling25893a32008-09-09 22:13:54 +00003060 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003061 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendling25893a32008-09-09 22:13:54 +00003062 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3063 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003064 getF32Constant(DAG, 0x3f324b07));
Bill Wendling25893a32008-09-09 22:13:54 +00003065 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3066 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003067 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendling25893a32008-09-09 22:13:54 +00003068 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3069
3070 // Add the exponent into the result in integer domain.
3071 SDValue t8 = DAG.getNode(ISD::ADD, MVT::i32,
3072 TwoToFracPartOfX, IntegerPartOfX);
3073
3074 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t8);
3075 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3076 // For floating-point precision of 18:
3077 //
3078 // TwoToFractionalPartOfX =
3079 // 0.999999982f +
3080 // (0.693148872f +
3081 // (0.240227044f +
3082 // (0.554906021e-1f +
3083 // (0.961591928e-2f +
3084 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3085 //
3086 // error 2.47208000*10^(-7), which is better than 18 bits
3087 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003088 getF32Constant(DAG, 0x3924b03e));
Bill Wendling25893a32008-09-09 22:13:54 +00003089 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003090 getF32Constant(DAG, 0x3ab24b87));
Bill Wendling25893a32008-09-09 22:13:54 +00003091 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3092 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003093 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendling25893a32008-09-09 22:13:54 +00003094 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3095 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003096 getF32Constant(DAG, 0x3d634a1d));
Bill Wendling25893a32008-09-09 22:13:54 +00003097 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3098 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003099 getF32Constant(DAG, 0x3e75fe14));
Bill Wendling25893a32008-09-09 22:13:54 +00003100 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3101 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003102 getF32Constant(DAG, 0x3f317234));
Bill Wendling25893a32008-09-09 22:13:54 +00003103 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3104 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003105 getF32Constant(DAG, 0x3f800000));
Bill Wendling25893a32008-09-09 22:13:54 +00003106 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3107
3108 // Add the exponent into the result in integer domain.
3109 SDValue t14 = DAG.getNode(ISD::ADD, MVT::i32,
3110 TwoToFracPartOfX, IntegerPartOfX);
3111
3112 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t14);
3113 }
3114 } else {
3115 // No special expansion.
3116 result = DAG.getNode(ISD::FEXP,
3117 getValue(I.getOperand(1)).getValueType(),
3118 getValue(I.getOperand(1)));
3119 }
3120
Dale Johannesen062bb5d2008-09-05 18:38:42 +00003121 setValue(&I, result);
3122}
3123
Bill Wendlingf590a042008-09-09 20:39:27 +00003124/// visitLog - Lower a log intrinsic. Handles the special sequences for
3125/// limited-precision mode.
Dale Johannesen062bb5d2008-09-05 18:38:42 +00003126void
3127SelectionDAGLowering::visitLog(CallInst &I) {
3128 SDValue result;
Bill Wendlingf590a042008-09-09 20:39:27 +00003129
3130 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3131 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3132 SDValue Op = getValue(I.getOperand(1));
3133 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3134
3135 // Scale the exponent by log(2) [0.69314718f].
Bill Wendling583c9c42009-01-20 06:10:42 +00003136 SDValue Exp = GetExponent(DAG, Op1, TLI);
Bill Wendlingf590a042008-09-09 20:39:27 +00003137 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003138 getF32Constant(DAG, 0x3f317218));
Bill Wendlingf590a042008-09-09 20:39:27 +00003139
3140 // Get the significand and build it into a floating-point number with
3141 // exponent of 1.
3142 SDValue X = GetSignificand(DAG, Op1);
3143
3144 if (LimitFloatPrecision <= 6) {
3145 // For floating-point precision of 6:
3146 //
3147 // LogofMantissa =
3148 // -1.1609546f +
3149 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00003150 //
Bill Wendlingf590a042008-09-09 20:39:27 +00003151 // error 0.0034276066, which is better than 8 bits
3152 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003153 getF32Constant(DAG, 0xbe74c456));
Bill Wendlingf590a042008-09-09 20:39:27 +00003154 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003155 getF32Constant(DAG, 0x3fb3a2b1));
Bill Wendlingf590a042008-09-09 20:39:27 +00003156 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3157 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003158 getF32Constant(DAG, 0x3f949a29));
Bill Wendlingf590a042008-09-09 20:39:27 +00003159
3160 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3161 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3162 // For floating-point precision of 12:
3163 //
3164 // LogOfMantissa =
3165 // -1.7417939f +
3166 // (2.8212026f +
3167 // (-1.4699568f +
3168 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3169 //
3170 // error 0.000061011436, which is 14 bits
3171 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003172 getF32Constant(DAG, 0xbd67b6d6));
Bill Wendlingf590a042008-09-09 20:39:27 +00003173 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003174 getF32Constant(DAG, 0x3ee4f4b8));
Bill Wendlingf590a042008-09-09 20:39:27 +00003175 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3176 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003177 getF32Constant(DAG, 0x3fbc278b));
Bill Wendlingf590a042008-09-09 20:39:27 +00003178 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3179 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003180 getF32Constant(DAG, 0x40348e95));
Bill Wendlingf590a042008-09-09 20:39:27 +00003181 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3182 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003183 getF32Constant(DAG, 0x3fdef31a));
Bill Wendlingf590a042008-09-09 20:39:27 +00003184
3185 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3186 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3187 // For floating-point precision of 18:
3188 //
3189 // LogOfMantissa =
3190 // -2.1072184f +
3191 // (4.2372794f +
3192 // (-3.7029485f +
3193 // (2.2781945f +
3194 // (-0.87823314f +
3195 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3196 //
3197 // error 0.0000023660568, which is better than 18 bits
3198 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003199 getF32Constant(DAG, 0xbc91e5ac));
Bill Wendlingf590a042008-09-09 20:39:27 +00003200 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003201 getF32Constant(DAG, 0x3e4350aa));
Bill Wendlingf590a042008-09-09 20:39:27 +00003202 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3203 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003204 getF32Constant(DAG, 0x3f60d3e3));
Bill Wendlingf590a042008-09-09 20:39:27 +00003205 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3206 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003207 getF32Constant(DAG, 0x4011cdf0));
Bill Wendlingf590a042008-09-09 20:39:27 +00003208 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3209 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003210 getF32Constant(DAG, 0x406cfd1c));
Bill Wendlingf590a042008-09-09 20:39:27 +00003211 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3212 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003213 getF32Constant(DAG, 0x408797cb));
Bill Wendlingf590a042008-09-09 20:39:27 +00003214 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3215 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003216 getF32Constant(DAG, 0x4006dcab));
Bill Wendlingf590a042008-09-09 20:39:27 +00003217
3218 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3219 }
3220 } else {
3221 // No special expansion.
3222 result = DAG.getNode(ISD::FLOG,
3223 getValue(I.getOperand(1)).getValueType(),
3224 getValue(I.getOperand(1)));
3225 }
3226
Dale Johannesen062bb5d2008-09-05 18:38:42 +00003227 setValue(&I, result);
3228}
3229
Bill Wendling0b40cbd2008-09-09 00:28:24 +00003230/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3231/// limited-precision mode.
Dale Johannesen062bb5d2008-09-05 18:38:42 +00003232void
3233SelectionDAGLowering::visitLog2(CallInst &I) {
3234 SDValue result;
Bill Wendling0b40cbd2008-09-09 00:28:24 +00003235
Dale Johannesend2cd53d2008-09-05 23:49:37 +00003236 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling0b40cbd2008-09-09 00:28:24 +00003237 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3238 SDValue Op = getValue(I.getOperand(1));
3239 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3240
Bill Wendlingf590a042008-09-09 20:39:27 +00003241 // Get the exponent.
Bill Wendling583c9c42009-01-20 06:10:42 +00003242 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI);
Bill Wendling0b40cbd2008-09-09 00:28:24 +00003243
3244 // Get the significand and build it into a floating-point number with
Bill Wendlingf590a042008-09-09 20:39:27 +00003245 // exponent of 1.
3246 SDValue X = GetSignificand(DAG, Op1);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00003247
Bill Wendling0b40cbd2008-09-09 00:28:24 +00003248 // Different possible minimax approximations of significand in
3249 // floating-point for various degrees of accuracy over [1,2].
3250 if (LimitFloatPrecision <= 6) {
3251 // For floating-point precision of 6:
3252 //
3253 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3254 //
3255 // error 0.0049451742, which is more than 7 bits
Bill Wendlingf590a042008-09-09 20:39:27 +00003256 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003257 getF32Constant(DAG, 0xbeb08fe0));
Bill Wendlingf590a042008-09-09 20:39:27 +00003258 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003259 getF32Constant(DAG, 0x40019463));
Bill Wendlingf590a042008-09-09 20:39:27 +00003260 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3261 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003262 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling0b40cbd2008-09-09 00:28:24 +00003263
3264 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3265 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3266 // For floating-point precision of 12:
3267 //
3268 // Log2ofMantissa =
3269 // -2.51285454f +
3270 // (4.07009056f +
3271 // (-2.12067489f +
3272 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00003273 //
Bill Wendling0b40cbd2008-09-09 00:28:24 +00003274 // error 0.0000876136000, which is better than 13 bits
Bill Wendlingf590a042008-09-09 20:39:27 +00003275 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003276 getF32Constant(DAG, 0xbda7262e));
Bill Wendlingf590a042008-09-09 20:39:27 +00003277 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003278 getF32Constant(DAG, 0x3f25280b));
Bill Wendlingf590a042008-09-09 20:39:27 +00003279 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3280 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003281 getF32Constant(DAG, 0x4007b923));
Bill Wendlingf590a042008-09-09 20:39:27 +00003282 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3283 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003284 getF32Constant(DAG, 0x40823e2f));
Bill Wendlingf590a042008-09-09 20:39:27 +00003285 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3286 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003287 getF32Constant(DAG, 0x4020d29c));
Bill Wendling0b40cbd2008-09-09 00:28:24 +00003288
3289 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3290 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3291 // For floating-point precision of 18:
3292 //
3293 // Log2ofMantissa =
3294 // -3.0400495f +
3295 // (6.1129976f +
3296 // (-5.3420409f +
3297 // (3.2865683f +
3298 // (-1.2669343f +
3299 // (0.27515199f -
3300 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3301 //
3302 // error 0.0000018516, which is better than 18 bits
Bill Wendlingf590a042008-09-09 20:39:27 +00003303 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003304 getF32Constant(DAG, 0xbcd2769e));
Bill Wendlingf590a042008-09-09 20:39:27 +00003305 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003306 getF32Constant(DAG, 0x3e8ce0b9));
Bill Wendlingf590a042008-09-09 20:39:27 +00003307 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3308 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003309 getF32Constant(DAG, 0x3fa22ae7));
Bill Wendlingf590a042008-09-09 20:39:27 +00003310 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3311 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003312 getF32Constant(DAG, 0x40525723));
Bill Wendlingf590a042008-09-09 20:39:27 +00003313 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3314 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003315 getF32Constant(DAG, 0x40aaf200));
Bill Wendlingf590a042008-09-09 20:39:27 +00003316 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3317 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003318 getF32Constant(DAG, 0x40c39dad));
Bill Wendling0b40cbd2008-09-09 00:28:24 +00003319 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
Bill Wendlingf590a042008-09-09 20:39:27 +00003320 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003321 getF32Constant(DAG, 0x4042902c));
Bill Wendling0b40cbd2008-09-09 00:28:24 +00003322
3323 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3324 }
Dale Johannesend2cd53d2008-09-05 23:49:37 +00003325 } else {
Bill Wendling0b40cbd2008-09-09 00:28:24 +00003326 // No special expansion.
Dale Johannesend2cd53d2008-09-05 23:49:37 +00003327 result = DAG.getNode(ISD::FLOG2,
3328 getValue(I.getOperand(1)).getValueType(),
3329 getValue(I.getOperand(1)));
3330 }
Bill Wendling0b40cbd2008-09-09 00:28:24 +00003331
Dale Johannesen062bb5d2008-09-05 18:38:42 +00003332 setValue(&I, result);
3333}
3334
Bill Wendling0b40cbd2008-09-09 00:28:24 +00003335/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3336/// limited-precision mode.
Dale Johannesen062bb5d2008-09-05 18:38:42 +00003337void
3338SelectionDAGLowering::visitLog10(CallInst &I) {
3339 SDValue result;
Bill Wendling22922462008-10-19 20:34:04 +00003340
Dale Johannesen91e305b2008-09-05 21:27:19 +00003341 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling0b40cbd2008-09-09 00:28:24 +00003342 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3343 SDValue Op = getValue(I.getOperand(1));
3344 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3345
Bill Wendlingf590a042008-09-09 20:39:27 +00003346 // Scale the exponent by log10(2) [0.30102999f].
Bill Wendling583c9c42009-01-20 06:10:42 +00003347 SDValue Exp = GetExponent(DAG, Op1, TLI);
Bill Wendlingf590a042008-09-09 20:39:27 +00003348 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003349 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling0b40cbd2008-09-09 00:28:24 +00003350
3351 // Get the significand and build it into a floating-point number with
Bill Wendlingf590a042008-09-09 20:39:27 +00003352 // exponent of 1.
3353 SDValue X = GetSignificand(DAG, Op1);
Bill Wendling0b40cbd2008-09-09 00:28:24 +00003354
3355 if (LimitFloatPrecision <= 6) {
Bill Wendlingf083e002008-09-09 18:42:23 +00003356 // For floating-point precision of 6:
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00003357 //
Bill Wendlingf083e002008-09-09 18:42:23 +00003358 // Log10ofMantissa =
3359 // -0.50419619f +
3360 // (0.60948995f - 0.10380950f * x) * x;
3361 //
3362 // error 0.0014886165, which is 6 bits
Bill Wendlingf590a042008-09-09 20:39:27 +00003363 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003364 getF32Constant(DAG, 0xbdd49a13));
Bill Wendlingf590a042008-09-09 20:39:27 +00003365 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003366 getF32Constant(DAG, 0x3f1c0789));
Bill Wendlingf590a042008-09-09 20:39:27 +00003367 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3368 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003369 getF32Constant(DAG, 0x3f011300));
Bill Wendlingf083e002008-09-09 18:42:23 +00003370
3371 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling0b40cbd2008-09-09 00:28:24 +00003372 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3373 // For floating-point precision of 12:
3374 //
3375 // Log10ofMantissa =
3376 // -0.64831180f +
3377 // (0.91751397f +
3378 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3379 //
3380 // error 0.00019228036, which is better than 12 bits
Bill Wendlingf590a042008-09-09 20:39:27 +00003381 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003382 getF32Constant(DAG, 0x3d431f31));
Bill Wendlingf590a042008-09-09 20:39:27 +00003383 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003384 getF32Constant(DAG, 0x3ea21fb2));
Bill Wendlingf590a042008-09-09 20:39:27 +00003385 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3386 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003387 getF32Constant(DAG, 0x3f6ae232));
Bill Wendlingf590a042008-09-09 20:39:27 +00003388 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3389 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t4,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003390 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling0b40cbd2008-09-09 00:28:24 +00003391
3392 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3393 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingf083e002008-09-09 18:42:23 +00003394 // For floating-point precision of 18:
3395 //
3396 // Log10ofMantissa =
3397 // -0.84299375f +
3398 // (1.5327582f +
3399 // (-1.0688956f +
3400 // (0.49102474f +
3401 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3402 //
3403 // error 0.0000037995730, which is better than 18 bits
Bill Wendlingf590a042008-09-09 20:39:27 +00003404 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003405 getF32Constant(DAG, 0x3c5d51ce));
Bill Wendlingf590a042008-09-09 20:39:27 +00003406 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003407 getF32Constant(DAG, 0x3e00685a));
Bill Wendlingf590a042008-09-09 20:39:27 +00003408 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3409 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003410 getF32Constant(DAG, 0x3efb6798));
Bill Wendlingf590a042008-09-09 20:39:27 +00003411 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3412 SDValue t5 = DAG.getNode(ISD::FSUB, MVT::f32, t4,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003413 getF32Constant(DAG, 0x3f88d192));
Bill Wendlingf590a042008-09-09 20:39:27 +00003414 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3415 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003416 getF32Constant(DAG, 0x3fc4316c));
Bill Wendlingf083e002008-09-09 18:42:23 +00003417 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
Bill Wendlingf590a042008-09-09 20:39:27 +00003418 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t8,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003419 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingf083e002008-09-09 18:42:23 +00003420
3421 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling0b40cbd2008-09-09 00:28:24 +00003422 }
Dale Johannesen91e305b2008-09-05 21:27:19 +00003423 } else {
Bill Wendling0b40cbd2008-09-09 00:28:24 +00003424 // No special expansion.
Dale Johannesen91e305b2008-09-05 21:27:19 +00003425 result = DAG.getNode(ISD::FLOG10,
3426 getValue(I.getOperand(1)).getValueType(),
3427 getValue(I.getOperand(1)));
3428 }
Bill Wendling0b40cbd2008-09-09 00:28:24 +00003429
Dale Johannesen062bb5d2008-09-05 18:38:42 +00003430 setValue(&I, result);
3431}
3432
Bill Wendlingd1641c92008-09-09 22:39:21 +00003433/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3434/// limited-precision mode.
Dale Johannesend93d7992008-09-05 01:48:15 +00003435void
3436SelectionDAGLowering::visitExp2(CallInst &I) {
3437 SDValue result;
Bill Wendlingd1641c92008-09-09 22:39:21 +00003438
Dale Johannesend93d7992008-09-05 01:48:15 +00003439 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlingd1641c92008-09-09 22:39:21 +00003440 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3441 SDValue Op = getValue(I.getOperand(1));
3442
3443 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, Op);
3444
3445 // FractionalPartOfX = x - (float)IntegerPartOfX;
3446 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3447 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, Op, t1);
3448
3449 // IntegerPartOfX <<= 23;
3450 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
Bill Wendling583c9c42009-01-20 06:10:42 +00003451 DAG.getConstant(23, TLI.getShiftAmountTy()));
Bill Wendlingd1641c92008-09-09 22:39:21 +00003452
3453 if (LimitFloatPrecision <= 6) {
3454 // For floating-point precision of 6:
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00003455 //
Bill Wendlingd1641c92008-09-09 22:39:21 +00003456 // TwoToFractionalPartOfX =
3457 // 0.997535578f +
3458 // (0.735607626f + 0.252464424f * x) * x;
3459 //
3460 // error 0.0144103317, which is 6 bits
3461 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003462 getF32Constant(DAG, 0x3e814304));
Bill Wendlingd1641c92008-09-09 22:39:21 +00003463 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003464 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlingd1641c92008-09-09 22:39:21 +00003465 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00003466 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003467 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlingd1641c92008-09-09 22:39:21 +00003468 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3469 SDValue TwoToFractionalPartOfX =
3470 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3471
3472 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3473 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3474 // For floating-point precision of 12:
3475 //
3476 // TwoToFractionalPartOfX =
3477 // 0.999892986f +
3478 // (0.696457318f +
3479 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3480 //
3481 // error 0.000107046256, which is 13 to 14 bits
3482 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003483 getF32Constant(DAG, 0x3da235e3));
Bill Wendlingd1641c92008-09-09 22:39:21 +00003484 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003485 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlingd1641c92008-09-09 22:39:21 +00003486 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00003487 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003488 getF32Constant(DAG, 0x3f324b07));
Bill Wendlingd1641c92008-09-09 22:39:21 +00003489 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3490 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003491 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlingd1641c92008-09-09 22:39:21 +00003492 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3493 SDValue TwoToFractionalPartOfX =
3494 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3495
3496 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3497 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3498 // For floating-point precision of 18:
3499 //
3500 // TwoToFractionalPartOfX =
3501 // 0.999999982f +
3502 // (0.693148872f +
3503 // (0.240227044f +
3504 // (0.554906021e-1f +
3505 // (0.961591928e-2f +
3506 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3507 // error 2.47208000*10^(-7), which is better than 18 bits
3508 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003509 getF32Constant(DAG, 0x3924b03e));
Bill Wendlingd1641c92008-09-09 22:39:21 +00003510 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003511 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlingd1641c92008-09-09 22:39:21 +00003512 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00003513 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003514 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlingd1641c92008-09-09 22:39:21 +00003515 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3516 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003517 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlingd1641c92008-09-09 22:39:21 +00003518 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3519 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003520 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlingd1641c92008-09-09 22:39:21 +00003521 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3522 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003523 getF32Constant(DAG, 0x3f317234));
Bill Wendlingd1641c92008-09-09 22:39:21 +00003524 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3525 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003526 getF32Constant(DAG, 0x3f800000));
Bill Wendlingd1641c92008-09-09 22:39:21 +00003527 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3528 SDValue TwoToFractionalPartOfX =
3529 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3530
3531 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3532 }
Dale Johannesend93d7992008-09-05 01:48:15 +00003533 } else {
Bill Wendling0b40cbd2008-09-09 00:28:24 +00003534 // No special expansion.
Dale Johannesend93d7992008-09-05 01:48:15 +00003535 result = DAG.getNode(ISD::FEXP2,
3536 getValue(I.getOperand(1)).getValueType(),
3537 getValue(I.getOperand(1)));
3538 }
Bill Wendlingd1641c92008-09-09 22:39:21 +00003539
Dale Johannesend93d7992008-09-05 01:48:15 +00003540 setValue(&I, result);
3541}
3542
Bill Wendling96f6fa12008-09-10 00:20:20 +00003543/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3544/// limited-precision mode with x == 10.0f.
3545void
3546SelectionDAGLowering::visitPow(CallInst &I) {
3547 SDValue result;
3548 Value *Val = I.getOperand(1);
3549 bool IsExp10 = false;
3550
3551 if (getValue(Val).getValueType() == MVT::f32 &&
Bill Wendling1249d2f2008-09-10 00:24:59 +00003552 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendling96f6fa12008-09-10 00:20:20 +00003553 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3554 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3555 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3556 APFloat Ten(10.0f);
3557 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3558 }
3559 }
3560 }
3561
3562 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3563 SDValue Op = getValue(I.getOperand(2));
3564
3565 // Put the exponent in the right bit position for later addition to the
3566 // final result:
3567 //
3568 // #define LOG2OF10 3.3219281f
3569 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3570 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003571 getF32Constant(DAG, 0x40549a78));
Bill Wendling96f6fa12008-09-10 00:20:20 +00003572 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3573
3574 // FractionalPartOfX = x - (float)IntegerPartOfX;
3575 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3576 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3577
3578 // IntegerPartOfX <<= 23;
3579 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
Bill Wendling583c9c42009-01-20 06:10:42 +00003580 DAG.getConstant(23, TLI.getShiftAmountTy()));
Bill Wendling96f6fa12008-09-10 00:20:20 +00003581
3582 if (LimitFloatPrecision <= 6) {
3583 // For floating-point precision of 6:
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00003584 //
Bill Wendling96f6fa12008-09-10 00:20:20 +00003585 // twoToFractionalPartOfX =
3586 // 0.997535578f +
3587 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00003588 //
Bill Wendling96f6fa12008-09-10 00:20:20 +00003589 // error 0.0144103317, which is 6 bits
3590 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003591 getF32Constant(DAG, 0x3e814304));
Bill Wendling96f6fa12008-09-10 00:20:20 +00003592 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003593 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendling96f6fa12008-09-10 00:20:20 +00003594 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00003595 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003596 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendling96f6fa12008-09-10 00:20:20 +00003597 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3598 SDValue TwoToFractionalPartOfX =
3599 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3600
3601 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3602 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3603 // For floating-point precision of 12:
3604 //
3605 // TwoToFractionalPartOfX =
3606 // 0.999892986f +
3607 // (0.696457318f +
3608 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3609 //
3610 // error 0.000107046256, which is 13 to 14 bits
3611 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003612 getF32Constant(DAG, 0x3da235e3));
Bill Wendling96f6fa12008-09-10 00:20:20 +00003613 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003614 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendling96f6fa12008-09-10 00:20:20 +00003615 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00003616 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003617 getF32Constant(DAG, 0x3f324b07));
Bill Wendling96f6fa12008-09-10 00:20:20 +00003618 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3619 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003620 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendling96f6fa12008-09-10 00:20:20 +00003621 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3622 SDValue TwoToFractionalPartOfX =
3623 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3624
3625 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3626 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3627 // For floating-point precision of 18:
3628 //
3629 // TwoToFractionalPartOfX =
3630 // 0.999999982f +
3631 // (0.693148872f +
3632 // (0.240227044f +
3633 // (0.554906021e-1f +
3634 // (0.961591928e-2f +
3635 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3636 // error 2.47208000*10^(-7), which is better than 18 bits
3637 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003638 getF32Constant(DAG, 0x3924b03e));
Bill Wendling96f6fa12008-09-10 00:20:20 +00003639 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003640 getF32Constant(DAG, 0x3ab24b87));
Bill Wendling96f6fa12008-09-10 00:20:20 +00003641 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00003642 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003643 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendling96f6fa12008-09-10 00:20:20 +00003644 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3645 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003646 getF32Constant(DAG, 0x3d634a1d));
Bill Wendling96f6fa12008-09-10 00:20:20 +00003647 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3648 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003649 getF32Constant(DAG, 0x3e75fe14));
Bill Wendling96f6fa12008-09-10 00:20:20 +00003650 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3651 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003652 getF32Constant(DAG, 0x3f317234));
Bill Wendling96f6fa12008-09-10 00:20:20 +00003653 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3654 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendling8b2e2d82008-09-22 00:44:35 +00003655 getF32Constant(DAG, 0x3f800000));
Bill Wendling96f6fa12008-09-10 00:20:20 +00003656 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3657 SDValue TwoToFractionalPartOfX =
3658 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3659
3660 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3661 }
3662 } else {
3663 // No special expansion.
3664 result = DAG.getNode(ISD::FPOW,
3665 getValue(I.getOperand(1)).getValueType(),
3666 getValue(I.getOperand(1)),
3667 getValue(I.getOperand(2)));
3668 }
3669
3670 setValue(&I, result);
3671}
3672
Dan Gohman13aeef92008-09-03 16:12:24 +00003673/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3674/// we want to emit this as a call to a named external function, return the name
3675/// otherwise lower it and return null.
3676const char *
3677SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3678 switch (Intrinsic) {
3679 default:
3680 // By default, turn this into a target intrinsic node.
3681 visitTargetIntrinsic(I, Intrinsic);
3682 return 0;
3683 case Intrinsic::vastart: visitVAStart(I); return 0;
3684 case Intrinsic::vaend: visitVAEnd(I); return 0;
3685 case Intrinsic::vacopy: visitVACopy(I); return 0;
3686 case Intrinsic::returnaddress:
3687 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3688 getValue(I.getOperand(1))));
3689 return 0;
Bill Wendlingf29e2a52008-09-26 22:10:44 +00003690 case Intrinsic::frameaddress:
Dan Gohman13aeef92008-09-03 16:12:24 +00003691 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3692 getValue(I.getOperand(1))));
3693 return 0;
3694 case Intrinsic::setjmp:
3695 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3696 break;
3697 case Intrinsic::longjmp:
3698 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3699 break;
Chris Lattner82c2e432008-11-21 16:42:48 +00003700 case Intrinsic::memcpy: {
Dan Gohman13aeef92008-09-03 16:12:24 +00003701 SDValue Op1 = getValue(I.getOperand(1));
3702 SDValue Op2 = getValue(I.getOperand(2));
3703 SDValue Op3 = getValue(I.getOperand(3));
3704 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3705 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3706 I.getOperand(1), 0, I.getOperand(2), 0));
3707 return 0;
3708 }
Chris Lattner82c2e432008-11-21 16:42:48 +00003709 case Intrinsic::memset: {
Dan Gohman13aeef92008-09-03 16:12:24 +00003710 SDValue Op1 = getValue(I.getOperand(1));
3711 SDValue Op2 = getValue(I.getOperand(2));
3712 SDValue Op3 = getValue(I.getOperand(3));
3713 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3714 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3715 I.getOperand(1), 0));
3716 return 0;
3717 }
Chris Lattner82c2e432008-11-21 16:42:48 +00003718 case Intrinsic::memmove: {
Dan Gohman13aeef92008-09-03 16:12:24 +00003719 SDValue Op1 = getValue(I.getOperand(1));
3720 SDValue Op2 = getValue(I.getOperand(2));
3721 SDValue Op3 = getValue(I.getOperand(3));
3722 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3723
3724 // If the source and destination are known to not be aliases, we can
3725 // lower memmove as memcpy.
3726 uint64_t Size = -1ULL;
3727 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanfaeb4a32008-09-12 16:56:44 +00003728 Size = C->getZExtValue();
Dan Gohman13aeef92008-09-03 16:12:24 +00003729 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3730 AliasAnalysis::NoAlias) {
3731 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3732 I.getOperand(1), 0, I.getOperand(2), 0));
3733 return 0;
3734 }
3735
3736 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3737 I.getOperand(1), 0, I.getOperand(2), 0));
3738 return 0;
3739 }
3740 case Intrinsic::dbg_stoppoint: {
Devang Patelfcf1c752009-01-13 00:35:13 +00003741 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohman13aeef92008-09-03 16:12:24 +00003742 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Devang Patel208098b2009-01-19 23:21:49 +00003743 if (DW && DW->ValidDebugInfo(SPI.getContext()))
Dan Gohman13aeef92008-09-03 16:12:24 +00003744 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3745 SPI.getLine(),
3746 SPI.getColumn(),
Devang Patelfcf1c752009-01-13 00:35:13 +00003747 SPI.getContext()));
Dan Gohman13aeef92008-09-03 16:12:24 +00003748 return 0;
3749 }
3750 case Intrinsic::dbg_region_start: {
Devang Patelfcf1c752009-01-13 00:35:13 +00003751 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohman13aeef92008-09-03 16:12:24 +00003752 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Devang Patel208098b2009-01-19 23:21:49 +00003753 if (DW && DW->ValidDebugInfo(RSI.getContext())) {
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00003754 unsigned LabelID =
Devang Patelfcf1c752009-01-13 00:35:13 +00003755 DW->RecordRegionStart(cast<GlobalVariable>(RSI.getContext()));
Dan Gohman13aeef92008-09-03 16:12:24 +00003756 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3757 }
3758
3759 return 0;
3760 }
3761 case Intrinsic::dbg_region_end: {
Devang Patelfcf1c752009-01-13 00:35:13 +00003762 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohman13aeef92008-09-03 16:12:24 +00003763 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Devang Patel208098b2009-01-19 23:21:49 +00003764 if (DW && DW->ValidDebugInfo(REI.getContext())) {
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00003765 unsigned LabelID =
Devang Patelfcf1c752009-01-13 00:35:13 +00003766 DW->RecordRegionEnd(cast<GlobalVariable>(REI.getContext()));
Dan Gohman13aeef92008-09-03 16:12:24 +00003767 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3768 }
3769
3770 return 0;
3771 }
3772 case Intrinsic::dbg_func_start: {
Devang Patelfcf1c752009-01-13 00:35:13 +00003773 DwarfWriter *DW = DAG.getDwarfWriter();
3774 if (!DW) return 0;
Dan Gohman13aeef92008-09-03 16:12:24 +00003775 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3776 Value *SP = FSI.getSubprogram();
Devang Patel2da0cc42009-01-15 23:41:32 +00003777 if (SP && DW->ValidDebugInfo(SP)) {
Dan Gohman13aeef92008-09-03 16:12:24 +00003778 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3779 // what (most?) gdb expects.
Devang Patelfcf1c752009-01-13 00:35:13 +00003780 DISubprogram Subprogram(cast<GlobalVariable>(SP));
3781 DICompileUnit CompileUnit = Subprogram.getCompileUnit();
3782 unsigned SrcFile = DW->RecordSource(CompileUnit.getDirectory(),
3783 CompileUnit.getFilename());
Devang Patel1fdfdd62008-11-06 00:30:09 +00003784 // Record the source line but does not create a label for the normal
3785 // function start. It will be emitted at asm emission time. However,
3786 // create a label if this is a beginning of inlined function.
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00003787 unsigned LabelID =
Devang Patelfcf1c752009-01-13 00:35:13 +00003788 DW->RecordSourceLine(Subprogram.getLineNumber(), 0, SrcFile);
3789 if (DW->getRecordSourceLineCount() != 1)
Devang Patel1fdfdd62008-11-06 00:30:09 +00003790 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
Dan Gohman13aeef92008-09-03 16:12:24 +00003791 }
3792
3793 return 0;
3794 }
3795 case Intrinsic::dbg_declare: {
Devang Patelfcf1c752009-01-13 00:35:13 +00003796 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohman13aeef92008-09-03 16:12:24 +00003797 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3798 Value *Variable = DI.getVariable();
Devang Patel208098b2009-01-19 23:21:49 +00003799 if (DW && DW->ValidDebugInfo(Variable))
Dan Gohman13aeef92008-09-03 16:12:24 +00003800 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3801 getValue(DI.getAddress()), getValue(Variable)));
3802 return 0;
3803 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00003804
Dan Gohman13aeef92008-09-03 16:12:24 +00003805 case Intrinsic::eh_exception: {
3806 if (!CurMBB->isLandingPad()) {
3807 // FIXME: Mark exception register as live in. Hack for PR1508.
3808 unsigned Reg = TLI.getExceptionAddressRegister();
3809 if (Reg) CurMBB->addLiveIn(Reg);
3810 }
3811 // Insert the EXCEPTIONADDR instruction.
3812 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3813 SDValue Ops[1];
3814 Ops[0] = DAG.getRoot();
3815 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3816 setValue(&I, Op);
3817 DAG.setRoot(Op.getValue(1));
3818 return 0;
3819 }
3820
3821 case Intrinsic::eh_selector_i32:
3822 case Intrinsic::eh_selector_i64: {
3823 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3824 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3825 MVT::i32 : MVT::i64);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00003826
Dan Gohman13aeef92008-09-03 16:12:24 +00003827 if (MMI) {
3828 if (CurMBB->isLandingPad())
3829 AddCatchInfo(I, MMI, CurMBB);
3830 else {
3831#ifndef NDEBUG
3832 FuncInfo.CatchInfoLost.insert(&I);
3833#endif
3834 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3835 unsigned Reg = TLI.getExceptionSelectorRegister();
3836 if (Reg) CurMBB->addLiveIn(Reg);
3837 }
3838
3839 // Insert the EHSELECTION instruction.
3840 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3841 SDValue Ops[2];
3842 Ops[0] = getValue(I.getOperand(1));
3843 Ops[1] = getRoot();
3844 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3845 setValue(&I, Op);
3846 DAG.setRoot(Op.getValue(1));
3847 } else {
3848 setValue(&I, DAG.getConstant(0, VT));
3849 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00003850
Dan Gohman13aeef92008-09-03 16:12:24 +00003851 return 0;
3852 }
3853
3854 case Intrinsic::eh_typeid_for_i32:
3855 case Intrinsic::eh_typeid_for_i64: {
3856 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3857 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3858 MVT::i32 : MVT::i64);
Anton Korobeynikov382fb242008-09-08 21:13:56 +00003859
Dan Gohman13aeef92008-09-03 16:12:24 +00003860 if (MMI) {
3861 // Find the type id for the given typeinfo.
3862 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3863
3864 unsigned TypeID = MMI->getTypeIDFor(GV);
3865 setValue(&I, DAG.getConstant(TypeID, VT));
3866 } else {
3867 // Return something different to eh_selector.
3868 setValue(&I, DAG.getConstant(1, VT));
3869 }
3870
3871 return 0;
3872 }
3873
Anton Korobeynikov382fb242008-09-08 21:13:56 +00003874 case Intrinsic::eh_return_i32:
3875 case Intrinsic::eh_return_i64:
3876 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
Dan Gohman13aeef92008-09-03 16:12:24 +00003877 MMI->setCallsEHReturn(true);
3878 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3879 MVT::Other,
3880 getControlRoot(),
3881 getValue(I.getOperand(1)),
3882 getValue(I.getOperand(2))));
3883 } else {
3884 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3885 }
3886
3887 return 0;
Anton Korobeynikov382fb242008-09-08 21:13:56 +00003888 case Intrinsic::eh_unwind_init:
3889 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3890 MMI->setCallsUnwindInit(true);
3891 }
Dan Gohman13aeef92008-09-03 16:12:24 +00003892
Anton Korobeynikov382fb242008-09-08 21:13:56 +00003893 return 0;
Dan Gohman13aeef92008-09-03 16:12:24 +00003894
Anton Korobeynikov382fb242008-09-08 21:13:56 +00003895 case Intrinsic::eh_dwarf_cfa: {
3896 MVT VT = getValue(I.getOperand(1)).getValueType();
3897 SDValue CfaArg;
3898 if (VT.bitsGT(TLI.getPointerTy()))
3899 CfaArg = DAG.getNode(ISD::TRUNCATE,
3900 TLI.getPointerTy(), getValue(I.getOperand(1)));
3901 else
3902 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3903 TLI.getPointerTy(), getValue(I.getOperand(1)));
Dan Gohman13aeef92008-09-03 16:12:24 +00003904
Anton Korobeynikov382fb242008-09-08 21:13:56 +00003905 SDValue Offset = DAG.getNode(ISD::ADD,
3906 TLI.getPointerTy(),
3907 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3908 TLI.getPointerTy()),
3909 CfaArg);
3910 setValue(&I, DAG.getNode(ISD::ADD,
3911 TLI.getPointerTy(),
3912 DAG.getNode(ISD::FRAMEADDR,
3913 TLI.getPointerTy(),
3914 DAG.getConstant(0,
3915 TLI.getPointerTy())),
3916 Offset));
3917 return 0;
Dan Gohman13aeef92008-09-03 16:12:24 +00003918 }
3919
Mon P Wang73d31542008-11-10 20:54:11 +00003920 case Intrinsic::convertff:
3921 case Intrinsic::convertfsi:
3922 case Intrinsic::convertfui:
3923 case Intrinsic::convertsif:
3924 case Intrinsic::convertuif:
3925 case Intrinsic::convertss:
3926 case Intrinsic::convertsu:
3927 case Intrinsic::convertus:
3928 case Intrinsic::convertuu: {
3929 ISD::CvtCode Code = ISD::CVT_INVALID;
3930 switch (Intrinsic) {
3931 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
3932 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
3933 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
3934 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
3935 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
3936 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
3937 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
3938 case Intrinsic::convertus: Code = ISD::CVT_US; break;
3939 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
3940 }
3941 MVT DestVT = TLI.getValueType(I.getType());
3942 Value* Op1 = I.getOperand(1);
3943 setValue(&I, DAG.getConvertRndSat(DestVT, getValue(Op1),
3944 DAG.getValueType(DestVT),
3945 DAG.getValueType(getValue(Op1).getValueType()),
3946 getValue(I.getOperand(2)),
3947 getValue(I.getOperand(3)),
3948 Code));
3949 return 0;
3950 }
3951
Dan Gohman13aeef92008-09-03 16:12:24 +00003952 case Intrinsic::sqrt:
3953 setValue(&I, DAG.getNode(ISD::FSQRT,
3954 getValue(I.getOperand(1)).getValueType(),
3955 getValue(I.getOperand(1))));
3956 return 0;
3957 case Intrinsic::powi:
3958 setValue(&I, DAG.getNode(ISD::FPOWI,
3959 getValue(I.getOperand(1)).getValueType(),
3960 getValue(I.getOperand(1)),
3961 getValue(I.getOperand(2))));
3962 return 0;
3963 case Intrinsic::sin:
3964 setValue(&I, DAG.getNode(ISD::FSIN,
3965 getValue(I.getOperand(1)).getValueType(),
3966 getValue(I.getOperand(1))));
3967 return 0;
3968 case Intrinsic::cos:
3969 setValue(&I, DAG.getNode(ISD::FCOS,
3970 getValue(I.getOperand(1)).getValueType(),
3971 getValue(I.getOperand(1))));
3972 return 0;
Dale Johannesen92b33082008-09-04 00:47:13 +00003973 case Intrinsic::log:
Dale Johannesen062bb5d2008-09-05 18:38:42 +00003974 visitLog(I);
Dale Johannesen92b33082008-09-04 00:47:13 +00003975 return 0;
3976 case Intrinsic::log2:
Dale Johannesen062bb5d2008-09-05 18:38:42 +00003977 visitLog2(I);
Dale Johannesen92b33082008-09-04 00:47:13 +00003978 return 0;
3979 case Intrinsic::log10:
Dale Johannesen062bb5d2008-09-05 18:38:42 +00003980 visitLog10(I);
Dale Johannesen92b33082008-09-04 00:47:13 +00003981 return 0;
3982 case Intrinsic::exp:
Dale Johannesen062bb5d2008-09-05 18:38:42 +00003983 visitExp(I);
Dale Johannesen92b33082008-09-04 00:47:13 +00003984 return 0;
3985 case Intrinsic::exp2:
Dale Johannesend93d7992008-09-05 01:48:15 +00003986 visitExp2(I);
Dale Johannesen92b33082008-09-04 00:47:13 +00003987 return 0;
Dan Gohman13aeef92008-09-03 16:12:24 +00003988 case Intrinsic::pow:
Bill Wendling96f6fa12008-09-10 00:20:20 +00003989 visitPow(I);
Dan Gohman13aeef92008-09-03 16:12:24 +00003990 return 0;
3991 case Intrinsic::pcmarker: {
3992 SDValue Tmp = getValue(I.getOperand(1));
3993 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3994 return 0;
3995 }
3996 case Intrinsic::readcyclecounter: {
3997 SDValue Op = getRoot();
3998 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3999 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
4000 &Op, 1);
4001 setValue(&I, Tmp);
4002 DAG.setRoot(Tmp.getValue(1));
4003 return 0;
4004 }
4005 case Intrinsic::part_select: {
4006 // Currently not implemented: just abort
4007 assert(0 && "part_select intrinsic not implemented");
4008 abort();
4009 }
4010 case Intrinsic::part_set: {
4011 // Currently not implemented: just abort
4012 assert(0 && "part_set intrinsic not implemented");
4013 abort();
4014 }
4015 case Intrinsic::bswap:
4016 setValue(&I, DAG.getNode(ISD::BSWAP,
4017 getValue(I.getOperand(1)).getValueType(),
4018 getValue(I.getOperand(1))));
4019 return 0;
4020 case Intrinsic::cttz: {
4021 SDValue Arg = getValue(I.getOperand(1));
4022 MVT Ty = Arg.getValueType();
4023 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
4024 setValue(&I, result);
4025 return 0;
4026 }
4027 case Intrinsic::ctlz: {
4028 SDValue Arg = getValue(I.getOperand(1));
4029 MVT Ty = Arg.getValueType();
4030 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
4031 setValue(&I, result);
4032 return 0;
4033 }
4034 case Intrinsic::ctpop: {
4035 SDValue Arg = getValue(I.getOperand(1));
4036 MVT Ty = Arg.getValueType();
4037 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
4038 setValue(&I, result);
4039 return 0;
4040 }
4041 case Intrinsic::stacksave: {
4042 SDValue Op = getRoot();
4043 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
4044 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
4045 setValue(&I, Tmp);
4046 DAG.setRoot(Tmp.getValue(1));
4047 return 0;
4048 }
4049 case Intrinsic::stackrestore: {
4050 SDValue Tmp = getValue(I.getOperand(1));
4051 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
4052 return 0;
4053 }
Bill Wendling0ac36702008-11-18 11:01:33 +00004054 case Intrinsic::stackprotector: {
Bill Wendling6d54ef92008-11-06 02:29:10 +00004055 // Emit code into the DAG to store the stack guard onto the stack.
4056 MachineFunction &MF = DAG.getMachineFunction();
4057 MachineFrameInfo *MFI = MF.getFrameInfo();
4058 MVT PtrTy = TLI.getPointerTy();
4059
Bill Wendling8126a3f2008-11-07 01:23:58 +00004060 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4061 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
Bill Wendling6d54ef92008-11-06 02:29:10 +00004062
Bill Wendling8126a3f2008-11-07 01:23:58 +00004063 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendling6d54ef92008-11-06 02:29:10 +00004064 MFI->setStackProtectorIndex(FI);
4065
4066 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4067
4068 // Store the stack protector onto the stack.
4069 SDValue Result = DAG.getStore(getRoot(), Src, FIN,
4070 PseudoSourceValue::getFixedStack(FI),
4071 0, true);
4072 setValue(&I, Result);
4073 DAG.setRoot(Result);
4074 return 0;
4075 }
Dan Gohman13aeef92008-09-03 16:12:24 +00004076 case Intrinsic::var_annotation:
4077 // Discard annotate attributes
4078 return 0;
4079
4080 case Intrinsic::init_trampoline: {
4081 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4082
4083 SDValue Ops[6];
4084 Ops[0] = getRoot();
4085 Ops[1] = getValue(I.getOperand(1));
4086 Ops[2] = getValue(I.getOperand(2));
4087 Ops[3] = getValue(I.getOperand(3));
4088 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4089 Ops[5] = DAG.getSrcValue(F);
4090
4091 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
4092 DAG.getNodeValueTypes(TLI.getPointerTy(),
4093 MVT::Other), 2,
4094 Ops, 6);
4095
4096 setValue(&I, Tmp);
4097 DAG.setRoot(Tmp.getValue(1));
4098 return 0;
4099 }
4100
4101 case Intrinsic::gcroot:
4102 if (GFI) {
4103 Value *Alloca = I.getOperand(1);
4104 Constant *TypeMap = cast<Constant>(I.getOperand(2));
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004105
Dan Gohman13aeef92008-09-03 16:12:24 +00004106 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4107 GFI->addStackRoot(FI->getIndex(), TypeMap);
4108 }
4109 return 0;
4110
4111 case Intrinsic::gcread:
4112 case Intrinsic::gcwrite:
4113 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
4114 return 0;
4115
4116 case Intrinsic::flt_rounds: {
4117 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
4118 return 0;
4119 }
4120
4121 case Intrinsic::trap: {
4122 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
4123 return 0;
4124 }
Bill Wendling5fc7e5c2008-11-21 02:03:52 +00004125
Bill Wendling9560f982008-11-21 02:38:44 +00004126 case Intrinsic::uadd_with_overflow:
Bill Wendling7e04be62008-12-09 22:08:41 +00004127 return implVisitAluOverflow(I, ISD::UADDO);
4128 case Intrinsic::sadd_with_overflow:
4129 return implVisitAluOverflow(I, ISD::SADDO);
4130 case Intrinsic::usub_with_overflow:
4131 return implVisitAluOverflow(I, ISD::USUBO);
4132 case Intrinsic::ssub_with_overflow:
4133 return implVisitAluOverflow(I, ISD::SSUBO);
4134 case Intrinsic::umul_with_overflow:
4135 return implVisitAluOverflow(I, ISD::UMULO);
4136 case Intrinsic::smul_with_overflow:
4137 return implVisitAluOverflow(I, ISD::SMULO);
Bill Wendling5fc7e5c2008-11-21 02:03:52 +00004138
Dan Gohman13aeef92008-09-03 16:12:24 +00004139 case Intrinsic::prefetch: {
4140 SDValue Ops[4];
4141 Ops[0] = getRoot();
4142 Ops[1] = getValue(I.getOperand(1));
4143 Ops[2] = getValue(I.getOperand(2));
4144 Ops[3] = getValue(I.getOperand(3));
4145 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
4146 return 0;
4147 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004148
Dan Gohman13aeef92008-09-03 16:12:24 +00004149 case Intrinsic::memory_barrier: {
4150 SDValue Ops[6];
4151 Ops[0] = getRoot();
4152 for (int x = 1; x < 6; ++x)
4153 Ops[x] = getValue(I.getOperand(x));
4154
4155 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
4156 return 0;
4157 }
4158 case Intrinsic::atomic_cmp_swap: {
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004159 SDValue Root = getRoot();
Dan Gohmanbebba8d2008-12-23 21:37:04 +00004160 SDValue L =
4161 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP,
4162 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4163 Root,
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004164 getValue(I.getOperand(1)),
Dan Gohmanbebba8d2008-12-23 21:37:04 +00004165 getValue(I.getOperand(2)),
4166 getValue(I.getOperand(3)),
4167 I.getOperand(1));
Dan Gohman13aeef92008-09-03 16:12:24 +00004168 setValue(&I, L);
4169 DAG.setRoot(L.getValue(1));
4170 return 0;
4171 }
4172 case Intrinsic::atomic_load_add:
Dan Gohmanbebba8d2008-12-23 21:37:04 +00004173 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
Dan Gohman13aeef92008-09-03 16:12:24 +00004174 case Intrinsic::atomic_load_sub:
Dan Gohmanbebba8d2008-12-23 21:37:04 +00004175 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Dan Gohman13aeef92008-09-03 16:12:24 +00004176 case Intrinsic::atomic_load_or:
Dan Gohmanbebba8d2008-12-23 21:37:04 +00004177 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
Dan Gohman13aeef92008-09-03 16:12:24 +00004178 case Intrinsic::atomic_load_xor:
Dan Gohmanbebba8d2008-12-23 21:37:04 +00004179 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Dan Gohman13aeef92008-09-03 16:12:24 +00004180 case Intrinsic::atomic_load_and:
Dan Gohmanbebba8d2008-12-23 21:37:04 +00004181 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
Dan Gohman13aeef92008-09-03 16:12:24 +00004182 case Intrinsic::atomic_load_nand:
Dan Gohmanbebba8d2008-12-23 21:37:04 +00004183 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Dan Gohman13aeef92008-09-03 16:12:24 +00004184 case Intrinsic::atomic_load_max:
Dan Gohmanbebba8d2008-12-23 21:37:04 +00004185 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
Dan Gohman13aeef92008-09-03 16:12:24 +00004186 case Intrinsic::atomic_load_min:
Dan Gohmanbebba8d2008-12-23 21:37:04 +00004187 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
Dan Gohman13aeef92008-09-03 16:12:24 +00004188 case Intrinsic::atomic_load_umin:
Dan Gohmanbebba8d2008-12-23 21:37:04 +00004189 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
Dan Gohman13aeef92008-09-03 16:12:24 +00004190 case Intrinsic::atomic_load_umax:
Dan Gohmanbebba8d2008-12-23 21:37:04 +00004191 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
Dan Gohman13aeef92008-09-03 16:12:24 +00004192 case Intrinsic::atomic_swap:
Dan Gohmanbebba8d2008-12-23 21:37:04 +00004193 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Dan Gohman13aeef92008-09-03 16:12:24 +00004194 }
4195}
4196
4197
4198void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4199 bool IsTailCall,
4200 MachineBasicBlock *LandingPad) {
4201 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4202 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4203 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4204 unsigned BeginLabel = 0, EndLabel = 0;
4205
4206 TargetLowering::ArgListTy Args;
4207 TargetLowering::ArgListEntry Entry;
4208 Args.reserve(CS.arg_size());
4209 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4210 i != e; ++i) {
4211 SDValue ArgNode = getValue(*i);
4212 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4213
4214 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Pateld222f862008-09-25 21:00:45 +00004215 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4216 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4217 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4218 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4219 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4220 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohman13aeef92008-09-03 16:12:24 +00004221 Entry.Alignment = CS.getParamAlignment(attrInd);
4222 Args.push_back(Entry);
4223 }
4224
4225 if (LandingPad && MMI) {
4226 // Insert a label before the invoke call to mark the try range. This can be
4227 // used to detect deletion of the invoke via the MachineModuleInfo.
4228 BeginLabel = MMI->NextLabelID();
4229 // Both PendingLoads and PendingExports must be flushed here;
4230 // this call might not return.
4231 (void)getRoot();
4232 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
4233 }
4234
4235 std::pair<SDValue,SDValue> Result =
4236 TLI.LowerCallTo(getRoot(), CS.getType(),
Devang Pateld222f862008-09-25 21:00:45 +00004237 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen67cc9b62008-09-26 19:31:26 +00004238 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4239 CS.paramHasAttr(0, Attribute::InReg),
4240 CS.getCallingConv(),
Dan Gohman5ea89a02008-09-16 01:42:28 +00004241 IsTailCall && PerformTailCallOpt,
Dan Gohman13aeef92008-09-03 16:12:24 +00004242 Callee, Args, DAG);
4243 if (CS.getType() != Type::VoidTy)
4244 setValue(CS.getInstruction(), Result.first);
4245 DAG.setRoot(Result.second);
4246
4247 if (LandingPad && MMI) {
4248 // Insert a label at the end of the invoke call to mark the try range. This
4249 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4250 EndLabel = MMI->NextLabelID();
4251 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
4252
4253 // Inform MachineModuleInfo of range.
4254 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4255 }
4256}
4257
4258
4259void SelectionDAGLowering::visitCall(CallInst &I) {
4260 const char *RenameFn = 0;
4261 if (Function *F = I.getCalledFunction()) {
4262 if (F->isDeclaration()) {
4263 if (unsigned IID = F->getIntrinsicID()) {
4264 RenameFn = visitIntrinsicCall(I, IID);
4265 if (!RenameFn)
4266 return;
4267 }
4268 }
4269
4270 // Check for well-known libc/libm calls. If the function is internal, it
4271 // can't be a library call.
4272 unsigned NameLen = F->getNameLen();
Rafael Espindolaa168fc92009-01-15 20:18:42 +00004273 if (!F->hasLocalLinkage() && NameLen) {
Dan Gohman13aeef92008-09-03 16:12:24 +00004274 const char *NameStr = F->getNameStart();
4275 if (NameStr[0] == 'c' &&
4276 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4277 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4278 if (I.getNumOperands() == 3 && // Basic sanity checks.
4279 I.getOperand(1)->getType()->isFloatingPoint() &&
4280 I.getType() == I.getOperand(1)->getType() &&
4281 I.getType() == I.getOperand(2)->getType()) {
4282 SDValue LHS = getValue(I.getOperand(1));
4283 SDValue RHS = getValue(I.getOperand(2));
4284 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
4285 LHS, RHS));
4286 return;
4287 }
4288 } else if (NameStr[0] == 'f' &&
4289 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4290 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4291 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4292 if (I.getNumOperands() == 2 && // Basic sanity checks.
4293 I.getOperand(1)->getType()->isFloatingPoint() &&
4294 I.getType() == I.getOperand(1)->getType()) {
4295 SDValue Tmp = getValue(I.getOperand(1));
4296 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
4297 return;
4298 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004299 } else if (NameStr[0] == 's' &&
Dan Gohman13aeef92008-09-03 16:12:24 +00004300 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4301 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4302 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4303 if (I.getNumOperands() == 2 && // Basic sanity checks.
4304 I.getOperand(1)->getType()->isFloatingPoint() &&
4305 I.getType() == I.getOperand(1)->getType()) {
4306 SDValue Tmp = getValue(I.getOperand(1));
4307 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
4308 return;
4309 }
4310 } else if (NameStr[0] == 'c' &&
4311 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4312 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4313 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4314 if (I.getNumOperands() == 2 && // Basic sanity checks.
4315 I.getOperand(1)->getType()->isFloatingPoint() &&
4316 I.getType() == I.getOperand(1)->getType()) {
4317 SDValue Tmp = getValue(I.getOperand(1));
4318 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
4319 return;
4320 }
4321 }
4322 }
4323 } else if (isa<InlineAsm>(I.getOperand(0))) {
4324 visitInlineAsm(&I);
4325 return;
4326 }
4327
4328 SDValue Callee;
4329 if (!RenameFn)
4330 Callee = getValue(I.getOperand(0));
4331 else
Bill Wendlingfef06052008-09-16 21:48:12 +00004332 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohman13aeef92008-09-03 16:12:24 +00004333
4334 LowerCallTo(&I, Callee, I.isTailCall());
4335}
4336
4337
4338/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004339/// this value and returns the result as a ValueVT value. This uses
Dan Gohman13aeef92008-09-03 16:12:24 +00004340/// Chain/Flag as the input and updates them for the output Chain/Flag.
4341/// If the Flag pointer is NULL, no flag is used.
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004342SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Dan Gohman13aeef92008-09-03 16:12:24 +00004343 SDValue &Chain,
4344 SDValue *Flag) const {
4345 // Assemble the legal parts into the final values.
4346 SmallVector<SDValue, 4> Values(ValueVTs.size());
4347 SmallVector<SDValue, 8> Parts;
4348 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4349 // Copy the legal parts from the registers.
4350 MVT ValueVT = ValueVTs[Value];
4351 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4352 MVT RegisterVT = RegVTs[Value];
4353
4354 Parts.resize(NumRegs);
4355 for (unsigned i = 0; i != NumRegs; ++i) {
4356 SDValue P;
4357 if (Flag == 0)
4358 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
4359 else {
4360 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
4361 *Flag = P.getValue(2);
4362 }
4363 Chain = P.getValue(1);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004364
Dan Gohman13aeef92008-09-03 16:12:24 +00004365 // If the source register was virtual and if we know something about it,
4366 // add an assert node.
4367 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4368 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4369 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4370 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4371 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4372 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004373
Dan Gohman13aeef92008-09-03 16:12:24 +00004374 unsigned RegSize = RegisterVT.getSizeInBits();
4375 unsigned NumSignBits = LOI.NumSignBits;
4376 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004377
Dan Gohman13aeef92008-09-03 16:12:24 +00004378 // FIXME: We capture more information than the dag can represent. For
4379 // now, just use the tightest assertzext/assertsext possible.
4380 bool isSExt = true;
4381 MVT FromVT(MVT::Other);
4382 if (NumSignBits == RegSize)
4383 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4384 else if (NumZeroBits >= RegSize-1)
4385 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4386 else if (NumSignBits > RegSize-8)
4387 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4388 else if (NumZeroBits >= RegSize-9)
4389 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4390 else if (NumSignBits > RegSize-16)
Bill Wendling22922462008-10-19 20:34:04 +00004391 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
Dan Gohman13aeef92008-09-03 16:12:24 +00004392 else if (NumZeroBits >= RegSize-17)
Bill Wendling22922462008-10-19 20:34:04 +00004393 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
Dan Gohman13aeef92008-09-03 16:12:24 +00004394 else if (NumSignBits > RegSize-32)
Bill Wendling22922462008-10-19 20:34:04 +00004395 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
Dan Gohman13aeef92008-09-03 16:12:24 +00004396 else if (NumZeroBits >= RegSize-33)
Bill Wendling22922462008-10-19 20:34:04 +00004397 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004398
Dan Gohman13aeef92008-09-03 16:12:24 +00004399 if (FromVT != MVT::Other) {
4400 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
4401 RegisterVT, P, DAG.getValueType(FromVT));
4402
4403 }
4404 }
4405 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004406
Dan Gohman13aeef92008-09-03 16:12:24 +00004407 Parts[i] = P;
4408 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004409
Dan Gohman13aeef92008-09-03 16:12:24 +00004410 Values[Value] = getCopyFromParts(DAG, Parts.begin(), NumRegs, RegisterVT,
4411 ValueVT);
4412 Part += NumRegs;
4413 Parts.clear();
4414 }
4415
Duncan Sands42d7bb82008-12-01 11:41:29 +00004416 return DAG.getNode(ISD::MERGE_VALUES,
4417 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4418 &Values[0], ValueVTs.size());
Dan Gohman13aeef92008-09-03 16:12:24 +00004419}
4420
4421/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004422/// specified value into the registers specified by this object. This uses
Dan Gohman13aeef92008-09-03 16:12:24 +00004423/// Chain/Flag as the input and updates them for the output Chain/Flag.
4424/// If the Flag pointer is NULL, no flag is used.
4425void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
4426 SDValue &Chain, SDValue *Flag) const {
4427 // Get the list of the values's legal parts.
4428 unsigned NumRegs = Regs.size();
4429 SmallVector<SDValue, 8> Parts(NumRegs);
4430 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4431 MVT ValueVT = ValueVTs[Value];
4432 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4433 MVT RegisterVT = RegVTs[Value];
4434
4435 getCopyToParts(DAG, Val.getValue(Val.getResNo() + Value),
4436 &Parts[Part], NumParts, RegisterVT);
4437 Part += NumParts;
4438 }
4439
4440 // Copy the parts into the registers.
4441 SmallVector<SDValue, 8> Chains(NumRegs);
4442 for (unsigned i = 0; i != NumRegs; ++i) {
4443 SDValue Part;
4444 if (Flag == 0)
4445 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
4446 else {
4447 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
4448 *Flag = Part.getValue(1);
4449 }
4450 Chains[i] = Part.getValue(0);
4451 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004452
Dan Gohman13aeef92008-09-03 16:12:24 +00004453 if (NumRegs == 1 || Flag)
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004454 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
Dan Gohman13aeef92008-09-03 16:12:24 +00004455 // flagged to it. That is the CopyToReg nodes and the user are considered
4456 // a single scheduling unit. If we create a TokenFactor and return it as
4457 // chain, then the TokenFactor is both a predecessor (operand) of the
4458 // user as well as a successor (the TF operands are flagged to the user).
4459 // c1, f1 = CopyToReg
4460 // c2, f2 = CopyToReg
4461 // c3 = TokenFactor c1, c2
4462 // ...
4463 // = op c3, ..., f2
4464 Chain = Chains[NumRegs-1];
4465 else
4466 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
4467}
4468
4469/// AddInlineAsmOperands - Add this value to the specified inlineasm node
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004470/// operand list. This adds the code marker and includes the number of
Dan Gohman13aeef92008-09-03 16:12:24 +00004471/// values added into it.
4472void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
4473 std::vector<SDValue> &Ops) const {
4474 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4475 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
4476 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4477 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4478 MVT RegisterVT = RegVTs[Value];
Chris Lattner01f53542008-10-17 16:21:11 +00004479 for (unsigned i = 0; i != NumRegs; ++i) {
4480 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Dan Gohman13aeef92008-09-03 16:12:24 +00004481 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner01f53542008-10-17 16:21:11 +00004482 }
Dan Gohman13aeef92008-09-03 16:12:24 +00004483 }
4484}
4485
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004486/// isAllocatableRegister - If the specified register is safe to allocate,
Dan Gohman13aeef92008-09-03 16:12:24 +00004487/// i.e. it isn't a stack pointer or some other special register, return the
4488/// register class for the register. Otherwise, return null.
4489static const TargetRegisterClass *
4490isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4491 const TargetLowering &TLI,
4492 const TargetRegisterInfo *TRI) {
4493 MVT FoundVT = MVT::Other;
4494 const TargetRegisterClass *FoundRC = 0;
4495 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4496 E = TRI->regclass_end(); RCI != E; ++RCI) {
4497 MVT ThisVT = MVT::Other;
4498
4499 const TargetRegisterClass *RC = *RCI;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004500 // If none of the the value types for this register class are valid, we
Dan Gohman13aeef92008-09-03 16:12:24 +00004501 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4502 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4503 I != E; ++I) {
4504 if (TLI.isTypeLegal(*I)) {
4505 // If we have already found this register in a different register class,
4506 // choose the one with the largest VT specified. For example, on
4507 // PowerPC, we favor f64 register classes over f32.
4508 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4509 ThisVT = *I;
4510 break;
4511 }
4512 }
4513 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004514
Dan Gohman13aeef92008-09-03 16:12:24 +00004515 if (ThisVT == MVT::Other) continue;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004516
Dan Gohman13aeef92008-09-03 16:12:24 +00004517 // NOTE: This isn't ideal. In particular, this might allocate the
4518 // frame pointer in functions that need it (due to them not being taken
4519 // out of allocation, because a variable sized allocation hasn't been seen
4520 // yet). This is a slight code pessimization, but should still work.
4521 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4522 E = RC->allocation_order_end(MF); I != E; ++I)
4523 if (*I == Reg) {
4524 // We found a matching register class. Keep looking at others in case
4525 // we find one with larger registers that this physreg is also in.
4526 FoundRC = RC;
4527 FoundVT = ThisVT;
4528 break;
4529 }
4530 }
4531 return FoundRC;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004532}
Dan Gohman13aeef92008-09-03 16:12:24 +00004533
4534
4535namespace llvm {
4536/// AsmOperandInfo - This contains information for each constraint that we are
4537/// lowering.
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004538struct VISIBILITY_HIDDEN SDISelAsmOperandInfo :
Daniel Dunbar9dc7b4e2008-09-10 04:16:29 +00004539 public TargetLowering::AsmOperandInfo {
Dan Gohman13aeef92008-09-03 16:12:24 +00004540 /// CallOperand - If this is the result output operand or a clobber
4541 /// this is null, otherwise it is the incoming operand to the CallInst.
4542 /// This gets modified as the asm is processed.
4543 SDValue CallOperand;
4544
4545 /// AssignedRegs - If this is a register or register class operand, this
4546 /// contains the set of register corresponding to the operand.
4547 RegsForValue AssignedRegs;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004548
Dan Gohman13aeef92008-09-03 16:12:24 +00004549 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4550 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4551 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004552
Dan Gohman13aeef92008-09-03 16:12:24 +00004553 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4554 /// busy in OutputRegs/InputRegs.
4555 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004556 std::set<unsigned> &OutputRegs,
Dan Gohman13aeef92008-09-03 16:12:24 +00004557 std::set<unsigned> &InputRegs,
4558 const TargetRegisterInfo &TRI) const {
4559 if (isOutReg) {
4560 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4561 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4562 }
4563 if (isInReg) {
4564 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4565 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4566 }
4567 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004568
Chris Lattner25326882008-10-17 17:05:25 +00004569 /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4570 /// corresponds to. If there is no Value* for this operand, it returns
4571 /// MVT::Other.
4572 MVT getCallOperandValMVT(const TargetLowering &TLI,
4573 const TargetData *TD) const {
4574 if (CallOperandVal == 0) return MVT::Other;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004575
Chris Lattner25326882008-10-17 17:05:25 +00004576 if (isa<BasicBlock>(CallOperandVal))
4577 return TLI.getPointerTy();
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004578
Chris Lattner25326882008-10-17 17:05:25 +00004579 const llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004580
Chris Lattner25326882008-10-17 17:05:25 +00004581 // If this is an indirect operand, the operand is a pointer to the
4582 // accessed type.
4583 if (isIndirect)
4584 OpTy = cast<PointerType>(OpTy)->getElementType();
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004585
Chris Lattner25326882008-10-17 17:05:25 +00004586 // If OpTy is not a single value, it may be a struct/union that we
4587 // can tile with integers.
4588 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4589 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4590 switch (BitSize) {
4591 default: break;
4592 case 1:
4593 case 8:
4594 case 16:
4595 case 32:
4596 case 64:
Chris Lattnerf1aaff62008-10-17 19:59:51 +00004597 case 128:
Chris Lattner25326882008-10-17 17:05:25 +00004598 OpTy = IntegerType::get(BitSize);
4599 break;
4600 }
4601 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004602
Chris Lattner25326882008-10-17 17:05:25 +00004603 return TLI.getValueType(OpTy, true);
4604 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004605
Dan Gohman13aeef92008-09-03 16:12:24 +00004606private:
4607 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4608 /// specified set.
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004609 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
Dan Gohman13aeef92008-09-03 16:12:24 +00004610 const TargetRegisterInfo &TRI) {
4611 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4612 Regs.insert(Reg);
4613 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4614 for (; *Aliases; ++Aliases)
4615 Regs.insert(*Aliases);
4616 }
4617};
4618} // end llvm namespace.
4619
4620
4621/// GetRegistersForValue - Assign registers (virtual or physical) for the
4622/// specified operand. We prefer to assign virtual registers, to allow the
4623/// register allocator handle the assignment process. However, if the asm uses
4624/// features that we can't model on machineinstrs, we have SDISel do the
4625/// allocation. This produces generally horrible, but correct, code.
4626///
4627/// OpInfo describes the operand.
Dan Gohman13aeef92008-09-03 16:12:24 +00004628/// Input and OutputRegs are the set of already allocated physical registers.
4629///
4630void SelectionDAGLowering::
Dale Johannesen47e30e42008-09-24 23:13:09 +00004631GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004632 std::set<unsigned> &OutputRegs,
Dan Gohman13aeef92008-09-03 16:12:24 +00004633 std::set<unsigned> &InputRegs) {
4634 // Compute whether this value requires an input register, an output register,
4635 // or both.
4636 bool isOutReg = false;
4637 bool isInReg = false;
4638 switch (OpInfo.Type) {
4639 case InlineAsm::isOutput:
4640 isOutReg = true;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004641
4642 // If there is an input constraint that matches this, we need to reserve
Dale Johannesen47e30e42008-09-24 23:13:09 +00004643 // the input register so no other inputs allocate to it.
Chris Lattnerefec3242008-10-17 16:47:46 +00004644 isInReg = OpInfo.hasMatchingInput();
Dan Gohman13aeef92008-09-03 16:12:24 +00004645 break;
4646 case InlineAsm::isInput:
4647 isInReg = true;
4648 isOutReg = false;
4649 break;
4650 case InlineAsm::isClobber:
4651 isOutReg = true;
4652 isInReg = true;
4653 break;
4654 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004655
4656
Dan Gohman13aeef92008-09-03 16:12:24 +00004657 MachineFunction &MF = DAG.getMachineFunction();
4658 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004659
Dan Gohman13aeef92008-09-03 16:12:24 +00004660 // If this is a constraint for a single physreg, or a constraint for a
4661 // register class, find it.
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004662 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohman13aeef92008-09-03 16:12:24 +00004663 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4664 OpInfo.ConstraintVT);
4665
4666 unsigned NumRegs = 1;
Chris Lattnerea90c032008-10-21 00:45:36 +00004667 if (OpInfo.ConstraintVT != MVT::Other) {
4668 // If this is a FP input in an integer register (or visa versa) insert a bit
4669 // cast of the input value. More generally, handle any case where the input
4670 // value disagrees with the register class we plan to stick this in.
4671 if (OpInfo.Type == InlineAsm::isInput &&
4672 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4673 // Try to convert to the first MVT that the reg class contains. If the
4674 // types are identical size, use a bitcast to convert (e.g. two differing
4675 // vector types).
4676 MVT RegVT = *PhysReg.second->vt_begin();
4677 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
4678 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4679 OpInfo.CallOperand);
4680 OpInfo.ConstraintVT = RegVT;
4681 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4682 // If the input is a FP value and we want it in FP registers, do a
4683 // bitcast to the corresponding integer type. This turns an f64 value
4684 // into i64, which can be passed with two i32 values on a 32-bit
4685 // machine.
4686 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
4687 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4688 OpInfo.CallOperand);
4689 OpInfo.ConstraintVT = RegVT;
4690 }
4691 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004692
Dan Gohman13aeef92008-09-03 16:12:24 +00004693 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattnerea90c032008-10-21 00:45:36 +00004694 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004695
Dan Gohman13aeef92008-09-03 16:12:24 +00004696 MVT RegVT;
4697 MVT ValueVT = OpInfo.ConstraintVT;
Dan Gohman13aeef92008-09-03 16:12:24 +00004698
4699 // If this is a constraint for a specific physical register, like {r17},
4700 // assign it now.
4701 if (PhysReg.first) {
4702 if (OpInfo.ConstraintVT == MVT::Other)
4703 ValueVT = *PhysReg.second->vt_begin();
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004704
Dan Gohman13aeef92008-09-03 16:12:24 +00004705 // Get the actual register value type. This is important, because the user
4706 // may have asked for (e.g.) the AX register in i32 type. We need to
4707 // remember that AX is actually i16 to get the right extension.
4708 RegVT = *PhysReg.second->vt_begin();
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004709
Dan Gohman13aeef92008-09-03 16:12:24 +00004710 // This is a explicit reference to a physical register.
4711 Regs.push_back(PhysReg.first);
4712
4713 // If this is an expanded reference, add the rest of the regs to Regs.
4714 if (NumRegs != 1) {
4715 TargetRegisterClass::iterator I = PhysReg.second->begin();
4716 for (; *I != PhysReg.first; ++I)
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004717 assert(I != PhysReg.second->end() && "Didn't find reg!");
4718
Dan Gohman13aeef92008-09-03 16:12:24 +00004719 // Already added the first reg.
4720 --NumRegs; ++I;
4721 for (; NumRegs; --NumRegs, ++I) {
4722 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
4723 Regs.push_back(*I);
4724 }
4725 }
4726 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4727 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4728 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4729 return;
4730 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004731
Dan Gohman13aeef92008-09-03 16:12:24 +00004732 // Otherwise, if this was a reference to an LLVM register class, create vregs
4733 // for this reference.
4734 std::vector<unsigned> RegClassRegs;
4735 const TargetRegisterClass *RC = PhysReg.second;
4736 if (RC) {
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004737 // If this is a tied register, our regalloc doesn't know how to maintain
Chris Lattner01f53542008-10-17 16:21:11 +00004738 // the constraint, so we have to pick a register to pin the input/output to.
4739 // If it isn't a matched constraint, go ahead and create vreg and let the
4740 // regalloc do its thing.
Chris Lattnerefec3242008-10-17 16:47:46 +00004741 if (!OpInfo.hasMatchingInput()) {
Dan Gohman13aeef92008-09-03 16:12:24 +00004742 RegVT = *PhysReg.second->vt_begin();
Dan Gohman13aeef92008-09-03 16:12:24 +00004743 if (OpInfo.ConstraintVT == MVT::Other)
4744 ValueVT = RegVT;
4745
4746 // Create the appropriate number of virtual registers.
4747 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4748 for (; NumRegs; --NumRegs)
4749 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004750
Dan Gohman13aeef92008-09-03 16:12:24 +00004751 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4752 return;
4753 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004754
Dan Gohman13aeef92008-09-03 16:12:24 +00004755 // Otherwise, we can't allocate it. Let the code below figure out how to
4756 // maintain these constraints.
4757 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004758
Dan Gohman13aeef92008-09-03 16:12:24 +00004759 } else {
4760 // This is a reference to a register class that doesn't directly correspond
4761 // to an LLVM register class. Allocate NumRegs consecutive, available,
4762 // registers from the class.
4763 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4764 OpInfo.ConstraintVT);
4765 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004766
Dan Gohman13aeef92008-09-03 16:12:24 +00004767 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4768 unsigned NumAllocated = 0;
4769 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4770 unsigned Reg = RegClassRegs[i];
4771 // See if this register is available.
4772 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4773 (isInReg && InputRegs.count(Reg))) { // Already used.
4774 // Make sure we find consecutive registers.
4775 NumAllocated = 0;
4776 continue;
4777 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004778
Dan Gohman13aeef92008-09-03 16:12:24 +00004779 // Check to see if this register is allocatable (i.e. don't give out the
4780 // stack pointer).
4781 if (RC == 0) {
4782 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4783 if (!RC) { // Couldn't allocate this register.
4784 // Reset NumAllocated to make sure we return consecutive registers.
4785 NumAllocated = 0;
4786 continue;
4787 }
4788 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004789
Dan Gohman13aeef92008-09-03 16:12:24 +00004790 // Okay, this register is good, we can use it.
4791 ++NumAllocated;
4792
4793 // If we allocated enough consecutive registers, succeed.
4794 if (NumAllocated == NumRegs) {
4795 unsigned RegStart = (i-NumAllocated)+1;
4796 unsigned RegEnd = i+1;
4797 // Mark all of the allocated registers used.
4798 for (unsigned i = RegStart; i != RegEnd; ++i)
4799 Regs.push_back(RegClassRegs[i]);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004800
4801 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Dan Gohman13aeef92008-09-03 16:12:24 +00004802 OpInfo.ConstraintVT);
4803 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4804 return;
4805 }
4806 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004807
Dan Gohman13aeef92008-09-03 16:12:24 +00004808 // Otherwise, we couldn't allocate enough registers for this.
4809}
4810
Evan Cheng7f250d62008-09-24 00:05:32 +00004811/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
4812/// processed uses a memory 'm' constraint.
4813static bool
4814hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
Dan Gohmana0c429e2009-01-15 16:58:17 +00004815 const TargetLowering &TLI) {
Evan Cheng7f250d62008-09-24 00:05:32 +00004816 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
4817 InlineAsm::ConstraintInfo &CI = CInfos[i];
4818 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
4819 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
4820 if (CType == TargetLowering::C_Memory)
4821 return true;
4822 }
4823 }
4824
4825 return false;
4826}
Dan Gohman13aeef92008-09-03 16:12:24 +00004827
4828/// visitInlineAsm - Handle a call to an InlineAsm object.
4829///
4830void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4831 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4832
4833 /// ConstraintOperands - Information about all of the constraints.
4834 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004835
Dan Gohman13aeef92008-09-03 16:12:24 +00004836 SDValue Chain = getRoot();
4837 SDValue Flag;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004838
Dan Gohman13aeef92008-09-03 16:12:24 +00004839 std::set<unsigned> OutputRegs, InputRegs;
4840
4841 // Do a prepass over the constraints, canonicalizing them, and building up the
4842 // ConstraintOperands list.
4843 std::vector<InlineAsm::ConstraintInfo>
4844 ConstraintInfos = IA->ParseConstraints();
4845
Evan Cheng7f250d62008-09-24 00:05:32 +00004846 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004847
Dan Gohman13aeef92008-09-03 16:12:24 +00004848 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4849 unsigned ResNo = 0; // ResNo - The result number of the next output.
4850 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4851 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4852 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004853
Dan Gohman13aeef92008-09-03 16:12:24 +00004854 MVT OpVT = MVT::Other;
4855
4856 // Compute the value type for each operand.
4857 switch (OpInfo.Type) {
4858 case InlineAsm::isOutput:
4859 // Indirect outputs just consume an argument.
4860 if (OpInfo.isIndirect) {
4861 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4862 break;
4863 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004864
Dan Gohman13aeef92008-09-03 16:12:24 +00004865 // The return value of the call is this value. As such, there is no
4866 // corresponding argument.
4867 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4868 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4869 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4870 } else {
4871 assert(ResNo == 0 && "Asm only has one result!");
4872 OpVT = TLI.getValueType(CS.getType());
4873 }
4874 ++ResNo;
4875 break;
4876 case InlineAsm::isInput:
4877 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4878 break;
4879 case InlineAsm::isClobber:
4880 // Nothing to do.
4881 break;
4882 }
4883
4884 // If this is an input or an indirect output, process the call argument.
4885 // BasicBlocks are labels, currently appearing only in asm's.
4886 if (OpInfo.CallOperandVal) {
Chris Lattner25326882008-10-17 17:05:25 +00004887 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohman13aeef92008-09-03 16:12:24 +00004888 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner25326882008-10-17 17:05:25 +00004889 } else {
Dan Gohman13aeef92008-09-03 16:12:24 +00004890 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohman13aeef92008-09-03 16:12:24 +00004891 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004892
Chris Lattner25326882008-10-17 17:05:25 +00004893 OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
Dan Gohman13aeef92008-09-03 16:12:24 +00004894 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004895
Dan Gohman13aeef92008-09-03 16:12:24 +00004896 OpInfo.ConstraintVT = OpVT;
Chris Lattner75dc7792008-10-18 18:49:30 +00004897 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004898
Chris Lattner75dc7792008-10-18 18:49:30 +00004899 // Second pass over the constraints: compute which constraint option to use
4900 // and assign registers to constraints that want a specific physreg.
4901 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4902 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004903
Chris Lattner75dc7792008-10-18 18:49:30 +00004904 // If this is an output operand with a matching input operand, look up the
Evan Cheng596801f2008-12-16 18:21:39 +00004905 // matching input. If their types mismatch, e.g. one is an integer, the
4906 // other is floating point, or their sizes are different, flag it as an
4907 // error.
Chris Lattner75dc7792008-10-18 18:49:30 +00004908 if (OpInfo.hasMatchingInput()) {
4909 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4910 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Evan Cheng596801f2008-12-16 18:21:39 +00004911 if ((OpInfo.ConstraintVT.isInteger() !=
4912 Input.ConstraintVT.isInteger()) ||
4913 (OpInfo.ConstraintVT.getSizeInBits() !=
4914 Input.ConstraintVT.getSizeInBits())) {
4915 cerr << "Unsupported asm: input constraint with a matching output "
4916 << "constraint of incompatible type!\n";
4917 exit(1);
4918 }
4919 Input.ConstraintVT = OpInfo.ConstraintVT;
Chris Lattner75dc7792008-10-18 18:49:30 +00004920 }
4921 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004922
Dan Gohman13aeef92008-09-03 16:12:24 +00004923 // Compute the constraint code and ConstraintType to use.
Evan Cheng7f250d62008-09-24 00:05:32 +00004924 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohman13aeef92008-09-03 16:12:24 +00004925
Dan Gohman13aeef92008-09-03 16:12:24 +00004926 // If this is a memory input, and if the operand is not indirect, do what we
4927 // need to to provide an address for the memory input.
4928 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4929 !OpInfo.isIndirect) {
4930 assert(OpInfo.Type == InlineAsm::isInput &&
4931 "Can only indirectify direct input operands!");
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004932
Dan Gohman13aeef92008-09-03 16:12:24 +00004933 // Memory operands really want the address of the value. If we don't have
4934 // an indirect input, put it in the constpool if we can, otherwise spill
4935 // it to a stack slot.
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004936
Dan Gohman13aeef92008-09-03 16:12:24 +00004937 // If the operand is a float, integer, or vector constant, spill to a
4938 // constant pool entry to get its address.
4939 Value *OpVal = OpInfo.CallOperandVal;
4940 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4941 isa<ConstantVector>(OpVal)) {
4942 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4943 TLI.getPointerTy());
4944 } else {
4945 // Otherwise, create a stack slot and emit a store to it before the
4946 // asm.
4947 const Type *Ty = OpVal->getType();
Duncan Sandsd68f13b2009-01-12 20:38:59 +00004948 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
Dan Gohman13aeef92008-09-03 16:12:24 +00004949 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4950 MachineFunction &MF = DAG.getMachineFunction();
4951 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4952 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4953 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4954 OpInfo.CallOperand = StackSlot;
4955 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004956
Dan Gohman13aeef92008-09-03 16:12:24 +00004957 // There is no longer a Value* corresponding to this operand.
4958 OpInfo.CallOperandVal = 0;
4959 // It is now an indirect operand.
4960 OpInfo.isIndirect = true;
4961 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004962
Dan Gohman13aeef92008-09-03 16:12:24 +00004963 // If this constraint is for a specific register, allocate it before
4964 // anything else.
4965 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen47e30e42008-09-24 23:13:09 +00004966 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohman13aeef92008-09-03 16:12:24 +00004967 }
4968 ConstraintInfos.clear();
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004969
4970
Dan Gohman13aeef92008-09-03 16:12:24 +00004971 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner01f53542008-10-17 16:21:11 +00004972 // to register class operands.
Dan Gohman13aeef92008-09-03 16:12:24 +00004973 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4974 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004975
Dan Gohman13aeef92008-09-03 16:12:24 +00004976 // C_Register operands have already been allocated, Other/Memory don't need
4977 // to be.
4978 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen47e30e42008-09-24 23:13:09 +00004979 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004980 }
4981
Dan Gohman13aeef92008-09-03 16:12:24 +00004982 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4983 std::vector<SDValue> AsmNodeOperands;
4984 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
4985 AsmNodeOperands.push_back(
Bill Wendlingfef06052008-09-16 21:48:12 +00004986 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004987
4988
Dan Gohman13aeef92008-09-03 16:12:24 +00004989 // Loop over all of the inputs, copying the operand values into the
4990 // appropriate registers and processing the output regs.
4991 RegsForValue RetValRegs;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004992
Dan Gohman13aeef92008-09-03 16:12:24 +00004993 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4994 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00004995
Dan Gohman13aeef92008-09-03 16:12:24 +00004996 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4997 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4998
4999 switch (OpInfo.Type) {
5000 case InlineAsm::isOutput: {
5001 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5002 OpInfo.ConstraintType != TargetLowering::C_Register) {
5003 // Memory output, or 'other' output (e.g. 'X' constraint).
5004 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5005
5006 // Add information to the INLINEASM node to know about this output.
Dale Johannesen94464072008-09-24 01:07:17 +00005007 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5008 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohman13aeef92008-09-03 16:12:24 +00005009 TLI.getPointerTy()));
5010 AsmNodeOperands.push_back(OpInfo.CallOperand);
5011 break;
5012 }
5013
5014 // Otherwise, this is a register or register class output.
5015
5016 // Copy the output from the appropriate register. Find a register that
5017 // we can use.
5018 if (OpInfo.AssignedRegs.Regs.empty()) {
5019 cerr << "Couldn't allocate output reg for constraint '"
5020 << OpInfo.ConstraintCode << "'!\n";
5021 exit(1);
5022 }
5023
5024 // If this is an indirect operand, store through the pointer after the
5025 // asm.
5026 if (OpInfo.isIndirect) {
5027 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5028 OpInfo.CallOperandVal));
5029 } else {
5030 // This is the result value of the call.
5031 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5032 // Concatenate this output onto the outputs list.
5033 RetValRegs.append(OpInfo.AssignedRegs);
5034 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005035
Dan Gohman13aeef92008-09-03 16:12:24 +00005036 // Add information to the INLINEASM node to know that this register is
5037 // set.
Dale Johannesen38438f72008-09-12 17:49:03 +00005038 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5039 6 /* EARLYCLOBBER REGDEF */ :
5040 2 /* REGDEF */ ,
5041 DAG, AsmNodeOperands);
Dan Gohman13aeef92008-09-03 16:12:24 +00005042 break;
5043 }
5044 case InlineAsm::isInput: {
5045 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005046
Chris Lattnerefec3242008-10-17 16:47:46 +00005047 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohman13aeef92008-09-03 16:12:24 +00005048 // If this is required to match an output register we have already set,
5049 // just use its register.
Chris Lattner01f53542008-10-17 16:21:11 +00005050 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005051
Dan Gohman13aeef92008-09-03 16:12:24 +00005052 // Scan until we find the definition we already emitted of this operand.
5053 // When we find it, create a RegsForValue operand.
5054 unsigned CurOp = 2; // The first operand.
5055 for (; OperandNo; --OperandNo) {
5056 // Advance to the next operand.
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005057 unsigned NumOps =
Dan Gohmanfaeb4a32008-09-12 16:56:44 +00005058 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Dan Gohman13aeef92008-09-03 16:12:24 +00005059 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
Dale Johannesen38438f72008-09-12 17:49:03 +00005060 (NumOps & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
Dale Johannesen94464072008-09-24 01:07:17 +00005061 (NumOps & 7) == 4 /*MEM*/) &&
Dan Gohman13aeef92008-09-03 16:12:24 +00005062 "Skipped past definitions?");
5063 CurOp += (NumOps>>3)+1;
5064 }
5065
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005066 unsigned NumOps =
Dan Gohmanfaeb4a32008-09-12 16:56:44 +00005067 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005068 if ((NumOps & 7) == 2 /*REGDEF*/
Dale Johannesen38438f72008-09-12 17:49:03 +00005069 || (NumOps & 7) == 6 /* EARLYCLOBBER REGDEF */) {
Dan Gohman13aeef92008-09-03 16:12:24 +00005070 // Add NumOps>>3 registers to MatchedRegs.
5071 RegsForValue MatchedRegs;
5072 MatchedRegs.TLI = &TLI;
5073 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5074 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
5075 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
5076 unsigned Reg =
5077 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
5078 MatchedRegs.Regs.push_back(Reg);
5079 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005080
5081 // Use the produced MatchedRegs object to
Dan Gohman13aeef92008-09-03 16:12:24 +00005082 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Dale Johannesen94464072008-09-24 01:07:17 +00005083 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Dan Gohman13aeef92008-09-03 16:12:24 +00005084 break;
5085 } else {
Dale Johannesen94464072008-09-24 01:07:17 +00005086 assert(((NumOps & 7) == 4) && "Unknown matching constraint!");
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005087 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
Dan Gohman13aeef92008-09-03 16:12:24 +00005088 // Add information to the INLINEASM node to know about this input.
Dale Johannesenbac3c812008-09-17 21:13:11 +00005089 AsmNodeOperands.push_back(DAG.getTargetConstant(NumOps,
Dan Gohman13aeef92008-09-03 16:12:24 +00005090 TLI.getPointerTy()));
5091 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5092 break;
5093 }
5094 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005095
Dan Gohman13aeef92008-09-03 16:12:24 +00005096 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005097 assert(!OpInfo.isIndirect &&
Dan Gohman13aeef92008-09-03 16:12:24 +00005098 "Don't know how to handle indirect other inputs yet!");
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005099
Dan Gohman13aeef92008-09-03 16:12:24 +00005100 std::vector<SDValue> Ops;
5101 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Cheng7f250d62008-09-24 00:05:32 +00005102 hasMemory, Ops, DAG);
Dan Gohman13aeef92008-09-03 16:12:24 +00005103 if (Ops.empty()) {
5104 cerr << "Invalid operand for inline asm constraint '"
5105 << OpInfo.ConstraintCode << "'!\n";
5106 exit(1);
5107 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005108
Dan Gohman13aeef92008-09-03 16:12:24 +00005109 // Add information to the INLINEASM node to know about this input.
5110 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005111 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohman13aeef92008-09-03 16:12:24 +00005112 TLI.getPointerTy()));
5113 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5114 break;
5115 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5116 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5117 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5118 "Memory operands expect pointer values");
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005119
Dan Gohman13aeef92008-09-03 16:12:24 +00005120 // Add information to the INLINEASM node to know about this input.
Dale Johannesen94464072008-09-24 01:07:17 +00005121 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5122 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohman13aeef92008-09-03 16:12:24 +00005123 TLI.getPointerTy()));
5124 AsmNodeOperands.push_back(InOperandVal);
5125 break;
5126 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005127
Dan Gohman13aeef92008-09-03 16:12:24 +00005128 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5129 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5130 "Unknown constraint type!");
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005131 assert(!OpInfo.isIndirect &&
Dan Gohman13aeef92008-09-03 16:12:24 +00005132 "Don't know how to handle indirect register inputs yet!");
5133
5134 // Copy the input into the appropriate registers.
Evan Cheng0adee052008-09-25 00:14:04 +00005135 if (OpInfo.AssignedRegs.Regs.empty()) {
5136 cerr << "Couldn't allocate output reg for constraint '"
5137 << OpInfo.ConstraintCode << "'!\n";
5138 exit(1);
5139 }
Dan Gohman13aeef92008-09-03 16:12:24 +00005140
5141 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005142
Dale Johannesen94464072008-09-24 01:07:17 +00005143 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/,
5144 DAG, AsmNodeOperands);
Dan Gohman13aeef92008-09-03 16:12:24 +00005145 break;
5146 }
5147 case InlineAsm::isClobber: {
5148 // Add the clobbered value to the operand list, so that the register
5149 // allocator is aware that the physreg got clobbered.
5150 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesenbac3c812008-09-17 21:13:11 +00005151 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
5152 DAG, AsmNodeOperands);
Dan Gohman13aeef92008-09-03 16:12:24 +00005153 break;
5154 }
5155 }
5156 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005157
Dan Gohman13aeef92008-09-03 16:12:24 +00005158 // Finish up input operands.
5159 AsmNodeOperands[0] = Chain;
5160 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005161
5162 Chain = DAG.getNode(ISD::INLINEASM,
Dan Gohman13aeef92008-09-03 16:12:24 +00005163 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
5164 &AsmNodeOperands[0], AsmNodeOperands.size());
5165 Flag = Chain.getValue(1);
5166
5167 // If this asm returns a register value, copy the result from that register
5168 // and set it as the value of the call.
5169 if (!RetValRegs.Regs.empty()) {
5170 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005171
Chris Lattner75dc7792008-10-18 18:49:30 +00005172 // FIXME: Why don't we do this for inline asms with MRVs?
5173 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5174 MVT ResultType = TLI.getValueType(CS.getType());
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005175
Chris Lattner75dc7792008-10-18 18:49:30 +00005176 // If any of the results of the inline asm is a vector, it may have the
5177 // wrong width/num elts. This can happen for register classes that can
5178 // contain multiple different value types. The preg or vreg allocated may
5179 // not have the same VT as was expected. Convert it to the right type
5180 // with bit_convert.
5181 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5182 Val = DAG.getNode(ISD::BIT_CONVERT, ResultType, Val);
Dan Gohman0d946af2008-10-18 01:03:45 +00005183
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005184 } else if (ResultType != Val.getValueType() &&
Chris Lattner75dc7792008-10-18 18:49:30 +00005185 ResultType.isInteger() && Val.getValueType().isInteger()) {
5186 // If a result value was tied to an input value, the computed result may
5187 // have a wider width than the expected result. Extract the relevant
5188 // portion.
5189 Val = DAG.getNode(ISD::TRUNCATE, ResultType, Val);
Dan Gohman0d946af2008-10-18 01:03:45 +00005190 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005191
Chris Lattner75dc7792008-10-18 18:49:30 +00005192 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattnera92185d2008-10-17 17:52:49 +00005193 }
Dan Gohman0d946af2008-10-18 01:03:45 +00005194
Dan Gohman13aeef92008-09-03 16:12:24 +00005195 setValue(CS.getInstruction(), Val);
5196 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005197
Dan Gohman13aeef92008-09-03 16:12:24 +00005198 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005199
Dan Gohman13aeef92008-09-03 16:12:24 +00005200 // Process indirect outputs, first output all of the flagged copies out of
5201 // physregs.
5202 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5203 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5204 Value *Ptr = IndirectStoresToEmit[i].second;
5205 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
5206 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5207 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005208
Dan Gohman13aeef92008-09-03 16:12:24 +00005209 // Emit the non-flagged stores from the physregs.
5210 SmallVector<SDValue, 8> OutChains;
5211 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5212 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
5213 getValue(StoresToEmit[i].second),
5214 StoresToEmit[i].second, 0));
5215 if (!OutChains.empty())
5216 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5217 &OutChains[0], OutChains.size());
5218 DAG.setRoot(Chain);
5219}
5220
5221
5222void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5223 SDValue Src = getValue(I.getOperand(0));
5224
5225 MVT IntPtr = TLI.getPointerTy();
5226
5227 if (IntPtr.bitsLT(Src.getValueType()))
5228 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
5229 else if (IntPtr.bitsGT(Src.getValueType()))
5230 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
5231
5232 // Scale the source by the type size.
Duncan Sandsd68f13b2009-01-12 20:38:59 +00005233 uint64_t ElementSize = TD->getTypePaddedSize(I.getType()->getElementType());
Dan Gohman13aeef92008-09-03 16:12:24 +00005234 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
5235 Src, DAG.getIntPtrConstant(ElementSize));
5236
5237 TargetLowering::ArgListTy Args;
5238 TargetLowering::ArgListEntry Entry;
5239 Entry.Node = Src;
5240 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5241 Args.push_back(Entry);
5242
5243 std::pair<SDValue,SDValue> Result =
Dale Johannesen67cc9b62008-09-26 19:31:26 +00005244 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005245 CallingConv::C, PerformTailCallOpt,
Dale Johannesen67cc9b62008-09-26 19:31:26 +00005246 DAG.getExternalSymbol("malloc", IntPtr),
Dan Gohman5ea89a02008-09-16 01:42:28 +00005247 Args, DAG);
Dan Gohman13aeef92008-09-03 16:12:24 +00005248 setValue(&I, Result.first); // Pointers always fit in registers
5249 DAG.setRoot(Result.second);
5250}
5251
5252void SelectionDAGLowering::visitFree(FreeInst &I) {
5253 TargetLowering::ArgListTy Args;
5254 TargetLowering::ArgListEntry Entry;
5255 Entry.Node = getValue(I.getOperand(0));
5256 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5257 Args.push_back(Entry);
5258 MVT IntPtr = TLI.getPointerTy();
5259 std::pair<SDValue,SDValue> Result =
Dale Johannesen67cc9b62008-09-26 19:31:26 +00005260 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
Dan Gohman5ea89a02008-09-16 01:42:28 +00005261 CallingConv::C, PerformTailCallOpt,
Bill Wendlingfef06052008-09-16 21:48:12 +00005262 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
Dan Gohman13aeef92008-09-03 16:12:24 +00005263 DAG.setRoot(Result.second);
5264}
5265
5266void SelectionDAGLowering::visitVAStart(CallInst &I) {
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005267 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
5268 getValue(I.getOperand(1)),
Dan Gohman13aeef92008-09-03 16:12:24 +00005269 DAG.getSrcValue(I.getOperand(1))));
5270}
5271
5272void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
5273 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
5274 getValue(I.getOperand(0)),
5275 DAG.getSrcValue(I.getOperand(0)));
5276 setValue(&I, V);
5277 DAG.setRoot(V.getValue(1));
5278}
5279
5280void SelectionDAGLowering::visitVAEnd(CallInst &I) {
5281 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005282 getValue(I.getOperand(1)),
Dan Gohman13aeef92008-09-03 16:12:24 +00005283 DAG.getSrcValue(I.getOperand(1))));
5284}
5285
5286void SelectionDAGLowering::visitVACopy(CallInst &I) {
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005287 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
5288 getValue(I.getOperand(1)),
Dan Gohman13aeef92008-09-03 16:12:24 +00005289 getValue(I.getOperand(2)),
5290 DAG.getSrcValue(I.getOperand(1)),
5291 DAG.getSrcValue(I.getOperand(2))));
5292}
5293
5294/// TargetLowering::LowerArguments - This is the default LowerArguments
5295/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005296/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
Dan Gohman13aeef92008-09-03 16:12:24 +00005297/// integrated into SDISel.
5298void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
5299 SmallVectorImpl<SDValue> &ArgValues) {
5300 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5301 SmallVector<SDValue, 3+16> Ops;
5302 Ops.push_back(DAG.getRoot());
5303 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5304 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5305
5306 // Add one result value for each formal argument.
5307 SmallVector<MVT, 16> RetVals;
5308 unsigned j = 1;
5309 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5310 I != E; ++I, ++j) {
5311 SmallVector<MVT, 4> ValueVTs;
5312 ComputeValueVTs(*this, I->getType(), ValueVTs);
5313 for (unsigned Value = 0, NumValues = ValueVTs.size();
5314 Value != NumValues; ++Value) {
5315 MVT VT = ValueVTs[Value];
5316 const Type *ArgTy = VT.getTypeForMVT();
5317 ISD::ArgFlagsTy Flags;
5318 unsigned OriginalAlignment =
5319 getTargetData()->getABITypeAlignment(ArgTy);
5320
Devang Pateld222f862008-09-25 21:00:45 +00005321 if (F.paramHasAttr(j, Attribute::ZExt))
Dan Gohman13aeef92008-09-03 16:12:24 +00005322 Flags.setZExt();
Devang Pateld222f862008-09-25 21:00:45 +00005323 if (F.paramHasAttr(j, Attribute::SExt))
Dan Gohman13aeef92008-09-03 16:12:24 +00005324 Flags.setSExt();
Devang Pateld222f862008-09-25 21:00:45 +00005325 if (F.paramHasAttr(j, Attribute::InReg))
Dan Gohman13aeef92008-09-03 16:12:24 +00005326 Flags.setInReg();
Devang Pateld222f862008-09-25 21:00:45 +00005327 if (F.paramHasAttr(j, Attribute::StructRet))
Dan Gohman13aeef92008-09-03 16:12:24 +00005328 Flags.setSRet();
Devang Pateld222f862008-09-25 21:00:45 +00005329 if (F.paramHasAttr(j, Attribute::ByVal)) {
Dan Gohman13aeef92008-09-03 16:12:24 +00005330 Flags.setByVal();
5331 const PointerType *Ty = cast<PointerType>(I->getType());
5332 const Type *ElementTy = Ty->getElementType();
5333 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsd68f13b2009-01-12 20:38:59 +00005334 unsigned FrameSize = getTargetData()->getTypePaddedSize(ElementTy);
Dan Gohman13aeef92008-09-03 16:12:24 +00005335 // For ByVal, alignment should be passed from FE. BE will guess if
5336 // this info is not there but there are cases it cannot get right.
5337 if (F.getParamAlignment(j))
5338 FrameAlign = F.getParamAlignment(j);
5339 Flags.setByValAlign(FrameAlign);
5340 Flags.setByValSize(FrameSize);
5341 }
Devang Pateld222f862008-09-25 21:00:45 +00005342 if (F.paramHasAttr(j, Attribute::Nest))
Dan Gohman13aeef92008-09-03 16:12:24 +00005343 Flags.setNest();
5344 Flags.setOrigAlign(OriginalAlignment);
5345
5346 MVT RegisterVT = getRegisterType(VT);
5347 unsigned NumRegs = getNumRegisters(VT);
5348 for (unsigned i = 0; i != NumRegs; ++i) {
5349 RetVals.push_back(RegisterVT);
5350 ISD::ArgFlagsTy MyFlags = Flags;
5351 if (NumRegs > 1 && i == 0)
5352 MyFlags.setSplit();
5353 // if it isn't first piece, alignment must be 1
5354 else if (i > 0)
5355 MyFlags.setOrigAlign(1);
5356 Ops.push_back(DAG.getArgFlags(MyFlags));
5357 }
5358 }
5359 }
5360
5361 RetVals.push_back(MVT::Other);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005362
Dan Gohman13aeef92008-09-03 16:12:24 +00005363 // Create the node.
5364 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
5365 DAG.getVTList(&RetVals[0], RetVals.size()),
5366 &Ops[0], Ops.size()).getNode();
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005367
Dan Gohman13aeef92008-09-03 16:12:24 +00005368 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5369 // allows exposing the loads that may be part of the argument access to the
5370 // first DAGCombiner pass.
5371 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005372
Dan Gohman13aeef92008-09-03 16:12:24 +00005373 // The number of results should match up, except that the lowered one may have
5374 // an extra flag result.
5375 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5376 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5377 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5378 && "Lowering produced unexpected number of results!");
5379
5380 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5381 if (Result != TmpRes.getNode() && Result->use_empty()) {
5382 HandleSDNode Dummy(DAG.getRoot());
5383 DAG.RemoveDeadNode(Result);
5384 }
5385
5386 Result = TmpRes.getNode();
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005387
Dan Gohman13aeef92008-09-03 16:12:24 +00005388 unsigned NumArgRegs = Result->getNumValues() - 1;
5389 DAG.setRoot(SDValue(Result, NumArgRegs));
5390
5391 // Set up the return result vector.
5392 unsigned i = 0;
5393 unsigned Idx = 1;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005394 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
Dan Gohman13aeef92008-09-03 16:12:24 +00005395 ++I, ++Idx) {
5396 SmallVector<MVT, 4> ValueVTs;
5397 ComputeValueVTs(*this, I->getType(), ValueVTs);
5398 for (unsigned Value = 0, NumValues = ValueVTs.size();
5399 Value != NumValues; ++Value) {
5400 MVT VT = ValueVTs[Value];
5401 MVT PartVT = getRegisterType(VT);
5402
5403 unsigned NumParts = getNumRegisters(VT);
5404 SmallVector<SDValue, 4> Parts(NumParts);
5405 for (unsigned j = 0; j != NumParts; ++j)
5406 Parts[j] = SDValue(Result, i++);
5407
5408 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Devang Pateld222f862008-09-25 21:00:45 +00005409 if (F.paramHasAttr(Idx, Attribute::SExt))
Dan Gohman13aeef92008-09-03 16:12:24 +00005410 AssertOp = ISD::AssertSext;
Devang Pateld222f862008-09-25 21:00:45 +00005411 else if (F.paramHasAttr(Idx, Attribute::ZExt))
Dan Gohman13aeef92008-09-03 16:12:24 +00005412 AssertOp = ISD::AssertZext;
5413
5414 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
5415 AssertOp));
5416 }
5417 }
5418 assert(i == NumArgRegs && "Argument register count mismatch!");
5419}
5420
5421
5422/// TargetLowering::LowerCallTo - This is the default LowerCallTo
5423/// implementation, which just inserts an ISD::CALL node, which is later custom
5424/// lowered by the target to something concrete. FIXME: When all targets are
5425/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5426std::pair<SDValue, SDValue>
5427TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5428 bool RetSExt, bool RetZExt, bool isVarArg,
Dale Johannesen67cc9b62008-09-26 19:31:26 +00005429 bool isInreg,
Dan Gohman13aeef92008-09-03 16:12:24 +00005430 unsigned CallingConv, bool isTailCall,
5431 SDValue Callee,
5432 ArgListTy &Args, SelectionDAG &DAG) {
Dan Gohman5ea89a02008-09-16 01:42:28 +00005433 assert((!isTailCall || PerformTailCallOpt) &&
5434 "isTailCall set when tail-call optimizations are disabled!");
5435
Dan Gohman13aeef92008-09-03 16:12:24 +00005436 SmallVector<SDValue, 32> Ops;
5437 Ops.push_back(Chain); // Op#0 - Chain
Dan Gohman13aeef92008-09-03 16:12:24 +00005438 Ops.push_back(Callee);
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005439
Dan Gohman13aeef92008-09-03 16:12:24 +00005440 // Handle all of the outgoing arguments.
5441 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5442 SmallVector<MVT, 4> ValueVTs;
5443 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5444 for (unsigned Value = 0, NumValues = ValueVTs.size();
5445 Value != NumValues; ++Value) {
5446 MVT VT = ValueVTs[Value];
5447 const Type *ArgTy = VT.getTypeForMVT();
Chris Lattner75dc7792008-10-18 18:49:30 +00005448 SDValue Op = SDValue(Args[i].Node.getNode(),
5449 Args[i].Node.getResNo() + Value);
Dan Gohman13aeef92008-09-03 16:12:24 +00005450 ISD::ArgFlagsTy Flags;
5451 unsigned OriginalAlignment =
5452 getTargetData()->getABITypeAlignment(ArgTy);
5453
5454 if (Args[i].isZExt)
5455 Flags.setZExt();
5456 if (Args[i].isSExt)
5457 Flags.setSExt();
5458 if (Args[i].isInReg)
5459 Flags.setInReg();
5460 if (Args[i].isSRet)
5461 Flags.setSRet();
5462 if (Args[i].isByVal) {
5463 Flags.setByVal();
5464 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5465 const Type *ElementTy = Ty->getElementType();
5466 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsd68f13b2009-01-12 20:38:59 +00005467 unsigned FrameSize = getTargetData()->getTypePaddedSize(ElementTy);
Dan Gohman13aeef92008-09-03 16:12:24 +00005468 // For ByVal, alignment should come from FE. BE will guess if this
5469 // info is not there but there are cases it cannot get right.
5470 if (Args[i].Alignment)
5471 FrameAlign = Args[i].Alignment;
5472 Flags.setByValAlign(FrameAlign);
5473 Flags.setByValSize(FrameSize);
5474 }
5475 if (Args[i].isNest)
5476 Flags.setNest();
5477 Flags.setOrigAlign(OriginalAlignment);
5478
5479 MVT PartVT = getRegisterType(VT);
5480 unsigned NumParts = getNumRegisters(VT);
5481 SmallVector<SDValue, 4> Parts(NumParts);
5482 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5483
5484 if (Args[i].isSExt)
5485 ExtendKind = ISD::SIGN_EXTEND;
5486 else if (Args[i].isZExt)
5487 ExtendKind = ISD::ZERO_EXTEND;
5488
5489 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5490
5491 for (unsigned i = 0; i != NumParts; ++i) {
5492 // if it isn't first piece, alignment must be 1
5493 ISD::ArgFlagsTy MyFlags = Flags;
5494 if (NumParts > 1 && i == 0)
5495 MyFlags.setSplit();
5496 else if (i != 0)
5497 MyFlags.setOrigAlign(1);
5498
5499 Ops.push_back(Parts[i]);
5500 Ops.push_back(DAG.getArgFlags(MyFlags));
5501 }
5502 }
5503 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005504
Dan Gohman13aeef92008-09-03 16:12:24 +00005505 // Figure out the result value types. We start by making a list of
5506 // the potentially illegal return value types.
5507 SmallVector<MVT, 4> LoweredRetTys;
5508 SmallVector<MVT, 4> RetTys;
5509 ComputeValueVTs(*this, RetTy, RetTys);
5510
5511 // Then we translate that to a list of legal types.
5512 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5513 MVT VT = RetTys[I];
5514 MVT RegisterVT = getRegisterType(VT);
5515 unsigned NumRegs = getNumRegisters(VT);
5516 for (unsigned i = 0; i != NumRegs; ++i)
5517 LoweredRetTys.push_back(RegisterVT);
5518 }
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005519
Dan Gohman13aeef92008-09-03 16:12:24 +00005520 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005521
Dan Gohman13aeef92008-09-03 16:12:24 +00005522 // Create the CALL node.
Dale Johannesen67cc9b62008-09-26 19:31:26 +00005523 SDValue Res = DAG.getCall(CallingConv, isVarArg, isTailCall, isInreg,
Dan Gohman705e3f72008-09-13 01:54:27 +00005524 DAG.getVTList(&LoweredRetTys[0],
5525 LoweredRetTys.size()),
Dale Johannesen67cc9b62008-09-26 19:31:26 +00005526 &Ops[0], Ops.size()
5527 );
Dan Gohman13aeef92008-09-03 16:12:24 +00005528 Chain = Res.getValue(LoweredRetTys.size() - 1);
5529
5530 // Gather up the call result into a single value.
Dan Gohman8542a552008-10-07 00:12:37 +00005531 if (RetTy != Type::VoidTy && !RetTys.empty()) {
Dan Gohman13aeef92008-09-03 16:12:24 +00005532 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5533
5534 if (RetSExt)
5535 AssertOp = ISD::AssertSext;
5536 else if (RetZExt)
5537 AssertOp = ISD::AssertZext;
5538
5539 SmallVector<SDValue, 4> ReturnValues;
5540 unsigned RegNo = 0;
5541 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5542 MVT VT = RetTys[I];
5543 MVT RegisterVT = getRegisterType(VT);
5544 unsigned NumRegs = getNumRegisters(VT);
5545 unsigned RegNoEnd = NumRegs + RegNo;
5546 SmallVector<SDValue, 4> Results;
5547 for (; RegNo != RegNoEnd; ++RegNo)
5548 Results.push_back(Res.getValue(RegNo));
5549 SDValue ReturnValue =
5550 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
5551 AssertOp);
5552 ReturnValues.push_back(ReturnValue);
5553 }
Duncan Sands42d7bb82008-12-01 11:41:29 +00005554 Res = DAG.getNode(ISD::MERGE_VALUES,
5555 DAG.getVTList(&RetTys[0], RetTys.size()),
5556 &ReturnValues[0], ReturnValues.size());
Dan Gohman13aeef92008-09-03 16:12:24 +00005557 }
5558
5559 return std::make_pair(Res, Chain);
5560}
5561
Duncan Sands1497b522009-01-21 09:00:29 +00005562void TargetLowering::LowerOperationWrapper(SDNode *N,
5563 SmallVectorImpl<SDValue> &Results,
5564 SelectionDAG &DAG) {
5565 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptab01fb4d2009-01-21 04:48:39 +00005566 if (Res.getNode())
5567 Results.push_back(Res);
5568}
5569
Dan Gohman13aeef92008-09-03 16:12:24 +00005570SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5571 assert(0 && "LowerOperation not implemented for this target!");
5572 abort();
5573 return SDValue();
5574}
5575
5576
5577void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5578 SDValue Op = getValue(V);
5579 assert((Op.getOpcode() != ISD::CopyFromReg ||
5580 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5581 "Copy from a reg to the same reg!");
5582 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5583
5584 RegsForValue RFV(TLI, Reg, V->getType());
5585 SDValue Chain = DAG.getEntryNode();
5586 RFV.getCopyToRegs(Op, DAG, Chain, 0);
5587 PendingExports.push_back(Chain);
5588}
5589
5590#include "llvm/CodeGen/SelectionDAGISel.h"
5591
5592void SelectionDAGISel::
5593LowerArguments(BasicBlock *LLVMBB) {
5594 // If this is the entry block, emit arguments.
5595 Function &F = *LLVMBB->getParent();
5596 SDValue OldRoot = SDL->DAG.getRoot();
5597 SmallVector<SDValue, 16> Args;
5598 TLI.LowerArguments(F, SDL->DAG, Args);
5599
5600 unsigned a = 0;
5601 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5602 AI != E; ++AI) {
5603 SmallVector<MVT, 4> ValueVTs;
5604 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5605 unsigned NumValues = ValueVTs.size();
5606 if (!AI->use_empty()) {
5607 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues));
5608 // If this argument is live outside of the entry block, insert a copy from
5609 // whereever we got it to the vreg that other BB's will reference it as.
5610 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5611 if (VMI != FuncInfo->ValueMap.end()) {
5612 SDL->CopyValueToVirtualRegister(AI, VMI->second);
5613 }
5614 }
5615 a += NumValues;
5616 }
5617
5618 // Finally, if the target has anything special to do, allow it to do so.
5619 // FIXME: this should insert code into the DAG!
5620 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5621}
5622
5623/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5624/// ensure constants are generated when needed. Remember the virtual registers
5625/// that need to be added to the Machine PHI nodes as input. We cannot just
5626/// directly add them, because expansion might result in multiple MBB's for one
5627/// BB. As such, the start of the BB might correspond to a different MBB than
5628/// the end.
5629///
5630void
5631SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5632 TerminatorInst *TI = LLVMBB->getTerminator();
5633
5634 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5635
5636 // Check successor nodes' PHI nodes that expect a constant to be available
5637 // from this block.
5638 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5639 BasicBlock *SuccBB = TI->getSuccessor(succ);
5640 if (!isa<PHINode>(SuccBB->begin())) continue;
5641 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005642
Dan Gohman13aeef92008-09-03 16:12:24 +00005643 // If this terminator has multiple identical successors (common for
5644 // switches), only handle each succ once.
5645 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005646
Dan Gohman13aeef92008-09-03 16:12:24 +00005647 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5648 PHINode *PN;
5649
5650 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5651 // nodes and Machine PHI nodes, but the incoming operands have not been
5652 // emitted yet.
5653 for (BasicBlock::iterator I = SuccBB->begin();
5654 (PN = dyn_cast<PHINode>(I)); ++I) {
5655 // Ignore dead phi's.
5656 if (PN->use_empty()) continue;
5657
5658 unsigned Reg;
5659 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5660
5661 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5662 unsigned &RegOut = SDL->ConstantsOut[C];
5663 if (RegOut == 0) {
5664 RegOut = FuncInfo->CreateRegForValue(C);
5665 SDL->CopyValueToVirtualRegister(C, RegOut);
5666 }
5667 Reg = RegOut;
5668 } else {
5669 Reg = FuncInfo->ValueMap[PHIOp];
5670 if (Reg == 0) {
5671 assert(isa<AllocaInst>(PHIOp) &&
5672 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5673 "Didn't codegen value into a register!??");
5674 Reg = FuncInfo->CreateRegForValue(PHIOp);
5675 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5676 }
5677 }
5678
5679 // Remember that this register needs to added to the machine PHI node as
5680 // the input for this MBB.
5681 SmallVector<MVT, 4> ValueVTs;
5682 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5683 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5684 MVT VT = ValueVTs[vti];
5685 unsigned NumRegisters = TLI.getNumRegisters(VT);
5686 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5687 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5688 Reg += NumRegisters;
5689 }
5690 }
5691 }
5692 SDL->ConstantsOut.clear();
Dan Gohman13aeef92008-09-03 16:12:24 +00005693}
5694
Dan Gohmanca4857a2008-09-03 23:12:08 +00005695/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5696/// supports legal types, and it emits MachineInstrs directly instead of
5697/// creating SelectionDAG nodes.
5698///
5699bool
5700SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5701 FastISel *F) {
5702 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohman13aeef92008-09-03 16:12:24 +00005703
Dan Gohmanca4857a2008-09-03 23:12:08 +00005704 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5705 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5706
5707 // Check successor nodes' PHI nodes that expect a constant to be available
5708 // from this block.
5709 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5710 BasicBlock *SuccBB = TI->getSuccessor(succ);
5711 if (!isa<PHINode>(SuccBB->begin())) continue;
5712 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005713
Dan Gohmanca4857a2008-09-03 23:12:08 +00005714 // If this terminator has multiple identical successors (common for
5715 // switches), only handle each succ once.
5716 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov26e9aed2009-01-16 06:53:46 +00005717
Dan Gohmanca4857a2008-09-03 23:12:08 +00005718 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5719 PHINode *PN;
5720
5721 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5722 // nodes and Machine PHI nodes, but the incoming operands have not been
5723 // emitted yet.
5724 for (BasicBlock::iterator I = SuccBB->begin();
5725 (PN = dyn_cast<PHINode>(I)); ++I) {
5726 // Ignore dead phi's.
5727 if (PN->use_empty()) continue;
5728
5729 // Only handle legal types. Two interesting things to note here. First,
5730 // by bailing out early, we may leave behind some dead instructions,
5731 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5732 // own moves. Second, this check is necessary becuase FastISel doesn't
5733 // use CreateRegForValue to create registers, so it always creates
5734 // exactly one register for each non-void instruction.
5735 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5736 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
Dan Gohman10999492008-09-10 21:01:31 +00005737 // Promote MVT::i1.
5738 if (VT == MVT::i1)
5739 VT = TLI.getTypeToTransformTo(VT);
5740 else {
5741 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5742 return false;
5743 }
Dan Gohmanca4857a2008-09-03 23:12:08 +00005744 }
5745
5746 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5747
5748 unsigned Reg = F->getRegForValue(PHIOp);
5749 if (Reg == 0) {
5750 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5751 return false;
5752 }
5753 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
5754 }
5755 }
5756
5757 return true;
5758}