blob: c467d9c3cb43ccf5e447bfc34847faa95e25964d [file] [log] [blame]
Dan Gohmanf0cbcd42008-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 Gohman5b229802008-09-04 20:49:27 +000017#include "llvm/ADT/SmallSet.h"
Dan Gohmanf0cbcd42008-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 Wendlingb2a42982008-11-06 02:29:10 +000028#include "llvm/Module.h"
Dan Gohmanf0cbcd42008-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 Wendlingb2a42982008-11-06 02:29:10 +000038#include "llvm/CodeGen/PseudoSourceValue.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000039#include "llvm/CodeGen/SelectionDAG.h"
Devang Patel83489bb2009-01-13 00:35:13 +000040#include "llvm/CodeGen/DwarfWriter.h"
41#include "llvm/Analysis/DebugInfo.h"
Dan Gohmanf0cbcd42008-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 Glushenkov2388a582009-01-16 07:02:28 +000050#include "llvm/Support/CommandLine.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000051#include "llvm/Support/Debug.h"
52#include "llvm/Support/MathExtras.h"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +000053#include "llvm/Support/raw_ostream.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000054#include <algorithm>
55using namespace llvm;
56
Dale Johannesen601d3c02008-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 Gohmanf0cbcd42008-09-03 16:12:24 +000068/// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
Dan Gohman2c91d102009-01-06 22:53:52 +000069/// of insertvalue or extractvalue indices that identify a member, return
Dan Gohmanf0cbcd42008-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 Gohman2c91d102009-01-06 22:53:52 +000090 return CurIndex;
Dan Gohmanf0cbcd42008-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 Gohman2c91d102009-01-06 22:53:52 +0000100 return CurIndex;
Dan Gohmanf0cbcd42008-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 Sandsceb4d1a2009-01-12 20:38:59 +0000131 uint64_t EltSize = TLI.getTargetData()->getTypePaddedSize(EltTy);
Dan Gohmanf0cbcd42008-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 Gohman2a7c6712008-09-03 23:18:39 +0000143namespace llvm {
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000152 ///
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000162
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000173
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000179
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000180 RegsForValue() : TLI(0) {}
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000181
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000182 RegsForValue(const TargetLowering &tli,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000183 const SmallVector<unsigned, 4> &regs,
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000187 const SmallVector<unsigned, 4> &regs,
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000205
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000213
214
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000215 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000216 /// this value and returns the result as a ValueVTs value. This uses
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000223 /// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000228
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000229 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000230 /// operand list. This adds the code marker and includes the number of
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000238/// PHI nodes or outside of the basic block that defines it, or used by a
Dan Gohmanf0cbcd42008-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 Gohman33134c42008-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 Gohmanf0cbcd42008-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 Sandsceb4d1a2009-01-12 20:38:59 +0000294 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000295 unsigned Align =
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000325
Dan Gohmanf0cbcd42008-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 Gohman6448d912008-09-04 15:39:15 +0000334 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Dan Gohmanf0cbcd42008-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 Gohmane9530ec2009-01-15 16:58:17 +0000384 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-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 Sandsd22ec5f2008-10-29 14:22:20 +0000401 MVT HalfVT = ValueVT.isInteger() ?
402 MVT::getIntegerVT(RoundBits/2) :
403 MVT::getFloatingPointVT(RoundBits/2);
404
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000405 if (RoundParts > 2) {
Dan Gohmanf0cbcd42008-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 Sandsd22ec5f2008-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 Gohmanf0cbcd42008-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 Lattner01426e12008-10-21 00:45:36 +0000526static void getCopyToParts(SelectionDAG &DAG, SDValue Val,
527 SDValue *Parts, unsigned NumParts, MVT PartVT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000528 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohmane9530ec2009-01-15 16:58:17 +0000529 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-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 Gohmane9530ec2009-01-15 16:58:17 +0000652 unsigned NumRegs = TLI
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000671 IntermediateVT, Val,
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000781}
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000800
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000803
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000804 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000805 return N = DAG.getConstant(*CI, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000806
807 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
808 return N = DAG.getGlobalAddress(GV, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000809
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000810 if (isa<ConstantPointerNull>(C))
811 return N = DAG.getConstant(0, TLI.getPointerTy());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000812
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000813 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000814 return N = DAG.getConstantFP(*CFP, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000815
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000826
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000862
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000883
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000887
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000896
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000897 unsigned InReg = FuncInfo.ValueMap[V];
898 assert(InReg && "Value not in map!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000899
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000911
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000912 SmallVector<SDValue, 8> NewValues;
913 NewValues.push_back(getControlRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000914 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000915 SmallVector<MVT, 4> ValueVTs;
916 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
Dan Gohman7ea1ca62008-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 Gohmanf0cbcd42008-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 Johannesenc9c6da62008-09-25 20:47:45 +0000925 // at least 32-bit. But this is not necessary for non-C calling
926 // conventions.
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000937
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000938 const Function *F = I.getParent()->getParent();
Devang Patel05988662008-09-25 21:00:45 +0000939 if (F->paramHasAttr(0, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000940 ExtendKind = ISD::SIGN_EXTEND;
Devang Patel05988662008-09-25 21:00:45 +0000941 else if (F->paramHasAttr(0, Attribute::ZExt))
Dan Gohmanf0cbcd42008-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 Johannesenc9c6da62008-09-25 20:47:45 +0000947 // 'inreg' on function refers to return value
948 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Devang Patel05988662008-09-25 21:00:45 +0000949 if (F->paramHasAttr(0, Attribute::InReg))
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000950 Flags.setInReg();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000951 for (unsigned i = 0; i < NumParts; ++i) {
952 NewValues.push_back(Parts[i]);
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000953 NewValues.push_back(DAG.getArgFlags(Flags));
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000967
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000983
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000984 // Is already exported, noop.
985 return FuncInfo.isExportedInst(V);
986 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000987
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +0000997
Dan Gohmanf0cbcd42008-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 Gohman8c1a6ca2008-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 Glushenkov5c1799b2009-01-16 06:53:46 +00001038 else
Dan Gohman8c1a6ca2008-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 Gohmanc2277342008-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 Gohmanf0cbcd42008-09-03 16:12:24 +00001073
Dan Gohmanc2277342008-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 Gohmanf0cbcd42008-09-03 16:12:24 +00001083 ISD::CondCode Condition;
1084 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001085 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001086 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001087 Condition = getFCmpCondCode(FC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001088 } else {
1089 Condition = ISD::SETEQ; // silence warning.
1090 assert(0 && "Unknown compare instruction");
1091 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001092
1093 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001094 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1095 SwitchCases.push_back(CB);
1096 return;
1097 }
Dan Gohmanc2277342008-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 Glushenkov5c1799b2009-01-16 06:53:46 +00001106/// FindMergedConditions - If Cond is an expression like
Dan Gohmanc2277342008-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 Glushenkov5c1799b2009-01-16 06:53:46 +00001114 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohmanc2277342008-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 Gohmanf0cbcd42008-09-03 16:12:24 +00001120 return;
1121 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001122
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +00001128
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +00001137
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001138 // Emit the LHS condition.
1139 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001140
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +00001153
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001154 // Emit the LHS condition.
1155 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001156
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +00001165bool
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001166SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1167 if (Cases.size() != 2) return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001168
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +00001177
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +00001194
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +00001211 // C = seteq
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001212 // cmp D, E
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001213 // F = setle
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +00001223 if (BOp->hasOneUse() &&
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +00001231
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +00001238
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +00001244
Dan Gohmanf0cbcd42008-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 Glushenkov5c1799b2009-01-16 06:53:46 +00001249
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001250 SwitchCases.clear();
1251 }
1252 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001253
Dan Gohmanf0cbcd42008-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 Korobeynikov23218582008-12-23 22:25:27 +00001267
1268 // Build the setcc now.
Dan Gohmanf0cbcd42008-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 Korobeynikov23218582008-12-23 22:25:27 +00001282 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1283 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohmanf0cbcd42008-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 Korobeynikov23218582008-12-23 22:25:27 +00001296
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001297 // Update successor info
1298 CurMBB->addSuccessor(CB.TrueBB);
1299 CurMBB->addSuccessor(CB.FalseBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001300
Dan Gohmanf0cbcd42008-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 Korobeynikov23218582008-12-23 22:25:27 +00001307
Dan Gohmanf0cbcd42008-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 Korobeynikov23218582008-12-23 22:25:27 +00001317
Dan Gohmanf0cbcd42008-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 Korobeynikov23218582008-12-23 22:25:27 +00001324 if (BrCond == getControlRoot())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001325 CurMBB->removeSuccessor(CB.TrueBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001326
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001327 if (CB.FalseBB == NextBlock)
1328 DAG.setRoot(BrCond);
1329 else
Anton Korobeynikov23218582008-12-23 22:25:27 +00001330 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-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));
1344 return;
1345}
1346
1347/// visitJumpTableHeader - This function emits necessary code to produce index
1348/// in the JumpTable from switch case.
1349void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1350 JumpTableHeader &JTH) {
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001351 // Subtract the lowest switch case value from the value being switched on and
1352 // conditional branch to default mbb if the result is greater than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001353 // difference between smallest and largest cases.
1354 SDValue SwitchOp = getValue(JTH.SValue);
1355 MVT VT = SwitchOp.getValueType();
1356 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001357 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001358
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001359 // The SDNode we just created, which holds the value being switched on minus
1360 // the the smallest case value, needs to be copied to a virtual register so it
1361 // can be used as an index into the jump table in a subsequent basic block.
1362 // This value may be smaller or larger than the target's pointer type, and
1363 // therefore require extension or truncating.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001364 if (VT.bitsGT(TLI.getPointerTy()))
1365 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1366 else
1367 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001368
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001369 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1370 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1371 JT.Reg = JumpTableReg;
1372
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001373 // Emit the range check for the jump table, and branch to the default block
1374 // for the switch statement if the value being switched on exceeds the largest
1375 // case in the switch.
Duncan Sands5480c042009-01-01 15:52:00 +00001376 SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB.getValueType()), SUB,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001377 DAG.getConstant(JTH.Last-JTH.First,VT),
1378 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001379
1380 // Set NextBlock to be the MBB immediately after the current one, if any.
1381 // This is used to avoid emitting unnecessary branches to the next block.
1382 MachineBasicBlock *NextBlock = 0;
1383 MachineFunction::iterator BBI = CurMBB;
1384 if (++BBI != CurMBB->getParent()->end())
1385 NextBlock = BBI;
1386
1387 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001388 DAG.getBasicBlock(JT.Default));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001389
1390 if (JT.MBB == NextBlock)
1391 DAG.setRoot(BrCond);
1392 else
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001393 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001394 DAG.getBasicBlock(JT.MBB)));
1395
1396 return;
1397}
1398
1399/// visitBitTestHeader - This function emits necessary code to produce value
1400/// suitable for "bit tests"
1401void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1402 // Subtract the minimum value
1403 SDValue SwitchOp = getValue(B.SValue);
1404 MVT VT = SwitchOp.getValueType();
1405 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001406 DAG.getConstant(B.First, VT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001407
1408 // Check range
Duncan Sands5480c042009-01-01 15:52:00 +00001409 SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB.getValueType()), SUB,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001410 DAG.getConstant(B.Range, VT),
1411 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001412
1413 SDValue ShiftOp;
1414 if (VT.bitsGT(TLI.getShiftAmountTy()))
1415 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1416 else
1417 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1418
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001419 B.Reg = FuncInfo.MakeReg(TLI.getShiftAmountTy());
1420 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), B.Reg, ShiftOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001421
1422 // Set NextBlock to be the MBB immediately after the current one, if any.
1423 // This is used to avoid emitting unnecessary branches to the next block.
1424 MachineBasicBlock *NextBlock = 0;
1425 MachineFunction::iterator BBI = CurMBB;
1426 if (++BBI != CurMBB->getParent()->end())
1427 NextBlock = BBI;
1428
1429 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1430
1431 CurMBB->addSuccessor(B.Default);
1432 CurMBB->addSuccessor(MBB);
1433
1434 SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001435 DAG.getBasicBlock(B.Default));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001436
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001437 if (MBB == NextBlock)
1438 DAG.setRoot(BrRange);
1439 else
1440 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1441 DAG.getBasicBlock(MBB)));
1442
1443 return;
1444}
1445
1446/// visitBitTestCase - this function produces one "bit test"
1447void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1448 unsigned Reg,
1449 BitTestCase &B) {
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001450 // Make desired shift
1451 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), Reg,
1452 TLI.getShiftAmountTy());
1453 SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1454 DAG.getConstant(1, TLI.getPointerTy()),
1455 ShiftOp);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001456
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001457 // Emit bit tests and jumps
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001458 SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001459 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Duncan Sands5480c042009-01-01 15:52:00 +00001460 SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp.getValueType()),
1461 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001462 ISD::SETNE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001463
1464 CurMBB->addSuccessor(B.TargetBB);
1465 CurMBB->addSuccessor(NextMBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001466
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001467 SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001468 AndCmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001469
1470 // Set NextBlock to be the MBB immediately after the current one, if any.
1471 // This is used to avoid emitting unnecessary branches to the next block.
1472 MachineBasicBlock *NextBlock = 0;
1473 MachineFunction::iterator BBI = CurMBB;
1474 if (++BBI != CurMBB->getParent()->end())
1475 NextBlock = BBI;
1476
1477 if (NextMBB == NextBlock)
1478 DAG.setRoot(BrAnd);
1479 else
1480 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1481 DAG.getBasicBlock(NextMBB)));
1482
1483 return;
1484}
1485
1486void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1487 // Retrieve successors.
1488 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1489 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1490
Gabor Greifb67e6b32009-01-15 11:10:44 +00001491 const Value *Callee(I.getCalledValue());
1492 if (isa<InlineAsm>(Callee))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001493 visitInlineAsm(&I);
1494 else
Gabor Greifb67e6b32009-01-15 11:10:44 +00001495 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001496
1497 // If the value of the invoke is used outside of its defining block, make it
1498 // available as a virtual register.
1499 if (!I.use_empty()) {
1500 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1501 if (VMI != FuncInfo.ValueMap.end())
1502 CopyValueToVirtualRegister(&I, VMI->second);
1503 }
1504
1505 // Update successor info
1506 CurMBB->addSuccessor(Return);
1507 CurMBB->addSuccessor(LandingPad);
1508
1509 // Drop into normal successor.
1510 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1511 DAG.getBasicBlock(Return)));
1512}
1513
1514void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1515}
1516
1517/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1518/// small case ranges).
1519bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1520 CaseRecVector& WorkList,
1521 Value* SV,
1522 MachineBasicBlock* Default) {
1523 Case& BackCase = *(CR.Range.second-1);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001524
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001525 // Size is the number of Cases represented by this range.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001526 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001527 if (Size > 3)
Anton Korobeynikov23218582008-12-23 22:25:27 +00001528 return false;
1529
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001530 // Get the MachineFunction which holds the current MBB. This is used when
1531 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001532 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001533
1534 // Figure out which block is immediately after the current one.
1535 MachineBasicBlock *NextBlock = 0;
1536 MachineFunction::iterator BBI = CR.CaseBB;
1537
1538 if (++BBI != CurMBB->getParent()->end())
1539 NextBlock = BBI;
1540
1541 // TODO: If any two of the cases has the same destination, and if one value
1542 // is the same as the other, but has one bit unset that the other has set,
1543 // use bit manipulation to do two compares at once. For example:
1544 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Anton Korobeynikov23218582008-12-23 22:25:27 +00001545
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001546 // Rearrange the case blocks so that the last one falls through if possible.
1547 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1548 // The last case block won't fall through into 'NextBlock' if we emit the
1549 // branches in this order. See if rearranging a case value would help.
1550 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1551 if (I->BB == NextBlock) {
1552 std::swap(*I, BackCase);
1553 break;
1554 }
1555 }
1556 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001557
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001558 // Create a CaseBlock record representing a conditional branch to
1559 // the Case's target mbb if the value being switched on SV is equal
1560 // to C.
1561 MachineBasicBlock *CurBlock = CR.CaseBB;
1562 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1563 MachineBasicBlock *FallThrough;
1564 if (I != E-1) {
1565 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1566 CurMF->insert(BBI, FallThrough);
1567 } else {
1568 // If the last case doesn't match, go to the default block.
1569 FallThrough = Default;
1570 }
1571
1572 Value *RHS, *LHS, *MHS;
1573 ISD::CondCode CC;
1574 if (I->High == I->Low) {
1575 // This is just small small case range :) containing exactly 1 case
1576 CC = ISD::SETEQ;
1577 LHS = SV; RHS = I->High; MHS = NULL;
1578 } else {
1579 CC = ISD::SETLE;
1580 LHS = I->Low; MHS = SV; RHS = I->High;
1581 }
1582 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001583
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001584 // If emitting the first comparison, just call visitSwitchCase to emit the
1585 // code into the current block. Otherwise, push the CaseBlock onto the
1586 // vector to be later processed by SDISel, and insert the node's MBB
1587 // before the next MBB.
1588 if (CurBlock == CurMBB)
1589 visitSwitchCase(CB);
1590 else
1591 SwitchCases.push_back(CB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001592
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001593 CurBlock = FallThrough;
1594 }
1595
1596 return true;
1597}
1598
1599static inline bool areJTsAllowed(const TargetLowering &TLI) {
1600 return !DisableJumpTables &&
1601 (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1602 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1603}
Anton Korobeynikov23218582008-12-23 22:25:27 +00001604
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001605static APInt ComputeRange(const APInt &First, const APInt &Last) {
1606 APInt LastExt(Last), FirstExt(First);
1607 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1608 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1609 return (LastExt - FirstExt + 1ULL);
1610}
1611
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001612/// handleJTSwitchCase - Emit jumptable for current switch case range
1613bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1614 CaseRecVector& WorkList,
1615 Value* SV,
1616 MachineBasicBlock* Default) {
1617 Case& FrontCase = *CR.Range.first;
1618 Case& BackCase = *(CR.Range.second-1);
1619
Anton Korobeynikov23218582008-12-23 22:25:27 +00001620 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1621 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001622
Anton Korobeynikov23218582008-12-23 22:25:27 +00001623 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001624 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1625 I!=E; ++I)
1626 TSize += I->size();
1627
1628 if (!areJTsAllowed(TLI) || TSize <= 3)
1629 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001630
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001631 APInt Range = ComputeRange(First, Last);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001632 double Density = (double)TSize / Range.roundToDouble();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001633 if (Density < 0.4)
1634 return false;
1635
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001636 DEBUG(errs() << "Lowering jump table\n"
1637 << "First entry: " << First << ". Last entry: " << Last << '\n'
1638 << "Range: " << Range
1639 << "Size: " << TSize << ". Density: " << Density << "\n\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001640
1641 // Get the MachineFunction which holds the current MBB. This is used when
1642 // inserting any additional MBBs necessary to represent the switch.
1643 MachineFunction *CurMF = CurMBB->getParent();
1644
1645 // Figure out which block is immediately after the current one.
1646 MachineBasicBlock *NextBlock = 0;
1647 MachineFunction::iterator BBI = CR.CaseBB;
1648
1649 if (++BBI != CurMBB->getParent()->end())
1650 NextBlock = BBI;
1651
1652 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1653
1654 // Create a new basic block to hold the code for loading the address
1655 // of the jump table, and jumping to it. Update successor information;
1656 // we will either branch to the default case for the switch, or the jump
1657 // table.
1658 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1659 CurMF->insert(BBI, JumpTableBB);
1660 CR.CaseBB->addSuccessor(Default);
1661 CR.CaseBB->addSuccessor(JumpTableBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001662
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001663 // Build a vector of destination BBs, corresponding to each target
1664 // of the jump table. If the value of the jump table slot corresponds to
1665 // a case statement, push the case's BB onto the vector, otherwise, push
1666 // the default BB.
1667 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001668 APInt TEI = First;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001669 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001670 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1671 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1672
1673 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001674 DestBBs.push_back(I->BB);
1675 if (TEI==High)
1676 ++I;
1677 } else {
1678 DestBBs.push_back(Default);
1679 }
1680 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001681
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001682 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001683 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1684 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001685 E = DestBBs.end(); I != E; ++I) {
1686 if (!SuccsHandled[(*I)->getNumber()]) {
1687 SuccsHandled[(*I)->getNumber()] = true;
1688 JumpTableBB->addSuccessor(*I);
1689 }
1690 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001691
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001692 // Create a jump table index for this jump table, or return an existing
1693 // one.
1694 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001695
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001696 // Set the jump table information so that we can codegen it as a second
1697 // MachineBasicBlock
1698 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1699 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1700 if (CR.CaseBB == CurMBB)
1701 visitJumpTableHeader(JT, JTH);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001702
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001703 JTCases.push_back(JumpTableBlock(JTH, JT));
1704
1705 return true;
1706}
1707
1708/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1709/// 2 subtrees.
1710bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1711 CaseRecVector& WorkList,
1712 Value* SV,
1713 MachineBasicBlock* Default) {
1714 // Get the MachineFunction which holds the current MBB. This is used when
1715 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001716 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001717
1718 // Figure out which block is immediately after the current one.
1719 MachineBasicBlock *NextBlock = 0;
1720 MachineFunction::iterator BBI = CR.CaseBB;
1721
1722 if (++BBI != CurMBB->getParent()->end())
1723 NextBlock = BBI;
1724
1725 Case& FrontCase = *CR.Range.first;
1726 Case& BackCase = *(CR.Range.second-1);
1727 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1728
1729 // Size is the number of Cases represented by this range.
1730 unsigned Size = CR.Range.second - CR.Range.first;
1731
Anton Korobeynikov23218582008-12-23 22:25:27 +00001732 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1733 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001734 double FMetric = 0;
1735 CaseItr Pivot = CR.Range.first + Size/2;
1736
1737 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1738 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001739 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001740 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1741 I!=E; ++I)
1742 TSize += I->size();
1743
Anton Korobeynikov23218582008-12-23 22:25:27 +00001744 size_t LSize = FrontCase.size();
1745 size_t RSize = TSize-LSize;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001746 DEBUG(errs() << "Selecting best pivot: \n"
1747 << "First: " << First << ", Last: " << Last <<'\n'
1748 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001749 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1750 J!=E; ++I, ++J) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001751 const APInt& LEnd = cast<ConstantInt>(I->High)->getValue();
1752 const APInt& RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001753 APInt Range = ComputeRange(LEnd, RBegin);
1754 assert((Range - 2ULL).isNonNegative() &&
1755 "Invalid case distance");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001756 double LDensity = (double)LSize / (LEnd - First + 1ULL).roundToDouble();
1757 double RDensity = (double)RSize / (Last - RBegin + 1ULL).roundToDouble();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001758 double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001759 // Should always split in some non-trivial place
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001760 DEBUG(errs() <<"=>Step\n"
1761 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1762 << "LDensity: " << LDensity
1763 << ", RDensity: " << RDensity << '\n'
1764 << "Metric: " << Metric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001765 if (FMetric < Metric) {
1766 Pivot = J;
1767 FMetric = Metric;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001768 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001769 }
1770
1771 LSize += J->size();
1772 RSize -= J->size();
1773 }
1774 if (areJTsAllowed(TLI)) {
1775 // If our case is dense we *really* should handle it earlier!
1776 assert((FMetric > 0) && "Should handle dense range earlier!");
1777 } else {
1778 Pivot = CR.Range.first + Size/2;
1779 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001780
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001781 CaseRange LHSR(CR.Range.first, Pivot);
1782 CaseRange RHSR(Pivot, CR.Range.second);
1783 Constant *C = Pivot->Low;
1784 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001785
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001786 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001787 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001788 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001789 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001790 // Pivot's Value, then we can branch directly to the LHS's Target,
1791 // rather than creating a leaf node for it.
1792 if ((LHSR.second - LHSR.first) == 1 &&
1793 LHSR.first->High == CR.GE &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001794 cast<ConstantInt>(C)->getValue() ==
1795 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001796 TrueBB = LHSR.first->BB;
1797 } else {
1798 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1799 CurMF->insert(BBI, TrueBB);
1800 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1801 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001802
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001803 // Similar to the optimization above, if the Value being switched on is
1804 // known to be less than the Constant CR.LT, and the current Case Value
1805 // is CR.LT - 1, then we can branch directly to the target block for
1806 // the current Case Value, rather than emitting a RHS leaf node for it.
1807 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001808 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1809 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001810 FalseBB = RHSR.first->BB;
1811 } else {
1812 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1813 CurMF->insert(BBI, FalseBB);
1814 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1815 }
1816
1817 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001818 // the LHS node if the value being switched on SV is less than C.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001819 // Otherwise, branch to LHS.
1820 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1821
1822 if (CR.CaseBB == CurMBB)
1823 visitSwitchCase(CB);
1824 else
1825 SwitchCases.push_back(CB);
1826
1827 return true;
1828}
1829
1830/// handleBitTestsSwitchCase - if current case range has few destination and
1831/// range span less, than machine word bitwidth, encode case range into series
1832/// of masks and emit bit tests with these masks.
1833bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1834 CaseRecVector& WorkList,
1835 Value* SV,
1836 MachineBasicBlock* Default){
1837 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1838
1839 Case& FrontCase = *CR.Range.first;
1840 Case& BackCase = *(CR.Range.second-1);
1841
1842 // Get the MachineFunction which holds the current MBB. This is used when
1843 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001844 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001845
Anton Korobeynikov23218582008-12-23 22:25:27 +00001846 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001847 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1848 I!=E; ++I) {
1849 // Single case counts one, case range - two.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001850 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001851 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001852
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001853 // Count unique destinations
1854 SmallSet<MachineBasicBlock*, 4> Dests;
1855 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1856 Dests.insert(I->BB);
1857 if (Dests.size() > 3)
1858 // Don't bother the code below, if there are too much unique destinations
1859 return false;
1860 }
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001861 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1862 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001863
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001864 // Compute span of values.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001865 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1866 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001867 APInt cmpRange = maxValue - minValue;
1868
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001869 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1870 << "Low bound: " << minValue << '\n'
1871 << "High bound: " << maxValue << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001872
1873 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001874 (!(Dests.size() == 1 && numCmps >= 3) &&
1875 !(Dests.size() == 2 && numCmps >= 5) &&
1876 !(Dests.size() >= 3 && numCmps >= 6)))
1877 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001878
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001879 DEBUG(errs() << "Emitting bit tests\n");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001880 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1881
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001882 // Optimize the case where all the case values fit in a
1883 // word without having to subtract minValue. In this case,
1884 // we can optimize away the subtraction.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001885 if (minValue.isNonNegative() &&
1886 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1887 cmpRange = maxValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001888 } else {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001889 lowBound = minValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001890 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001891
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001892 CaseBitsVector CasesBits;
1893 unsigned i, count = 0;
1894
1895 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1896 MachineBasicBlock* Dest = I->BB;
1897 for (i = 0; i < count; ++i)
1898 if (Dest == CasesBits[i].BB)
1899 break;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001900
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001901 if (i == count) {
1902 assert((count < 3) && "Too much destinations to test!");
1903 CasesBits.push_back(CaseBits(0, Dest, 0));
1904 count++;
1905 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001906
1907 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1908 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1909
1910 uint64_t lo = (lowValue - lowBound).getZExtValue();
1911 uint64_t hi = (highValue - lowBound).getZExtValue();
1912
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001913 for (uint64_t j = lo; j <= hi; j++) {
1914 CasesBits[i].Mask |= 1ULL << j;
1915 CasesBits[i].Bits++;
1916 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001917
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001918 }
1919 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001920
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001921 BitTestInfo BTC;
1922
1923 // Figure out which block is immediately after the current one.
1924 MachineFunction::iterator BBI = CR.CaseBB;
1925 ++BBI;
1926
1927 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1928
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001929 DEBUG(errs() << "Cases:\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001930 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001931 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
1932 << ", Bits: " << CasesBits[i].Bits
1933 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001934
1935 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1936 CurMF->insert(BBI, CaseBB);
1937 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1938 CaseBB,
1939 CasesBits[i].BB));
1940 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001941
1942 BitTestBlock BTB(lowBound, cmpRange, SV,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001943 -1U, (CR.CaseBB == CurMBB),
1944 CR.CaseBB, Default, BTC);
1945
1946 if (CR.CaseBB == CurMBB)
1947 visitBitTestHeader(BTB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001948
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001949 BitTestCases.push_back(BTB);
1950
1951 return true;
1952}
1953
1954
1955/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov23218582008-12-23 22:25:27 +00001956size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001957 const SwitchInst& SI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001958 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001959
1960 // Start with "simple" cases
Anton Korobeynikov23218582008-12-23 22:25:27 +00001961 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001962 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1963 Cases.push_back(Case(SI.getSuccessorValue(i),
1964 SI.getSuccessorValue(i),
1965 SMBB));
1966 }
1967 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1968
1969 // Merge case into clusters
Anton Korobeynikov23218582008-12-23 22:25:27 +00001970 if (Cases.size() >= 2)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001971 // Must recompute end() each iteration because it may be
1972 // invalidated by erase if we hold on to it
Anton Korobeynikov23218582008-12-23 22:25:27 +00001973 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
1974 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
1975 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001976 MachineBasicBlock* nextBB = J->BB;
1977 MachineBasicBlock* currentBB = I->BB;
1978
1979 // If the two neighboring cases go to the same destination, merge them
1980 // into a single case.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001981 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001982 I->High = J->High;
1983 J = Cases.erase(J);
1984 } else {
1985 I = J++;
1986 }
1987 }
1988
1989 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1990 if (I->Low != I->High)
1991 // A range counts double, since it requires two compares.
1992 ++numCmps;
1993 }
1994
1995 return numCmps;
1996}
1997
Anton Korobeynikov23218582008-12-23 22:25:27 +00001998void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001999 // Figure out which block is immediately after the current one.
2000 MachineBasicBlock *NextBlock = 0;
2001 MachineFunction::iterator BBI = CurMBB;
2002
2003 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2004
2005 // If there is only the default destination, branch to it if it is not the
2006 // next basic block. Otherwise, just fall through.
2007 if (SI.getNumOperands() == 2) {
2008 // Update machine-CFG edges.
2009
2010 // If this is not a fall-through branch, emit the branch.
2011 CurMBB->addSuccessor(Default);
2012 if (Default != NextBlock)
2013 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
2014 DAG.getBasicBlock(Default)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002015 return;
2016 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002017
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002018 // If there are any non-default case statements, create a vector of Cases
2019 // representing each one, and sort the vector so that we can efficiently
2020 // create a binary search tree from them.
2021 CaseVector Cases;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002022 size_t numCmps = Clusterify(Cases, SI);
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002023 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2024 << ". Total compares: " << numCmps << '\n');
Devang Patel8a84e442009-01-05 17:31:22 +00002025 numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002026
2027 // Get the Value to be switched on and default basic blocks, which will be
2028 // inserted into CaseBlock records, representing basic blocks in the binary
2029 // search tree.
2030 Value *SV = SI.getOperand(0);
2031
2032 // Push the initial CaseRec onto the worklist
2033 CaseRecVector WorkList;
2034 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2035
2036 while (!WorkList.empty()) {
2037 // Grab a record representing a case range to process off the worklist
2038 CaseRec CR = WorkList.back();
2039 WorkList.pop_back();
2040
2041 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2042 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002043
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002044 // If the range has few cases (two or less) emit a series of specific
2045 // tests.
2046 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2047 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002048
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002049 // If the switch has more than 5 blocks, and at least 40% dense, and the
2050 // target supports indirect branches, then emit a jump table rather than
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002051 // lowering the switch to a binary tree of conditional branches.
2052 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2053 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002054
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002055 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2056 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2057 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2058 }
2059}
2060
2061
2062void SelectionDAGLowering::visitSub(User &I) {
2063 // -0.0 - X --> fneg
2064 const Type *Ty = I.getType();
2065 if (isa<VectorType>(Ty)) {
2066 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2067 const VectorType *DestTy = cast<VectorType>(I.getType());
2068 const Type *ElTy = DestTy->getElementType();
2069 if (ElTy->isFloatingPoint()) {
2070 unsigned VL = DestTy->getNumElements();
2071 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2072 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2073 if (CV == CNZ) {
2074 SDValue Op2 = getValue(I.getOperand(1));
2075 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2076 return;
2077 }
2078 }
2079 }
2080 }
2081 if (Ty->isFloatingPoint()) {
2082 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2083 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2084 SDValue Op2 = getValue(I.getOperand(1));
2085 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2086 return;
2087 }
2088 }
2089
2090 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2091}
2092
2093void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2094 SDValue Op1 = getValue(I.getOperand(0));
2095 SDValue Op2 = getValue(I.getOperand(1));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002096
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002097 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2098}
2099
2100void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2101 SDValue Op1 = getValue(I.getOperand(0));
2102 SDValue Op2 = getValue(I.getOperand(1));
2103 if (!isa<VectorType>(I.getType())) {
2104 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2105 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2106 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2107 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2108 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002109
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002110 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2111}
2112
2113void SelectionDAGLowering::visitICmp(User &I) {
2114 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2115 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2116 predicate = IC->getPredicate();
2117 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2118 predicate = ICmpInst::Predicate(IC->getPredicate());
2119 SDValue Op1 = getValue(I.getOperand(0));
2120 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002121 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002122 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2123}
2124
2125void SelectionDAGLowering::visitFCmp(User &I) {
2126 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2127 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2128 predicate = FC->getPredicate();
2129 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2130 predicate = FCmpInst::Predicate(FC->getPredicate());
2131 SDValue Op1 = getValue(I.getOperand(0));
2132 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002133 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002134 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2135}
2136
2137void SelectionDAGLowering::visitVICmp(User &I) {
2138 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2139 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2140 predicate = IC->getPredicate();
2141 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2142 predicate = ICmpInst::Predicate(IC->getPredicate());
2143 SDValue Op1 = getValue(I.getOperand(0));
2144 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002145 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002146 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2147}
2148
2149void SelectionDAGLowering::visitVFCmp(User &I) {
2150 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2151 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2152 predicate = FC->getPredicate();
2153 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2154 predicate = FCmpInst::Predicate(FC->getPredicate());
2155 SDValue Op1 = getValue(I.getOperand(0));
2156 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002157 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002158 MVT DestVT = TLI.getValueType(I.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002159
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002160 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2161}
2162
2163void SelectionDAGLowering::visitSelect(User &I) {
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002164 SmallVector<MVT, 4> ValueVTs;
2165 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2166 unsigned NumValues = ValueVTs.size();
2167 if (NumValues != 0) {
2168 SmallVector<SDValue, 4> Values(NumValues);
2169 SDValue Cond = getValue(I.getOperand(0));
2170 SDValue TrueVal = getValue(I.getOperand(1));
2171 SDValue FalseVal = getValue(I.getOperand(2));
2172
2173 for (unsigned i = 0; i != NumValues; ++i)
2174 Values[i] = DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2175 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2176 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2177
Duncan Sandsaaffa052008-12-01 11:41:29 +00002178 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2179 DAG.getVTList(&ValueVTs[0], NumValues),
2180 &Values[0], NumValues));
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002181 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002182}
2183
2184
2185void SelectionDAGLowering::visitTrunc(User &I) {
2186 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2187 SDValue N = getValue(I.getOperand(0));
2188 MVT DestVT = TLI.getValueType(I.getType());
2189 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2190}
2191
2192void SelectionDAGLowering::visitZExt(User &I) {
2193 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2194 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2195 SDValue N = getValue(I.getOperand(0));
2196 MVT DestVT = TLI.getValueType(I.getType());
2197 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2198}
2199
2200void SelectionDAGLowering::visitSExt(User &I) {
2201 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2202 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2203 SDValue N = getValue(I.getOperand(0));
2204 MVT DestVT = TLI.getValueType(I.getType());
2205 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2206}
2207
2208void SelectionDAGLowering::visitFPTrunc(User &I) {
2209 // 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_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2213}
2214
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002215void SelectionDAGLowering::visitFPExt(User &I){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002216 // FPTrunc 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_EXTEND, DestVT, N));
2220}
2221
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002222void SelectionDAGLowering::visitFPToUI(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002223 // FPToUI 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_UINT, DestVT, N));
2227}
2228
2229void SelectionDAGLowering::visitFPToSI(User &I) {
2230 // FPToSI 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::FP_TO_SINT, DestVT, N));
2234}
2235
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002236void SelectionDAGLowering::visitUIToFP(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002237 // UIToFP is never a no-op cast, no need to check
2238 SDValue N = getValue(I.getOperand(0));
2239 MVT DestVT = TLI.getValueType(I.getType());
2240 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2241}
2242
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002243void SelectionDAGLowering::visitSIToFP(User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002244 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002245 SDValue N = getValue(I.getOperand(0));
2246 MVT DestVT = TLI.getValueType(I.getType());
2247 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2248}
2249
2250void SelectionDAGLowering::visitPtrToInt(User &I) {
2251 // What to do depends on the size of the integer and the size of the pointer.
2252 // We can either truncate, zero extend, or no-op, accordingly.
2253 SDValue N = getValue(I.getOperand(0));
2254 MVT SrcVT = N.getValueType();
2255 MVT DestVT = TLI.getValueType(I.getType());
2256 SDValue Result;
2257 if (DestVT.bitsLT(SrcVT))
2258 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002259 else
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002260 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2261 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2262 setValue(&I, Result);
2263}
2264
2265void SelectionDAGLowering::visitIntToPtr(User &I) {
2266 // What to do depends on the size of the integer and the size of the pointer.
2267 // We can either truncate, zero extend, or no-op, accordingly.
2268 SDValue N = getValue(I.getOperand(0));
2269 MVT SrcVT = N.getValueType();
2270 MVT DestVT = TLI.getValueType(I.getType());
2271 if (DestVT.bitsLT(SrcVT))
2272 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002273 else
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002274 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2275 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2276}
2277
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002278void SelectionDAGLowering::visitBitCast(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002279 SDValue N = getValue(I.getOperand(0));
2280 MVT DestVT = TLI.getValueType(I.getType());
2281
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002282 // BitCast assures us that source and destination are the same size so this
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002283 // is either a BIT_CONVERT or a no-op.
2284 if (DestVT != N.getValueType())
2285 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2286 else
2287 setValue(&I, N); // noop cast.
2288}
2289
2290void SelectionDAGLowering::visitInsertElement(User &I) {
2291 SDValue InVec = getValue(I.getOperand(0));
2292 SDValue InVal = getValue(I.getOperand(1));
2293 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2294 getValue(I.getOperand(2)));
2295
2296 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2297 TLI.getValueType(I.getType()),
2298 InVec, InVal, InIdx));
2299}
2300
2301void SelectionDAGLowering::visitExtractElement(User &I) {
2302 SDValue InVec = getValue(I.getOperand(0));
2303 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2304 getValue(I.getOperand(1)));
2305 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2306 TLI.getValueType(I.getType()), InVec, InIdx));
2307}
2308
Mon P Wangaeb06d22008-11-10 04:46:22 +00002309
2310// Utility for visitShuffleVector - Returns true if the mask is mask starting
2311// from SIndx and increasing to the element length (undefs are allowed).
2312static bool SequentialMask(SDValue Mask, unsigned SIndx) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002313 unsigned MaskNumElts = Mask.getNumOperands();
2314 for (unsigned i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002315 if (Mask.getOperand(i).getOpcode() != ISD::UNDEF) {
2316 unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2317 if (Idx != i + SIndx)
2318 return false;
2319 }
2320 }
2321 return true;
2322}
2323
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002324void SelectionDAGLowering::visitShuffleVector(User &I) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002325 SDValue Src1 = getValue(I.getOperand(0));
2326 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002327 SDValue Mask = getValue(I.getOperand(2));
2328
Mon P Wangaeb06d22008-11-10 04:46:22 +00002329 MVT VT = TLI.getValueType(I.getType());
Mon P Wang230e4fa2008-11-21 04:25:21 +00002330 MVT SrcVT = Src1.getValueType();
Mon P Wangc7849c22008-11-16 05:06:27 +00002331 int MaskNumElts = Mask.getNumOperands();
2332 int SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002333
Mon P Wangc7849c22008-11-16 05:06:27 +00002334 if (SrcNumElts == MaskNumElts) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002335 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002336 return;
2337 }
2338
2339 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002340 MVT MaskEltVT = Mask.getValueType().getVectorElementType();
2341
2342 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2343 // Mask is longer than the source vectors and is a multiple of the source
2344 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang230e4fa2008-11-21 04:25:21 +00002345 // lengths match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002346 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2347 // The shuffle is concatenating two vectors together.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002348 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, VT, Src1, Src2));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002349 return;
2350 }
2351
Mon P Wangc7849c22008-11-16 05:06:27 +00002352 // Pad both vectors with undefs to make them the same length as the mask.
2353 unsigned NumConcat = MaskNumElts / SrcNumElts;
2354 SDValue UndefVal = DAG.getNode(ISD::UNDEF, SrcVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002355
Mon P Wang230e4fa2008-11-21 04:25:21 +00002356 SDValue* MOps1 = new SDValue[NumConcat];
2357 SDValue* MOps2 = new SDValue[NumConcat];
2358 MOps1[0] = Src1;
2359 MOps2[0] = Src2;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002360 for (unsigned i = 1; i != NumConcat; ++i) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002361 MOps1[i] = UndefVal;
2362 MOps2[i] = UndefVal;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002363 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002364 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, VT, MOps1, NumConcat);
2365 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, VT, MOps2, NumConcat);
2366
2367 delete [] MOps1;
2368 delete [] MOps2;
2369
Mon P Wangaeb06d22008-11-10 04:46:22 +00002370 // Readjust mask for new input vector length.
2371 SmallVector<SDValue, 8> MappedOps;
Mon P Wangc7849c22008-11-16 05:06:27 +00002372 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002373 if (Mask.getOperand(i).getOpcode() == ISD::UNDEF) {
2374 MappedOps.push_back(Mask.getOperand(i));
2375 } else {
Mon P Wangc7849c22008-11-16 05:06:27 +00002376 int Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2377 if (Idx < SrcNumElts)
2378 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2379 else
2380 MappedOps.push_back(DAG.getConstant(Idx + MaskNumElts - SrcNumElts,
2381 MaskEltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002382 }
2383 }
2384 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2385 &MappedOps[0], MappedOps.size());
2386
Mon P Wang230e4fa2008-11-21 04:25:21 +00002387 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002388 return;
2389 }
2390
Mon P Wangc7849c22008-11-16 05:06:27 +00002391 if (SrcNumElts > MaskNumElts) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002392 // Resulting vector is shorter than the incoming vector.
Mon P Wangc7849c22008-11-16 05:06:27 +00002393 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,0)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002394 // Shuffle extracts 1st vector.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002395 setValue(&I, Src1);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002396 return;
2397 }
2398
Mon P Wangc7849c22008-11-16 05:06:27 +00002399 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,MaskNumElts)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002400 // Shuffle extracts 2nd vector.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002401 setValue(&I, Src2);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002402 return;
2403 }
2404
Mon P Wangc7849c22008-11-16 05:06:27 +00002405 // Analyze the access pattern of the vector to see if we can extract
2406 // two subvectors and do the shuffle. The analysis is done by calculating
2407 // the range of elements the mask access on both vectors.
2408 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2409 int MaxRange[2] = {-1, -1};
2410
2411 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002412 SDValue Arg = Mask.getOperand(i);
2413 if (Arg.getOpcode() != ISD::UNDEF) {
2414 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Mon P Wangc7849c22008-11-16 05:06:27 +00002415 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2416 int Input = 0;
2417 if (Idx >= SrcNumElts) {
2418 Input = 1;
2419 Idx -= SrcNumElts;
2420 }
2421 if (Idx > MaxRange[Input])
2422 MaxRange[Input] = Idx;
2423 if (Idx < MinRange[Input])
2424 MinRange[Input] = Idx;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002425 }
2426 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002427
Mon P Wangc7849c22008-11-16 05:06:27 +00002428 // Check if the access is smaller than the vector size and can we find
2429 // a reasonable extract index.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002430 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
Mon P Wangc7849c22008-11-16 05:06:27 +00002431 int StartIdx[2]; // StartIdx to extract from
2432 for (int Input=0; Input < 2; ++Input) {
2433 if (MinRange[Input] == SrcNumElts+1 && MaxRange[Input] == -1) {
2434 RangeUse[Input] = 0; // Unused
2435 StartIdx[Input] = 0;
2436 } else if (MaxRange[Input] - MinRange[Input] < MaskNumElts) {
2437 // Fits within range but we should see if we can find a good
Mon P Wang230e4fa2008-11-21 04:25:21 +00002438 // start index that is a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002439 if (MaxRange[Input] < MaskNumElts) {
2440 RangeUse[Input] = 1; // Extract from beginning of the vector
2441 StartIdx[Input] = 0;
2442 } else {
2443 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
Mon P Wang6cce3da2008-11-23 04:35:05 +00002444 if (MaxRange[Input] - StartIdx[Input] < MaskNumElts &&
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002445 StartIdx[Input] + MaskNumElts < SrcNumElts)
Mon P Wangc7849c22008-11-16 05:06:27 +00002446 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002447 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002448 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002449 }
2450
2451 if (RangeUse[0] == 0 && RangeUse[0] == 0) {
2452 setValue(&I, DAG.getNode(ISD::UNDEF, VT)); // Vectors are not used.
2453 return;
2454 }
2455 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2456 // Extract appropriate subvector and generate a vector shuffle
2457 for (int Input=0; Input < 2; ++Input) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002458 SDValue& Src = Input == 0 ? Src1 : Src2;
Mon P Wangc7849c22008-11-16 05:06:27 +00002459 if (RangeUse[Input] == 0) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002460 Src = DAG.getNode(ISD::UNDEF, VT);
Mon P Wangc7849c22008-11-16 05:06:27 +00002461 } else {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002462 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, VT, Src,
2463 DAG.getIntPtrConstant(StartIdx[Input]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002464 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002465 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002466 // Calculate new mask.
2467 SmallVector<SDValue, 8> MappedOps;
2468 for (int i = 0; i != MaskNumElts; ++i) {
2469 SDValue Arg = Mask.getOperand(i);
2470 if (Arg.getOpcode() == ISD::UNDEF) {
2471 MappedOps.push_back(Arg);
2472 } else {
2473 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2474 if (Idx < SrcNumElts)
2475 MappedOps.push_back(DAG.getConstant(Idx - StartIdx[0], MaskEltVT));
2476 else {
2477 Idx = Idx - SrcNumElts - StartIdx[1] + MaskNumElts;
2478 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002479 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002480 }
2481 }
2482 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2483 &MappedOps[0], MappedOps.size());
Mon P Wang230e4fa2008-11-21 04:25:21 +00002484 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
Mon P Wangc7849c22008-11-16 05:06:27 +00002485 return;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002486 }
2487 }
2488
Mon P Wangc7849c22008-11-16 05:06:27 +00002489 // We can't use either concat vectors or extract subvectors so fall back to
2490 // replacing the shuffle with extract and build vector.
2491 // to insert and build vector.
Mon P Wangaeb06d22008-11-10 04:46:22 +00002492 MVT EltVT = VT.getVectorElementType();
2493 MVT PtrVT = TLI.getPointerTy();
2494 SmallVector<SDValue,8> Ops;
Mon P Wangc7849c22008-11-16 05:06:27 +00002495 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002496 SDValue Arg = Mask.getOperand(i);
2497 if (Arg.getOpcode() == ISD::UNDEF) {
2498 Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2499 } else {
2500 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Mon P Wangc7849c22008-11-16 05:06:27 +00002501 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2502 if (Idx < SrcNumElts)
Mon P Wang230e4fa2008-11-21 04:25:21 +00002503 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Src1,
Mon P Wangaeb06d22008-11-10 04:46:22 +00002504 DAG.getConstant(Idx, PtrVT)));
2505 else
Mon P Wang230e4fa2008-11-21 04:25:21 +00002506 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Src2,
Mon P Wangc7849c22008-11-16 05:06:27 +00002507 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002508 }
2509 }
2510 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002511}
2512
2513void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2514 const Value *Op0 = I.getOperand(0);
2515 const Value *Op1 = I.getOperand(1);
2516 const Type *AggTy = I.getType();
2517 const Type *ValTy = Op1->getType();
2518 bool IntoUndef = isa<UndefValue>(Op0);
2519 bool FromUndef = isa<UndefValue>(Op1);
2520
2521 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2522 I.idx_begin(), I.idx_end());
2523
2524 SmallVector<MVT, 4> AggValueVTs;
2525 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2526 SmallVector<MVT, 4> ValValueVTs;
2527 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2528
2529 unsigned NumAggValues = AggValueVTs.size();
2530 unsigned NumValValues = ValValueVTs.size();
2531 SmallVector<SDValue, 4> Values(NumAggValues);
2532
2533 SDValue Agg = getValue(Op0);
2534 SDValue Val = getValue(Op1);
2535 unsigned i = 0;
2536 // Copy the beginning value(s) from the original aggregate.
2537 for (; i != LinearIndex; ++i)
2538 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2539 SDValue(Agg.getNode(), Agg.getResNo() + i);
2540 // Copy values from the inserted value(s).
2541 for (; i != LinearIndex + NumValValues; ++i)
2542 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2543 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2544 // Copy remaining value(s) from the original aggregate.
2545 for (; i != NumAggValues; ++i)
2546 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2547 SDValue(Agg.getNode(), Agg.getResNo() + i);
2548
Duncan Sandsaaffa052008-12-01 11:41:29 +00002549 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2550 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2551 &Values[0], NumAggValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002552}
2553
2554void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2555 const Value *Op0 = I.getOperand(0);
2556 const Type *AggTy = Op0->getType();
2557 const Type *ValTy = I.getType();
2558 bool OutOfUndef = isa<UndefValue>(Op0);
2559
2560 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2561 I.idx_begin(), I.idx_end());
2562
2563 SmallVector<MVT, 4> ValValueVTs;
2564 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2565
2566 unsigned NumValValues = ValValueVTs.size();
2567 SmallVector<SDValue, 4> Values(NumValValues);
2568
2569 SDValue Agg = getValue(Op0);
2570 // Copy out the selected value(s).
2571 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2572 Values[i - LinearIndex] =
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002573 OutOfUndef ?
2574 DAG.getNode(ISD::UNDEF,
2575 Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2576 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002577
Duncan Sandsaaffa052008-12-01 11:41:29 +00002578 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2579 DAG.getVTList(&ValValueVTs[0], NumValValues),
2580 &Values[0], NumValValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002581}
2582
2583
2584void SelectionDAGLowering::visitGetElementPtr(User &I) {
2585 SDValue N = getValue(I.getOperand(0));
2586 const Type *Ty = I.getOperand(0)->getType();
2587
2588 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2589 OI != E; ++OI) {
2590 Value *Idx = *OI;
2591 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2592 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2593 if (Field) {
2594 // N = N + Offset
2595 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2596 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2597 DAG.getIntPtrConstant(Offset));
2598 }
2599 Ty = StTy->getElementType(Field);
2600 } else {
2601 Ty = cast<SequentialType>(Ty)->getElementType();
2602
2603 // If this is a constant subscript, handle it quickly.
2604 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2605 if (CI->getZExtValue() == 0) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002606 uint64_t Offs =
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00002607 TD->getTypePaddedSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002608 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2609 DAG.getIntPtrConstant(Offs));
2610 continue;
2611 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002612
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002613 // N = N + Idx * ElementSize;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00002614 uint64_t ElementSize = TD->getTypePaddedSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002615 SDValue IdxN = getValue(Idx);
2616
2617 // If the index is smaller or larger than intptr_t, truncate or extend
2618 // it.
2619 if (IdxN.getValueType().bitsLT(N.getValueType()))
2620 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2621 else if (IdxN.getValueType().bitsGT(N.getValueType()))
2622 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2623
2624 // If this is a multiply by a power of two, turn it into a shl
2625 // immediately. This is a very common case.
2626 if (ElementSize != 1) {
2627 if (isPowerOf2_64(ElementSize)) {
2628 unsigned Amt = Log2_64(ElementSize);
2629 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2630 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2631 } else {
2632 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2633 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2634 }
2635 }
2636
2637 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2638 }
2639 }
2640 setValue(&I, N);
2641}
2642
2643void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2644 // If this is a fixed sized alloca in the entry block of the function,
2645 // allocate it statically on the stack.
2646 if (FuncInfo.StaticAllocaMap.count(&I))
2647 return; // getValue will auto-populate this.
2648
2649 const Type *Ty = I.getAllocatedType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00002650 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002651 unsigned Align =
2652 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2653 I.getAlignment());
2654
2655 SDValue AllocSize = getValue(I.getArraySize());
2656 MVT IntPtr = TLI.getPointerTy();
2657 if (IntPtr.bitsLT(AllocSize.getValueType()))
2658 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2659 else if (IntPtr.bitsGT(AllocSize.getValueType()))
2660 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2661
2662 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2663 DAG.getIntPtrConstant(TySize));
2664
2665 // Handle alignment. If the requested alignment is less than or equal to
2666 // the stack alignment, ignore it. If the size is greater than or equal to
2667 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2668 unsigned StackAlign =
2669 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2670 if (Align <= StackAlign)
2671 Align = 0;
2672
2673 // Round the size of the allocation up to the stack alignment size
2674 // by add SA-1 to the size.
2675 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2676 DAG.getIntPtrConstant(StackAlign-1));
2677 // Mask out the low bits for alignment purposes.
2678 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2679 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2680
2681 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2682 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2683 MVT::Other);
2684 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2685 setValue(&I, DSA);
2686 DAG.setRoot(DSA.getValue(1));
2687
2688 // Inform the Frame Information that we have just allocated a variable-sized
2689 // object.
2690 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2691}
2692
2693void SelectionDAGLowering::visitLoad(LoadInst &I) {
2694 const Value *SV = I.getOperand(0);
2695 SDValue Ptr = getValue(SV);
2696
2697 const Type *Ty = I.getType();
2698 bool isVolatile = I.isVolatile();
2699 unsigned Alignment = I.getAlignment();
2700
2701 SmallVector<MVT, 4> ValueVTs;
2702 SmallVector<uint64_t, 4> Offsets;
2703 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2704 unsigned NumValues = ValueVTs.size();
2705 if (NumValues == 0)
2706 return;
2707
2708 SDValue Root;
2709 bool ConstantMemory = false;
2710 if (I.isVolatile())
2711 // Serialize volatile loads with other side effects.
2712 Root = getRoot();
2713 else if (AA->pointsToConstantMemory(SV)) {
2714 // Do not serialize (non-volatile) loads of constant memory with anything.
2715 Root = DAG.getEntryNode();
2716 ConstantMemory = true;
2717 } else {
2718 // Do not serialize non-volatile loads against each other.
2719 Root = DAG.getRoot();
2720 }
2721
2722 SmallVector<SDValue, 4> Values(NumValues);
2723 SmallVector<SDValue, 4> Chains(NumValues);
2724 MVT PtrVT = Ptr.getValueType();
2725 for (unsigned i = 0; i != NumValues; ++i) {
2726 SDValue L = DAG.getLoad(ValueVTs[i], Root,
2727 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2728 DAG.getConstant(Offsets[i], PtrVT)),
2729 SV, Offsets[i],
2730 isVolatile, Alignment);
2731 Values[i] = L;
2732 Chains[i] = L.getValue(1);
2733 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002734
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002735 if (!ConstantMemory) {
2736 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2737 &Chains[0], NumValues);
2738 if (isVolatile)
2739 DAG.setRoot(Chain);
2740 else
2741 PendingLoads.push_back(Chain);
2742 }
2743
Duncan Sandsaaffa052008-12-01 11:41:29 +00002744 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2745 DAG.getVTList(&ValueVTs[0], NumValues),
2746 &Values[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002747}
2748
2749
2750void SelectionDAGLowering::visitStore(StoreInst &I) {
2751 Value *SrcV = I.getOperand(0);
2752 Value *PtrV = I.getOperand(1);
2753
2754 SmallVector<MVT, 4> ValueVTs;
2755 SmallVector<uint64_t, 4> Offsets;
2756 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2757 unsigned NumValues = ValueVTs.size();
2758 if (NumValues == 0)
2759 return;
2760
2761 // Get the lowered operands. Note that we do this after
2762 // checking if NumResults is zero, because with zero results
2763 // the operands won't have values in the map.
2764 SDValue Src = getValue(SrcV);
2765 SDValue Ptr = getValue(PtrV);
2766
2767 SDValue Root = getRoot();
2768 SmallVector<SDValue, 4> Chains(NumValues);
2769 MVT PtrVT = Ptr.getValueType();
2770 bool isVolatile = I.isVolatile();
2771 unsigned Alignment = I.getAlignment();
2772 for (unsigned i = 0; i != NumValues; ++i)
2773 Chains[i] = DAG.getStore(Root, SDValue(Src.getNode(), Src.getResNo() + i),
2774 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2775 DAG.getConstant(Offsets[i], PtrVT)),
2776 PtrV, Offsets[i],
2777 isVolatile, Alignment);
2778
2779 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2780}
2781
2782/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2783/// node.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002784void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002785 unsigned Intrinsic) {
2786 bool HasChain = !I.doesNotAccessMemory();
2787 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2788
2789 // Build the operand list.
2790 SmallVector<SDValue, 8> Ops;
2791 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2792 if (OnlyLoad) {
2793 // We don't need to serialize loads against other loads.
2794 Ops.push_back(DAG.getRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002795 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002796 Ops.push_back(getRoot());
2797 }
2798 }
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002799
2800 // Info is set by getTgtMemInstrinsic
2801 TargetLowering::IntrinsicInfo Info;
2802 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2803
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002804 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002805 if (!IsTgtIntrinsic)
2806 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002807
2808 // Add all operands of the call to the operand list.
2809 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2810 SDValue Op = getValue(I.getOperand(i));
2811 assert(TLI.isTypeLegal(Op.getValueType()) &&
2812 "Intrinsic uses a non-legal type?");
2813 Ops.push_back(Op);
2814 }
2815
2816 std::vector<MVT> VTs;
2817 if (I.getType() != Type::VoidTy) {
2818 MVT VT = TLI.getValueType(I.getType());
2819 if (VT.isVector()) {
2820 const VectorType *DestTy = cast<VectorType>(I.getType());
2821 MVT EltVT = TLI.getValueType(DestTy->getElementType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002822
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002823 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2824 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2825 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002826
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002827 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2828 VTs.push_back(VT);
2829 }
2830 if (HasChain)
2831 VTs.push_back(MVT::Other);
2832
2833 const MVT *VTList = DAG.getNodeValueTypes(VTs);
2834
2835 // Create the node.
2836 SDValue Result;
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002837 if (IsTgtIntrinsic) {
2838 // This is target intrinsic that touches memory
2839 Result = DAG.getMemIntrinsicNode(Info.opc, VTList, VTs.size(),
2840 &Ops[0], Ops.size(),
2841 Info.memVT, Info.ptrVal, Info.offset,
2842 Info.align, Info.vol,
2843 Info.readMem, Info.writeMem);
2844 }
2845 else if (!HasChain)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002846 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2847 &Ops[0], Ops.size());
2848 else if (I.getType() != Type::VoidTy)
2849 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2850 &Ops[0], Ops.size());
2851 else
2852 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2853 &Ops[0], Ops.size());
2854
2855 if (HasChain) {
2856 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2857 if (OnlyLoad)
2858 PendingLoads.push_back(Chain);
2859 else
2860 DAG.setRoot(Chain);
2861 }
2862 if (I.getType() != Type::VoidTy) {
2863 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2864 MVT VT = TLI.getValueType(PTy);
2865 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002866 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002867 setValue(&I, Result);
2868 }
2869}
2870
2871/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2872static GlobalVariable *ExtractTypeInfo(Value *V) {
2873 V = V->stripPointerCasts();
2874 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2875 assert ((GV || isa<ConstantPointerNull>(V)) &&
2876 "TypeInfo must be a global variable or NULL");
2877 return GV;
2878}
2879
2880namespace llvm {
2881
2882/// AddCatchInfo - Extract the personality and type infos from an eh.selector
2883/// call, and add them to the specified machine basic block.
2884void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2885 MachineBasicBlock *MBB) {
2886 // Inform the MachineModuleInfo of the personality for this landing pad.
2887 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2888 assert(CE->getOpcode() == Instruction::BitCast &&
2889 isa<Function>(CE->getOperand(0)) &&
2890 "Personality should be a function");
2891 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2892
2893 // Gather all the type infos for this landing pad and pass them along to
2894 // MachineModuleInfo.
2895 std::vector<GlobalVariable *> TyInfo;
2896 unsigned N = I.getNumOperands();
2897
2898 for (unsigned i = N - 1; i > 2; --i) {
2899 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2900 unsigned FilterLength = CI->getZExtValue();
2901 unsigned FirstCatch = i + FilterLength + !FilterLength;
2902 assert (FirstCatch <= N && "Invalid filter length");
2903
2904 if (FirstCatch < N) {
2905 TyInfo.reserve(N - FirstCatch);
2906 for (unsigned j = FirstCatch; j < N; ++j)
2907 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2908 MMI->addCatchTypeInfo(MBB, TyInfo);
2909 TyInfo.clear();
2910 }
2911
2912 if (!FilterLength) {
2913 // Cleanup.
2914 MMI->addCleanup(MBB);
2915 } else {
2916 // Filter.
2917 TyInfo.reserve(FilterLength - 1);
2918 for (unsigned j = i + 1; j < FirstCatch; ++j)
2919 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2920 MMI->addFilterTypeInfo(MBB, TyInfo);
2921 TyInfo.clear();
2922 }
2923
2924 N = i;
2925 }
2926 }
2927
2928 if (N > 3) {
2929 TyInfo.reserve(N - 3);
2930 for (unsigned j = 3; j < N; ++j)
2931 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2932 MMI->addCatchTypeInfo(MBB, TyInfo);
2933 }
2934}
2935
2936}
2937
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002938/// GetSignificand - Get the significand and build it into a floating-point
2939/// number with exponent of 1:
2940///
2941/// Op = (Op & 0x007fffff) | 0x3f800000;
2942///
2943/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002944static SDValue
2945GetSignificand(SelectionDAG &DAG, SDValue Op) {
Bill Wendlinge9a72862009-01-20 21:17:57 +00002946 SDValue t1 = DAG.getNode(ISD::AND, MVT::i32, Op,
2947 DAG.getConstant(0x007fffff, MVT::i32));
2948 SDValue t2 = DAG.getNode(ISD::OR, MVT::i32, t1,
2949 DAG.getConstant(0x3f800000, MVT::i32));
2950 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00002951}
2952
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002953/// GetExponent - Get the exponent:
2954///
Bill Wendlinge9a72862009-01-20 21:17:57 +00002955/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002956///
2957/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002958static SDValue
Bill Wendling6c533342009-01-20 06:10:42 +00002959GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI) {
Bill Wendlinge9a72862009-01-20 21:17:57 +00002960 SDValue t0 = DAG.getNode(ISD::AND, MVT::i32, Op,
2961 DAG.getConstant(0x7f800000, MVT::i32));
2962 SDValue t1 = DAG.getNode(ISD::SRL, MVT::i32, t0,
2963 DAG.getConstant(23, TLI.getShiftAmountTy()));
2964 SDValue t2 = DAG.getNode(ISD::SUB, MVT::i32, t1,
2965 DAG.getConstant(127, MVT::i32));
2966 return DAG.getNode(ISD::SINT_TO_FP, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00002967}
2968
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002969/// getF32Constant - Get 32-bit floating point constant.
2970static SDValue
2971getF32Constant(SelectionDAG &DAG, unsigned Flt) {
2972 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
2973}
2974
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002975/// Inlined utility function to implement binary input atomic intrinsics for
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002976/// visitIntrinsicCall: I is a call instruction
2977/// Op is the associated NodeType for I
2978const char *
2979SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002980 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00002981 SDValue L =
2982 DAG.getAtomic(Op, getValue(I.getOperand(2)).getValueType().getSimpleVT(),
2983 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002984 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00002985 getValue(I.getOperand(2)),
2986 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002987 setValue(&I, L);
2988 DAG.setRoot(L.getValue(1));
2989 return 0;
2990}
2991
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002992// implVisitAluOverflow - Lower arithmetic overflow instrinsics.
Bill Wendling74c37652008-12-09 22:08:41 +00002993const char *
2994SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002995 SDValue Op1 = getValue(I.getOperand(1));
2996 SDValue Op2 = getValue(I.getOperand(2));
Bill Wendling74c37652008-12-09 22:08:41 +00002997
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002998 MVT ValueVTs[] = { Op1.getValueType(), MVT::i1 };
2999 SDValue Ops[] = { Op1, Op2 };
Bill Wendling74c37652008-12-09 22:08:41 +00003000
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003001 SDValue Result = DAG.getNode(Op, DAG.getVTList(&ValueVTs[0], 2), &Ops[0], 2);
Bill Wendling74c37652008-12-09 22:08:41 +00003002
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003003 setValue(&I, Result);
3004 return 0;
3005}
Bill Wendling74c37652008-12-09 22:08:41 +00003006
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003007/// visitExp - Lower an exp intrinsic. Handles the special sequences for
3008/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003009void
3010SelectionDAGLowering::visitExp(CallInst &I) {
3011 SDValue result;
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003012
3013 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3014 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3015 SDValue Op = getValue(I.getOperand(1));
3016
3017 // Put the exponent in the right bit position for later addition to the
3018 // final result:
3019 //
3020 // #define LOG2OFe 1.4426950f
3021 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3022 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003023 getF32Constant(DAG, 0x3fb8aa3b));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003024 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3025
3026 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3027 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3028 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3029
3030 // IntegerPartOfX <<= 23;
3031 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
Bill Wendling6c533342009-01-20 06:10:42 +00003032 DAG.getConstant(23, TLI.getShiftAmountTy()));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003033
3034 if (LimitFloatPrecision <= 6) {
3035 // For floating-point precision of 6:
3036 //
3037 // TwoToFractionalPartOfX =
3038 // 0.997535578f +
3039 // (0.735607626f + 0.252464424f * x) * x;
3040 //
3041 // error 0.0144103317, which is 6 bits
3042 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003043 getF32Constant(DAG, 0x3e814304));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003044 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003045 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003046 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3047 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003048 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003049 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3050
3051 // Add the exponent into the result in integer domain.
3052 SDValue t6 = DAG.getNode(ISD::ADD, MVT::i32,
3053 TwoToFracPartOfX, IntegerPartOfX);
3054
3055 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t6);
3056 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3057 // For floating-point precision of 12:
3058 //
3059 // TwoToFractionalPartOfX =
3060 // 0.999892986f +
3061 // (0.696457318f +
3062 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3063 //
3064 // 0.000107046256 error, which is 13 to 14 bits
3065 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003066 getF32Constant(DAG, 0x3da235e3));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003067 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003068 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003069 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3070 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003071 getF32Constant(DAG, 0x3f324b07));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003072 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3073 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003074 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003075 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3076
3077 // Add the exponent into the result in integer domain.
3078 SDValue t8 = DAG.getNode(ISD::ADD, MVT::i32,
3079 TwoToFracPartOfX, IntegerPartOfX);
3080
3081 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t8);
3082 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3083 // For floating-point precision of 18:
3084 //
3085 // TwoToFractionalPartOfX =
3086 // 0.999999982f +
3087 // (0.693148872f +
3088 // (0.240227044f +
3089 // (0.554906021e-1f +
3090 // (0.961591928e-2f +
3091 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3092 //
3093 // error 2.47208000*10^(-7), which is better than 18 bits
3094 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003095 getF32Constant(DAG, 0x3924b03e));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003096 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003097 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003098 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3099 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003100 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003101 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3102 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003103 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003104 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3105 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003106 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003107 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3108 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003109 getF32Constant(DAG, 0x3f317234));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003110 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3111 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003112 getF32Constant(DAG, 0x3f800000));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003113 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3114
3115 // Add the exponent into the result in integer domain.
3116 SDValue t14 = DAG.getNode(ISD::ADD, MVT::i32,
3117 TwoToFracPartOfX, IntegerPartOfX);
3118
3119 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t14);
3120 }
3121 } else {
3122 // No special expansion.
3123 result = DAG.getNode(ISD::FEXP,
3124 getValue(I.getOperand(1)).getValueType(),
3125 getValue(I.getOperand(1)));
3126 }
3127
Dale Johannesen59e577f2008-09-05 18:38:42 +00003128 setValue(&I, result);
3129}
3130
Bill Wendling39150252008-09-09 20:39:27 +00003131/// visitLog - Lower a log intrinsic. Handles the special sequences for
3132/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003133void
3134SelectionDAGLowering::visitLog(CallInst &I) {
3135 SDValue result;
Bill Wendling39150252008-09-09 20:39:27 +00003136
3137 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3138 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3139 SDValue Op = getValue(I.getOperand(1));
3140 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3141
3142 // Scale the exponent by log(2) [0.69314718f].
Bill Wendling6c533342009-01-20 06:10:42 +00003143 SDValue Exp = GetExponent(DAG, Op1, TLI);
Bill Wendling39150252008-09-09 20:39:27 +00003144 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003145 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003146
3147 // Get the significand and build it into a floating-point number with
3148 // exponent of 1.
3149 SDValue X = GetSignificand(DAG, Op1);
3150
3151 if (LimitFloatPrecision <= 6) {
3152 // For floating-point precision of 6:
3153 //
3154 // LogofMantissa =
3155 // -1.1609546f +
3156 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003157 //
Bill Wendling39150252008-09-09 20:39:27 +00003158 // error 0.0034276066, which is better than 8 bits
3159 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003160 getF32Constant(DAG, 0xbe74c456));
Bill Wendling39150252008-09-09 20:39:27 +00003161 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003162 getF32Constant(DAG, 0x3fb3a2b1));
Bill Wendling39150252008-09-09 20:39:27 +00003163 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3164 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003165 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00003166
3167 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3168 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3169 // For floating-point precision of 12:
3170 //
3171 // LogOfMantissa =
3172 // -1.7417939f +
3173 // (2.8212026f +
3174 // (-1.4699568f +
3175 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3176 //
3177 // error 0.000061011436, which is 14 bits
3178 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003179 getF32Constant(DAG, 0xbd67b6d6));
Bill Wendling39150252008-09-09 20:39:27 +00003180 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003181 getF32Constant(DAG, 0x3ee4f4b8));
Bill Wendling39150252008-09-09 20:39:27 +00003182 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3183 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003184 getF32Constant(DAG, 0x3fbc278b));
Bill Wendling39150252008-09-09 20:39:27 +00003185 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3186 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003187 getF32Constant(DAG, 0x40348e95));
Bill Wendling39150252008-09-09 20:39:27 +00003188 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3189 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003190 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00003191
3192 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3193 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3194 // For floating-point precision of 18:
3195 //
3196 // LogOfMantissa =
3197 // -2.1072184f +
3198 // (4.2372794f +
3199 // (-3.7029485f +
3200 // (2.2781945f +
3201 // (-0.87823314f +
3202 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3203 //
3204 // error 0.0000023660568, which is better than 18 bits
3205 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003206 getF32Constant(DAG, 0xbc91e5ac));
Bill Wendling39150252008-09-09 20:39:27 +00003207 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003208 getF32Constant(DAG, 0x3e4350aa));
Bill Wendling39150252008-09-09 20:39:27 +00003209 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3210 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003211 getF32Constant(DAG, 0x3f60d3e3));
Bill Wendling39150252008-09-09 20:39:27 +00003212 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3213 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003214 getF32Constant(DAG, 0x4011cdf0));
Bill Wendling39150252008-09-09 20:39:27 +00003215 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3216 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003217 getF32Constant(DAG, 0x406cfd1c));
Bill Wendling39150252008-09-09 20:39:27 +00003218 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3219 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003220 getF32Constant(DAG, 0x408797cb));
Bill Wendling39150252008-09-09 20:39:27 +00003221 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3222 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003223 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003224
3225 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3226 }
3227 } else {
3228 // No special expansion.
3229 result = DAG.getNode(ISD::FLOG,
3230 getValue(I.getOperand(1)).getValueType(),
3231 getValue(I.getOperand(1)));
3232 }
3233
Dale Johannesen59e577f2008-09-05 18:38:42 +00003234 setValue(&I, result);
3235}
3236
Bill Wendling3eb59402008-09-09 00:28:24 +00003237/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3238/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003239void
3240SelectionDAGLowering::visitLog2(CallInst &I) {
3241 SDValue result;
Bill Wendling3eb59402008-09-09 00:28:24 +00003242
Dale Johannesen853244f2008-09-05 23:49:37 +00003243 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003244 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3245 SDValue Op = getValue(I.getOperand(1));
3246 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3247
Bill Wendling39150252008-09-09 20:39:27 +00003248 // Get the exponent.
Bill Wendling6c533342009-01-20 06:10:42 +00003249 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI);
Bill Wendling3eb59402008-09-09 00:28:24 +00003250
3251 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003252 // exponent of 1.
3253 SDValue X = GetSignificand(DAG, Op1);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003254
Bill Wendling3eb59402008-09-09 00:28:24 +00003255 // Different possible minimax approximations of significand in
3256 // floating-point for various degrees of accuracy over [1,2].
3257 if (LimitFloatPrecision <= 6) {
3258 // For floating-point precision of 6:
3259 //
3260 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3261 //
3262 // error 0.0049451742, which is more than 7 bits
Bill Wendling39150252008-09-09 20:39:27 +00003263 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003264 getF32Constant(DAG, 0xbeb08fe0));
Bill Wendling39150252008-09-09 20:39:27 +00003265 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003266 getF32Constant(DAG, 0x40019463));
Bill Wendling39150252008-09-09 20:39:27 +00003267 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3268 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003269 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003270
3271 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3272 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3273 // For floating-point precision of 12:
3274 //
3275 // Log2ofMantissa =
3276 // -2.51285454f +
3277 // (4.07009056f +
3278 // (-2.12067489f +
3279 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003280 //
Bill Wendling3eb59402008-09-09 00:28:24 +00003281 // error 0.0000876136000, which is better than 13 bits
Bill Wendling39150252008-09-09 20:39:27 +00003282 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003283 getF32Constant(DAG, 0xbda7262e));
Bill Wendling39150252008-09-09 20:39:27 +00003284 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003285 getF32Constant(DAG, 0x3f25280b));
Bill Wendling39150252008-09-09 20:39:27 +00003286 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3287 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003288 getF32Constant(DAG, 0x4007b923));
Bill Wendling39150252008-09-09 20:39:27 +00003289 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3290 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003291 getF32Constant(DAG, 0x40823e2f));
Bill Wendling39150252008-09-09 20:39:27 +00003292 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3293 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003294 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003295
3296 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3297 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3298 // For floating-point precision of 18:
3299 //
3300 // Log2ofMantissa =
3301 // -3.0400495f +
3302 // (6.1129976f +
3303 // (-5.3420409f +
3304 // (3.2865683f +
3305 // (-1.2669343f +
3306 // (0.27515199f -
3307 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3308 //
3309 // error 0.0000018516, which is better than 18 bits
Bill Wendling39150252008-09-09 20:39:27 +00003310 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003311 getF32Constant(DAG, 0xbcd2769e));
Bill Wendling39150252008-09-09 20:39:27 +00003312 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003313 getF32Constant(DAG, 0x3e8ce0b9));
Bill Wendling39150252008-09-09 20:39:27 +00003314 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3315 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003316 getF32Constant(DAG, 0x3fa22ae7));
Bill Wendling39150252008-09-09 20:39:27 +00003317 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3318 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003319 getF32Constant(DAG, 0x40525723));
Bill Wendling39150252008-09-09 20:39:27 +00003320 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3321 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003322 getF32Constant(DAG, 0x40aaf200));
Bill Wendling39150252008-09-09 20:39:27 +00003323 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3324 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003325 getF32Constant(DAG, 0x40c39dad));
Bill Wendling3eb59402008-09-09 00:28:24 +00003326 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
Bill Wendling39150252008-09-09 20:39:27 +00003327 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003328 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003329
3330 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3331 }
Dale Johannesen853244f2008-09-05 23:49:37 +00003332 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003333 // No special expansion.
Dale Johannesen853244f2008-09-05 23:49:37 +00003334 result = DAG.getNode(ISD::FLOG2,
3335 getValue(I.getOperand(1)).getValueType(),
3336 getValue(I.getOperand(1)));
3337 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003338
Dale Johannesen59e577f2008-09-05 18:38:42 +00003339 setValue(&I, result);
3340}
3341
Bill Wendling3eb59402008-09-09 00:28:24 +00003342/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3343/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003344void
3345SelectionDAGLowering::visitLog10(CallInst &I) {
3346 SDValue result;
Bill Wendling181b6272008-10-19 20:34:04 +00003347
Dale Johannesen852680a2008-09-05 21:27:19 +00003348 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003349 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3350 SDValue Op = getValue(I.getOperand(1));
3351 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3352
Bill Wendling39150252008-09-09 20:39:27 +00003353 // Scale the exponent by log10(2) [0.30102999f].
Bill Wendling6c533342009-01-20 06:10:42 +00003354 SDValue Exp = GetExponent(DAG, Op1, TLI);
Bill Wendling39150252008-09-09 20:39:27 +00003355 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003356 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003357
3358 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003359 // exponent of 1.
3360 SDValue X = GetSignificand(DAG, Op1);
Bill Wendling3eb59402008-09-09 00:28:24 +00003361
3362 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003363 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003364 //
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003365 // Log10ofMantissa =
3366 // -0.50419619f +
3367 // (0.60948995f - 0.10380950f * x) * x;
3368 //
3369 // error 0.0014886165, which is 6 bits
Bill Wendling39150252008-09-09 20:39:27 +00003370 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003371 getF32Constant(DAG, 0xbdd49a13));
Bill Wendling39150252008-09-09 20:39:27 +00003372 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003373 getF32Constant(DAG, 0x3f1c0789));
Bill Wendling39150252008-09-09 20:39:27 +00003374 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3375 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003376 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003377
3378 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003379 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3380 // For floating-point precision of 12:
3381 //
3382 // Log10ofMantissa =
3383 // -0.64831180f +
3384 // (0.91751397f +
3385 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3386 //
3387 // error 0.00019228036, which is better than 12 bits
Bill Wendling39150252008-09-09 20:39:27 +00003388 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003389 getF32Constant(DAG, 0x3d431f31));
Bill Wendling39150252008-09-09 20:39:27 +00003390 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003391 getF32Constant(DAG, 0x3ea21fb2));
Bill Wendling39150252008-09-09 20:39:27 +00003392 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3393 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003394 getF32Constant(DAG, 0x3f6ae232));
Bill Wendling39150252008-09-09 20:39:27 +00003395 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3396 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003397 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00003398
3399 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3400 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003401 // For floating-point precision of 18:
3402 //
3403 // Log10ofMantissa =
3404 // -0.84299375f +
3405 // (1.5327582f +
3406 // (-1.0688956f +
3407 // (0.49102474f +
3408 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3409 //
3410 // error 0.0000037995730, which is better than 18 bits
Bill Wendling39150252008-09-09 20:39:27 +00003411 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003412 getF32Constant(DAG, 0x3c5d51ce));
Bill Wendling39150252008-09-09 20:39:27 +00003413 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003414 getF32Constant(DAG, 0x3e00685a));
Bill Wendling39150252008-09-09 20:39:27 +00003415 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3416 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003417 getF32Constant(DAG, 0x3efb6798));
Bill Wendling39150252008-09-09 20:39:27 +00003418 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3419 SDValue t5 = DAG.getNode(ISD::FSUB, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003420 getF32Constant(DAG, 0x3f88d192));
Bill Wendling39150252008-09-09 20:39:27 +00003421 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3422 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003423 getF32Constant(DAG, 0x3fc4316c));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003424 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
Bill Wendling39150252008-09-09 20:39:27 +00003425 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003426 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003427
3428 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003429 }
Dale Johannesen852680a2008-09-05 21:27:19 +00003430 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003431 // No special expansion.
Dale Johannesen852680a2008-09-05 21:27:19 +00003432 result = DAG.getNode(ISD::FLOG10,
3433 getValue(I.getOperand(1)).getValueType(),
3434 getValue(I.getOperand(1)));
3435 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003436
Dale Johannesen59e577f2008-09-05 18:38:42 +00003437 setValue(&I, result);
3438}
3439
Bill Wendlinge10c8142008-09-09 22:39:21 +00003440/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3441/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003442void
3443SelectionDAGLowering::visitExp2(CallInst &I) {
3444 SDValue result;
Bill Wendlinge10c8142008-09-09 22:39:21 +00003445
Dale Johannesen601d3c02008-09-05 01:48:15 +00003446 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00003447 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3448 SDValue Op = getValue(I.getOperand(1));
3449
3450 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, Op);
3451
3452 // FractionalPartOfX = x - (float)IntegerPartOfX;
3453 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3454 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, Op, t1);
3455
3456 // IntegerPartOfX <<= 23;
3457 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
Bill Wendling6c533342009-01-20 06:10:42 +00003458 DAG.getConstant(23, TLI.getShiftAmountTy()));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003459
3460 if (LimitFloatPrecision <= 6) {
3461 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003462 //
Bill Wendlinge10c8142008-09-09 22:39:21 +00003463 // TwoToFractionalPartOfX =
3464 // 0.997535578f +
3465 // (0.735607626f + 0.252464424f * x) * x;
3466 //
3467 // error 0.0144103317, which is 6 bits
3468 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003469 getF32Constant(DAG, 0x3e814304));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003470 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003471 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003472 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003473 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003474 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003475 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3476 SDValue TwoToFractionalPartOfX =
3477 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3478
3479 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3480 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3481 // For floating-point precision of 12:
3482 //
3483 // TwoToFractionalPartOfX =
3484 // 0.999892986f +
3485 // (0.696457318f +
3486 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3487 //
3488 // error 0.000107046256, which is 13 to 14 bits
3489 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003490 getF32Constant(DAG, 0x3da235e3));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003491 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003492 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003493 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003494 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003495 getF32Constant(DAG, 0x3f324b07));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003496 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3497 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003498 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003499 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3500 SDValue TwoToFractionalPartOfX =
3501 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3502
3503 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3504 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3505 // For floating-point precision of 18:
3506 //
3507 // TwoToFractionalPartOfX =
3508 // 0.999999982f +
3509 // (0.693148872f +
3510 // (0.240227044f +
3511 // (0.554906021e-1f +
3512 // (0.961591928e-2f +
3513 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3514 // error 2.47208000*10^(-7), which is better than 18 bits
3515 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003516 getF32Constant(DAG, 0x3924b03e));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003517 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003518 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003519 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003520 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003521 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003522 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3523 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003524 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003525 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3526 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003527 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003528 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3529 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003530 getF32Constant(DAG, 0x3f317234));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003531 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3532 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003533 getF32Constant(DAG, 0x3f800000));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003534 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3535 SDValue TwoToFractionalPartOfX =
3536 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3537
3538 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3539 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00003540 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003541 // No special expansion.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003542 result = DAG.getNode(ISD::FEXP2,
3543 getValue(I.getOperand(1)).getValueType(),
3544 getValue(I.getOperand(1)));
3545 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00003546
Dale Johannesen601d3c02008-09-05 01:48:15 +00003547 setValue(&I, result);
3548}
3549
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003550/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3551/// limited-precision mode with x == 10.0f.
3552void
3553SelectionDAGLowering::visitPow(CallInst &I) {
3554 SDValue result;
3555 Value *Val = I.getOperand(1);
3556 bool IsExp10 = false;
3557
3558 if (getValue(Val).getValueType() == MVT::f32 &&
Bill Wendling277fc242008-09-10 00:24:59 +00003559 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003560 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3561 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3562 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3563 APFloat Ten(10.0f);
3564 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3565 }
3566 }
3567 }
3568
3569 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3570 SDValue Op = getValue(I.getOperand(2));
3571
3572 // Put the exponent in the right bit position for later addition to the
3573 // final result:
3574 //
3575 // #define LOG2OF10 3.3219281f
3576 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3577 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003578 getF32Constant(DAG, 0x40549a78));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003579 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3580
3581 // FractionalPartOfX = x - (float)IntegerPartOfX;
3582 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3583 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3584
3585 // IntegerPartOfX <<= 23;
3586 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
Bill Wendling6c533342009-01-20 06:10:42 +00003587 DAG.getConstant(23, TLI.getShiftAmountTy()));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003588
3589 if (LimitFloatPrecision <= 6) {
3590 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003591 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003592 // twoToFractionalPartOfX =
3593 // 0.997535578f +
3594 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003595 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003596 // error 0.0144103317, which is 6 bits
3597 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003598 getF32Constant(DAG, 0x3e814304));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003599 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003600 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003601 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003602 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003603 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003604 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3605 SDValue TwoToFractionalPartOfX =
3606 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3607
3608 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3609 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3610 // For floating-point precision of 12:
3611 //
3612 // TwoToFractionalPartOfX =
3613 // 0.999892986f +
3614 // (0.696457318f +
3615 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3616 //
3617 // error 0.000107046256, which is 13 to 14 bits
3618 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003619 getF32Constant(DAG, 0x3da235e3));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003620 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003621 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003622 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003623 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003624 getF32Constant(DAG, 0x3f324b07));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003625 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3626 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003627 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003628 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3629 SDValue TwoToFractionalPartOfX =
3630 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3631
3632 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3633 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3634 // For floating-point precision of 18:
3635 //
3636 // TwoToFractionalPartOfX =
3637 // 0.999999982f +
3638 // (0.693148872f +
3639 // (0.240227044f +
3640 // (0.554906021e-1f +
3641 // (0.961591928e-2f +
3642 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3643 // error 2.47208000*10^(-7), which is better than 18 bits
3644 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003645 getF32Constant(DAG, 0x3924b03e));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003646 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003647 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003648 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003649 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003650 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003651 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3652 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003653 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003654 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3655 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003656 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003657 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3658 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003659 getF32Constant(DAG, 0x3f317234));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003660 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3661 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003662 getF32Constant(DAG, 0x3f800000));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003663 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3664 SDValue TwoToFractionalPartOfX =
3665 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3666
3667 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3668 }
3669 } else {
3670 // No special expansion.
3671 result = DAG.getNode(ISD::FPOW,
3672 getValue(I.getOperand(1)).getValueType(),
3673 getValue(I.getOperand(1)),
3674 getValue(I.getOperand(2)));
3675 }
3676
3677 setValue(&I, result);
3678}
3679
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003680/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3681/// we want to emit this as a call to a named external function, return the name
3682/// otherwise lower it and return null.
3683const char *
3684SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3685 switch (Intrinsic) {
3686 default:
3687 // By default, turn this into a target intrinsic node.
3688 visitTargetIntrinsic(I, Intrinsic);
3689 return 0;
3690 case Intrinsic::vastart: visitVAStart(I); return 0;
3691 case Intrinsic::vaend: visitVAEnd(I); return 0;
3692 case Intrinsic::vacopy: visitVACopy(I); return 0;
3693 case Intrinsic::returnaddress:
3694 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3695 getValue(I.getOperand(1))));
3696 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00003697 case Intrinsic::frameaddress:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003698 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3699 getValue(I.getOperand(1))));
3700 return 0;
3701 case Intrinsic::setjmp:
3702 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3703 break;
3704 case Intrinsic::longjmp:
3705 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3706 break;
Chris Lattner824b9582008-11-21 16:42:48 +00003707 case Intrinsic::memcpy: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003708 SDValue Op1 = getValue(I.getOperand(1));
3709 SDValue Op2 = getValue(I.getOperand(2));
3710 SDValue Op3 = getValue(I.getOperand(3));
3711 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3712 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3713 I.getOperand(1), 0, I.getOperand(2), 0));
3714 return 0;
3715 }
Chris Lattner824b9582008-11-21 16:42:48 +00003716 case Intrinsic::memset: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003717 SDValue Op1 = getValue(I.getOperand(1));
3718 SDValue Op2 = getValue(I.getOperand(2));
3719 SDValue Op3 = getValue(I.getOperand(3));
3720 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3721 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3722 I.getOperand(1), 0));
3723 return 0;
3724 }
Chris Lattner824b9582008-11-21 16:42:48 +00003725 case Intrinsic::memmove: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003726 SDValue Op1 = getValue(I.getOperand(1));
3727 SDValue Op2 = getValue(I.getOperand(2));
3728 SDValue Op3 = getValue(I.getOperand(3));
3729 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3730
3731 // If the source and destination are known to not be aliases, we can
3732 // lower memmove as memcpy.
3733 uint64_t Size = -1ULL;
3734 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003735 Size = C->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003736 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3737 AliasAnalysis::NoAlias) {
3738 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3739 I.getOperand(1), 0, I.getOperand(2), 0));
3740 return 0;
3741 }
3742
3743 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3744 I.getOperand(1), 0, I.getOperand(2), 0));
3745 return 0;
3746 }
3747 case Intrinsic::dbg_stoppoint: {
Devang Patel83489bb2009-01-13 00:35:13 +00003748 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003749 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Devang Patelb79b5352009-01-19 23:21:49 +00003750 if (DW && DW->ValidDebugInfo(SPI.getContext()))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003751 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3752 SPI.getLine(),
3753 SPI.getColumn(),
Devang Patel83489bb2009-01-13 00:35:13 +00003754 SPI.getContext()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003755 return 0;
3756 }
3757 case Intrinsic::dbg_region_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003758 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003759 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Devang Patelb79b5352009-01-19 23:21:49 +00003760 if (DW && DW->ValidDebugInfo(RSI.getContext())) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003761 unsigned LabelID =
Devang Patel83489bb2009-01-13 00:35:13 +00003762 DW->RecordRegionStart(cast<GlobalVariable>(RSI.getContext()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003763 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3764 }
3765
3766 return 0;
3767 }
3768 case Intrinsic::dbg_region_end: {
Devang Patel83489bb2009-01-13 00:35:13 +00003769 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003770 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Devang Patelb79b5352009-01-19 23:21:49 +00003771 if (DW && DW->ValidDebugInfo(REI.getContext())) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003772 unsigned LabelID =
Devang Patel83489bb2009-01-13 00:35:13 +00003773 DW->RecordRegionEnd(cast<GlobalVariable>(REI.getContext()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003774 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3775 }
3776
3777 return 0;
3778 }
3779 case Intrinsic::dbg_func_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003780 DwarfWriter *DW = DAG.getDwarfWriter();
3781 if (!DW) return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003782 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3783 Value *SP = FSI.getSubprogram();
Devang Patelcf3a4482009-01-15 23:41:32 +00003784 if (SP && DW->ValidDebugInfo(SP)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003785 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3786 // what (most?) gdb expects.
Devang Patel83489bb2009-01-13 00:35:13 +00003787 DISubprogram Subprogram(cast<GlobalVariable>(SP));
3788 DICompileUnit CompileUnit = Subprogram.getCompileUnit();
3789 unsigned SrcFile = DW->RecordSource(CompileUnit.getDirectory(),
3790 CompileUnit.getFilename());
Devang Patel20dd0462008-11-06 00:30:09 +00003791 // Record the source line but does not create a label for the normal
3792 // function start. It will be emitted at asm emission time. However,
3793 // create a label if this is a beginning of inlined function.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003794 unsigned LabelID =
Devang Patel83489bb2009-01-13 00:35:13 +00003795 DW->RecordSourceLine(Subprogram.getLineNumber(), 0, SrcFile);
3796 if (DW->getRecordSourceLineCount() != 1)
Devang Patel20dd0462008-11-06 00:30:09 +00003797 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003798 }
3799
3800 return 0;
3801 }
3802 case Intrinsic::dbg_declare: {
Devang Patel83489bb2009-01-13 00:35:13 +00003803 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003804 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3805 Value *Variable = DI.getVariable();
Devang Patelb79b5352009-01-19 23:21:49 +00003806 if (DW && DW->ValidDebugInfo(Variable))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003807 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3808 getValue(DI.getAddress()), getValue(Variable)));
3809 return 0;
3810 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003811
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003812 case Intrinsic::eh_exception: {
3813 if (!CurMBB->isLandingPad()) {
3814 // FIXME: Mark exception register as live in. Hack for PR1508.
3815 unsigned Reg = TLI.getExceptionAddressRegister();
3816 if (Reg) CurMBB->addLiveIn(Reg);
3817 }
3818 // Insert the EXCEPTIONADDR instruction.
3819 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3820 SDValue Ops[1];
3821 Ops[0] = DAG.getRoot();
3822 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3823 setValue(&I, Op);
3824 DAG.setRoot(Op.getValue(1));
3825 return 0;
3826 }
3827
3828 case Intrinsic::eh_selector_i32:
3829 case Intrinsic::eh_selector_i64: {
3830 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3831 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3832 MVT::i32 : MVT::i64);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003833
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003834 if (MMI) {
3835 if (CurMBB->isLandingPad())
3836 AddCatchInfo(I, MMI, CurMBB);
3837 else {
3838#ifndef NDEBUG
3839 FuncInfo.CatchInfoLost.insert(&I);
3840#endif
3841 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3842 unsigned Reg = TLI.getExceptionSelectorRegister();
3843 if (Reg) CurMBB->addLiveIn(Reg);
3844 }
3845
3846 // Insert the EHSELECTION instruction.
3847 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3848 SDValue Ops[2];
3849 Ops[0] = getValue(I.getOperand(1));
3850 Ops[1] = getRoot();
3851 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3852 setValue(&I, Op);
3853 DAG.setRoot(Op.getValue(1));
3854 } else {
3855 setValue(&I, DAG.getConstant(0, VT));
3856 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003857
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003858 return 0;
3859 }
3860
3861 case Intrinsic::eh_typeid_for_i32:
3862 case Intrinsic::eh_typeid_for_i64: {
3863 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3864 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3865 MVT::i32 : MVT::i64);
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003866
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003867 if (MMI) {
3868 // Find the type id for the given typeinfo.
3869 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3870
3871 unsigned TypeID = MMI->getTypeIDFor(GV);
3872 setValue(&I, DAG.getConstant(TypeID, VT));
3873 } else {
3874 // Return something different to eh_selector.
3875 setValue(&I, DAG.getConstant(1, VT));
3876 }
3877
3878 return 0;
3879 }
3880
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003881 case Intrinsic::eh_return_i32:
3882 case Intrinsic::eh_return_i64:
3883 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003884 MMI->setCallsEHReturn(true);
3885 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3886 MVT::Other,
3887 getControlRoot(),
3888 getValue(I.getOperand(1)),
3889 getValue(I.getOperand(2))));
3890 } else {
3891 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3892 }
3893
3894 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003895 case Intrinsic::eh_unwind_init:
3896 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3897 MMI->setCallsUnwindInit(true);
3898 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003899
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003900 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003901
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003902 case Intrinsic::eh_dwarf_cfa: {
3903 MVT VT = getValue(I.getOperand(1)).getValueType();
3904 SDValue CfaArg;
3905 if (VT.bitsGT(TLI.getPointerTy()))
3906 CfaArg = DAG.getNode(ISD::TRUNCATE,
3907 TLI.getPointerTy(), getValue(I.getOperand(1)));
3908 else
3909 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3910 TLI.getPointerTy(), getValue(I.getOperand(1)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003911
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003912 SDValue Offset = DAG.getNode(ISD::ADD,
3913 TLI.getPointerTy(),
3914 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3915 TLI.getPointerTy()),
3916 CfaArg);
3917 setValue(&I, DAG.getNode(ISD::ADD,
3918 TLI.getPointerTy(),
3919 DAG.getNode(ISD::FRAMEADDR,
3920 TLI.getPointerTy(),
3921 DAG.getConstant(0,
3922 TLI.getPointerTy())),
3923 Offset));
3924 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003925 }
3926
Mon P Wang77cdf302008-11-10 20:54:11 +00003927 case Intrinsic::convertff:
3928 case Intrinsic::convertfsi:
3929 case Intrinsic::convertfui:
3930 case Intrinsic::convertsif:
3931 case Intrinsic::convertuif:
3932 case Intrinsic::convertss:
3933 case Intrinsic::convertsu:
3934 case Intrinsic::convertus:
3935 case Intrinsic::convertuu: {
3936 ISD::CvtCode Code = ISD::CVT_INVALID;
3937 switch (Intrinsic) {
3938 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
3939 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
3940 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
3941 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
3942 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
3943 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
3944 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
3945 case Intrinsic::convertus: Code = ISD::CVT_US; break;
3946 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
3947 }
3948 MVT DestVT = TLI.getValueType(I.getType());
3949 Value* Op1 = I.getOperand(1);
3950 setValue(&I, DAG.getConvertRndSat(DestVT, getValue(Op1),
3951 DAG.getValueType(DestVT),
3952 DAG.getValueType(getValue(Op1).getValueType()),
3953 getValue(I.getOperand(2)),
3954 getValue(I.getOperand(3)),
3955 Code));
3956 return 0;
3957 }
3958
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003959 case Intrinsic::sqrt:
3960 setValue(&I, DAG.getNode(ISD::FSQRT,
3961 getValue(I.getOperand(1)).getValueType(),
3962 getValue(I.getOperand(1))));
3963 return 0;
3964 case Intrinsic::powi:
3965 setValue(&I, DAG.getNode(ISD::FPOWI,
3966 getValue(I.getOperand(1)).getValueType(),
3967 getValue(I.getOperand(1)),
3968 getValue(I.getOperand(2))));
3969 return 0;
3970 case Intrinsic::sin:
3971 setValue(&I, DAG.getNode(ISD::FSIN,
3972 getValue(I.getOperand(1)).getValueType(),
3973 getValue(I.getOperand(1))));
3974 return 0;
3975 case Intrinsic::cos:
3976 setValue(&I, DAG.getNode(ISD::FCOS,
3977 getValue(I.getOperand(1)).getValueType(),
3978 getValue(I.getOperand(1))));
3979 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003980 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003981 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003982 return 0;
3983 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003984 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003985 return 0;
3986 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003987 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003988 return 0;
3989 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003990 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003991 return 0;
3992 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00003993 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003994 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003995 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003996 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003997 return 0;
3998 case Intrinsic::pcmarker: {
3999 SDValue Tmp = getValue(I.getOperand(1));
4000 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
4001 return 0;
4002 }
4003 case Intrinsic::readcyclecounter: {
4004 SDValue Op = getRoot();
4005 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
4006 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
4007 &Op, 1);
4008 setValue(&I, Tmp);
4009 DAG.setRoot(Tmp.getValue(1));
4010 return 0;
4011 }
4012 case Intrinsic::part_select: {
4013 // Currently not implemented: just abort
4014 assert(0 && "part_select intrinsic not implemented");
4015 abort();
4016 }
4017 case Intrinsic::part_set: {
4018 // Currently not implemented: just abort
4019 assert(0 && "part_set intrinsic not implemented");
4020 abort();
4021 }
4022 case Intrinsic::bswap:
4023 setValue(&I, DAG.getNode(ISD::BSWAP,
4024 getValue(I.getOperand(1)).getValueType(),
4025 getValue(I.getOperand(1))));
4026 return 0;
4027 case Intrinsic::cttz: {
4028 SDValue Arg = getValue(I.getOperand(1));
4029 MVT Ty = Arg.getValueType();
4030 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
4031 setValue(&I, result);
4032 return 0;
4033 }
4034 case Intrinsic::ctlz: {
4035 SDValue Arg = getValue(I.getOperand(1));
4036 MVT Ty = Arg.getValueType();
4037 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
4038 setValue(&I, result);
4039 return 0;
4040 }
4041 case Intrinsic::ctpop: {
4042 SDValue Arg = getValue(I.getOperand(1));
4043 MVT Ty = Arg.getValueType();
4044 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
4045 setValue(&I, result);
4046 return 0;
4047 }
4048 case Intrinsic::stacksave: {
4049 SDValue Op = getRoot();
4050 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
4051 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
4052 setValue(&I, Tmp);
4053 DAG.setRoot(Tmp.getValue(1));
4054 return 0;
4055 }
4056 case Intrinsic::stackrestore: {
4057 SDValue Tmp = getValue(I.getOperand(1));
4058 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
4059 return 0;
4060 }
Bill Wendling57344502008-11-18 11:01:33 +00004061 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00004062 // Emit code into the DAG to store the stack guard onto the stack.
4063 MachineFunction &MF = DAG.getMachineFunction();
4064 MachineFrameInfo *MFI = MF.getFrameInfo();
4065 MVT PtrTy = TLI.getPointerTy();
4066
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004067 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4068 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
Bill Wendlingb2a42982008-11-06 02:29:10 +00004069
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004070 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00004071 MFI->setStackProtectorIndex(FI);
4072
4073 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4074
4075 // Store the stack protector onto the stack.
4076 SDValue Result = DAG.getStore(getRoot(), Src, FIN,
4077 PseudoSourceValue::getFixedStack(FI),
4078 0, true);
4079 setValue(&I, Result);
4080 DAG.setRoot(Result);
4081 return 0;
4082 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004083 case Intrinsic::var_annotation:
4084 // Discard annotate attributes
4085 return 0;
4086
4087 case Intrinsic::init_trampoline: {
4088 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4089
4090 SDValue Ops[6];
4091 Ops[0] = getRoot();
4092 Ops[1] = getValue(I.getOperand(1));
4093 Ops[2] = getValue(I.getOperand(2));
4094 Ops[3] = getValue(I.getOperand(3));
4095 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4096 Ops[5] = DAG.getSrcValue(F);
4097
4098 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
4099 DAG.getNodeValueTypes(TLI.getPointerTy(),
4100 MVT::Other), 2,
4101 Ops, 6);
4102
4103 setValue(&I, Tmp);
4104 DAG.setRoot(Tmp.getValue(1));
4105 return 0;
4106 }
4107
4108 case Intrinsic::gcroot:
4109 if (GFI) {
4110 Value *Alloca = I.getOperand(1);
4111 Constant *TypeMap = cast<Constant>(I.getOperand(2));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004112
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004113 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4114 GFI->addStackRoot(FI->getIndex(), TypeMap);
4115 }
4116 return 0;
4117
4118 case Intrinsic::gcread:
4119 case Intrinsic::gcwrite:
4120 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
4121 return 0;
4122
4123 case Intrinsic::flt_rounds: {
4124 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
4125 return 0;
4126 }
4127
4128 case Intrinsic::trap: {
4129 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
4130 return 0;
4131 }
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004132
Bill Wendlingef375462008-11-21 02:38:44 +00004133 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00004134 return implVisitAluOverflow(I, ISD::UADDO);
4135 case Intrinsic::sadd_with_overflow:
4136 return implVisitAluOverflow(I, ISD::SADDO);
4137 case Intrinsic::usub_with_overflow:
4138 return implVisitAluOverflow(I, ISD::USUBO);
4139 case Intrinsic::ssub_with_overflow:
4140 return implVisitAluOverflow(I, ISD::SSUBO);
4141 case Intrinsic::umul_with_overflow:
4142 return implVisitAluOverflow(I, ISD::UMULO);
4143 case Intrinsic::smul_with_overflow:
4144 return implVisitAluOverflow(I, ISD::SMULO);
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004145
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004146 case Intrinsic::prefetch: {
4147 SDValue Ops[4];
4148 Ops[0] = getRoot();
4149 Ops[1] = getValue(I.getOperand(1));
4150 Ops[2] = getValue(I.getOperand(2));
4151 Ops[3] = getValue(I.getOperand(3));
4152 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
4153 return 0;
4154 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004155
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004156 case Intrinsic::memory_barrier: {
4157 SDValue Ops[6];
4158 Ops[0] = getRoot();
4159 for (int x = 1; x < 6; ++x)
4160 Ops[x] = getValue(I.getOperand(x));
4161
4162 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
4163 return 0;
4164 }
4165 case Intrinsic::atomic_cmp_swap: {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004166 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004167 SDValue L =
4168 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP,
4169 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4170 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004171 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004172 getValue(I.getOperand(2)),
4173 getValue(I.getOperand(3)),
4174 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004175 setValue(&I, L);
4176 DAG.setRoot(L.getValue(1));
4177 return 0;
4178 }
4179 case Intrinsic::atomic_load_add:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004180 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004181 case Intrinsic::atomic_load_sub:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004182 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004183 case Intrinsic::atomic_load_or:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004184 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004185 case Intrinsic::atomic_load_xor:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004186 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004187 case Intrinsic::atomic_load_and:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004188 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004189 case Intrinsic::atomic_load_nand:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004190 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004191 case Intrinsic::atomic_load_max:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004192 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004193 case Intrinsic::atomic_load_min:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004194 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004195 case Intrinsic::atomic_load_umin:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004196 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004197 case Intrinsic::atomic_load_umax:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004198 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004199 case Intrinsic::atomic_swap:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004200 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004201 }
4202}
4203
4204
4205void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4206 bool IsTailCall,
4207 MachineBasicBlock *LandingPad) {
4208 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4209 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4210 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4211 unsigned BeginLabel = 0, EndLabel = 0;
4212
4213 TargetLowering::ArgListTy Args;
4214 TargetLowering::ArgListEntry Entry;
4215 Args.reserve(CS.arg_size());
4216 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4217 i != e; ++i) {
4218 SDValue ArgNode = getValue(*i);
4219 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4220
4221 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00004222 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4223 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4224 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4225 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4226 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4227 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004228 Entry.Alignment = CS.getParamAlignment(attrInd);
4229 Args.push_back(Entry);
4230 }
4231
4232 if (LandingPad && MMI) {
4233 // Insert a label before the invoke call to mark the try range. This can be
4234 // used to detect deletion of the invoke via the MachineModuleInfo.
4235 BeginLabel = MMI->NextLabelID();
4236 // Both PendingLoads and PendingExports must be flushed here;
4237 // this call might not return.
4238 (void)getRoot();
4239 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
4240 }
4241
4242 std::pair<SDValue,SDValue> Result =
4243 TLI.LowerCallTo(getRoot(), CS.getType(),
Devang Patel05988662008-09-25 21:00:45 +00004244 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004245 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4246 CS.paramHasAttr(0, Attribute::InReg),
4247 CS.getCallingConv(),
Dan Gohman1937e2f2008-09-16 01:42:28 +00004248 IsTailCall && PerformTailCallOpt,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004249 Callee, Args, DAG);
4250 if (CS.getType() != Type::VoidTy)
4251 setValue(CS.getInstruction(), Result.first);
4252 DAG.setRoot(Result.second);
4253
4254 if (LandingPad && MMI) {
4255 // Insert a label at the end of the invoke call to mark the try range. This
4256 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4257 EndLabel = MMI->NextLabelID();
4258 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
4259
4260 // Inform MachineModuleInfo of range.
4261 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4262 }
4263}
4264
4265
4266void SelectionDAGLowering::visitCall(CallInst &I) {
4267 const char *RenameFn = 0;
4268 if (Function *F = I.getCalledFunction()) {
4269 if (F->isDeclaration()) {
4270 if (unsigned IID = F->getIntrinsicID()) {
4271 RenameFn = visitIntrinsicCall(I, IID);
4272 if (!RenameFn)
4273 return;
4274 }
4275 }
4276
4277 // Check for well-known libc/libm calls. If the function is internal, it
4278 // can't be a library call.
4279 unsigned NameLen = F->getNameLen();
Rafael Espindolabb46f522009-01-15 20:18:42 +00004280 if (!F->hasLocalLinkage() && NameLen) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004281 const char *NameStr = F->getNameStart();
4282 if (NameStr[0] == 'c' &&
4283 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4284 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4285 if (I.getNumOperands() == 3 && // Basic sanity checks.
4286 I.getOperand(1)->getType()->isFloatingPoint() &&
4287 I.getType() == I.getOperand(1)->getType() &&
4288 I.getType() == I.getOperand(2)->getType()) {
4289 SDValue LHS = getValue(I.getOperand(1));
4290 SDValue RHS = getValue(I.getOperand(2));
4291 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
4292 LHS, RHS));
4293 return;
4294 }
4295 } else if (NameStr[0] == 'f' &&
4296 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4297 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4298 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4299 if (I.getNumOperands() == 2 && // Basic sanity checks.
4300 I.getOperand(1)->getType()->isFloatingPoint() &&
4301 I.getType() == I.getOperand(1)->getType()) {
4302 SDValue Tmp = getValue(I.getOperand(1));
4303 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
4304 return;
4305 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004306 } else if (NameStr[0] == 's' &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004307 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4308 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4309 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4310 if (I.getNumOperands() == 2 && // Basic sanity checks.
4311 I.getOperand(1)->getType()->isFloatingPoint() &&
4312 I.getType() == I.getOperand(1)->getType()) {
4313 SDValue Tmp = getValue(I.getOperand(1));
4314 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
4315 return;
4316 }
4317 } else if (NameStr[0] == 'c' &&
4318 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4319 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4320 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4321 if (I.getNumOperands() == 2 && // Basic sanity checks.
4322 I.getOperand(1)->getType()->isFloatingPoint() &&
4323 I.getType() == I.getOperand(1)->getType()) {
4324 SDValue Tmp = getValue(I.getOperand(1));
4325 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
4326 return;
4327 }
4328 }
4329 }
4330 } else if (isa<InlineAsm>(I.getOperand(0))) {
4331 visitInlineAsm(&I);
4332 return;
4333 }
4334
4335 SDValue Callee;
4336 if (!RenameFn)
4337 Callee = getValue(I.getOperand(0));
4338 else
Bill Wendling056292f2008-09-16 21:48:12 +00004339 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004340
4341 LowerCallTo(&I, Callee, I.isTailCall());
4342}
4343
4344
4345/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004346/// this value and returns the result as a ValueVT value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004347/// Chain/Flag as the input and updates them for the output Chain/Flag.
4348/// If the Flag pointer is NULL, no flag is used.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004349SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004350 SDValue &Chain,
4351 SDValue *Flag) const {
4352 // Assemble the legal parts into the final values.
4353 SmallVector<SDValue, 4> Values(ValueVTs.size());
4354 SmallVector<SDValue, 8> Parts;
4355 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4356 // Copy the legal parts from the registers.
4357 MVT ValueVT = ValueVTs[Value];
4358 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4359 MVT RegisterVT = RegVTs[Value];
4360
4361 Parts.resize(NumRegs);
4362 for (unsigned i = 0; i != NumRegs; ++i) {
4363 SDValue P;
4364 if (Flag == 0)
4365 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
4366 else {
4367 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
4368 *Flag = P.getValue(2);
4369 }
4370 Chain = P.getValue(1);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004371
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004372 // If the source register was virtual and if we know something about it,
4373 // add an assert node.
4374 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4375 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4376 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4377 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4378 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4379 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004380
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004381 unsigned RegSize = RegisterVT.getSizeInBits();
4382 unsigned NumSignBits = LOI.NumSignBits;
4383 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004384
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004385 // FIXME: We capture more information than the dag can represent. For
4386 // now, just use the tightest assertzext/assertsext possible.
4387 bool isSExt = true;
4388 MVT FromVT(MVT::Other);
4389 if (NumSignBits == RegSize)
4390 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4391 else if (NumZeroBits >= RegSize-1)
4392 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4393 else if (NumSignBits > RegSize-8)
4394 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4395 else if (NumZeroBits >= RegSize-9)
4396 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4397 else if (NumSignBits > RegSize-16)
Bill Wendling181b6272008-10-19 20:34:04 +00004398 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004399 else if (NumZeroBits >= RegSize-17)
Bill Wendling181b6272008-10-19 20:34:04 +00004400 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004401 else if (NumSignBits > RegSize-32)
Bill Wendling181b6272008-10-19 20:34:04 +00004402 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004403 else if (NumZeroBits >= RegSize-33)
Bill Wendling181b6272008-10-19 20:34:04 +00004404 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004405
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004406 if (FromVT != MVT::Other) {
4407 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
4408 RegisterVT, P, DAG.getValueType(FromVT));
4409
4410 }
4411 }
4412 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004413
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004414 Parts[i] = P;
4415 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004416
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004417 Values[Value] = getCopyFromParts(DAG, Parts.begin(), NumRegs, RegisterVT,
4418 ValueVT);
4419 Part += NumRegs;
4420 Parts.clear();
4421 }
4422
Duncan Sandsaaffa052008-12-01 11:41:29 +00004423 return DAG.getNode(ISD::MERGE_VALUES,
4424 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4425 &Values[0], ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004426}
4427
4428/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004429/// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004430/// Chain/Flag as the input and updates them for the output Chain/Flag.
4431/// If the Flag pointer is NULL, no flag is used.
4432void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
4433 SDValue &Chain, SDValue *Flag) const {
4434 // Get the list of the values's legal parts.
4435 unsigned NumRegs = Regs.size();
4436 SmallVector<SDValue, 8> Parts(NumRegs);
4437 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4438 MVT ValueVT = ValueVTs[Value];
4439 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4440 MVT RegisterVT = RegVTs[Value];
4441
4442 getCopyToParts(DAG, Val.getValue(Val.getResNo() + Value),
4443 &Parts[Part], NumParts, RegisterVT);
4444 Part += NumParts;
4445 }
4446
4447 // Copy the parts into the registers.
4448 SmallVector<SDValue, 8> Chains(NumRegs);
4449 for (unsigned i = 0; i != NumRegs; ++i) {
4450 SDValue Part;
4451 if (Flag == 0)
4452 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
4453 else {
4454 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
4455 *Flag = Part.getValue(1);
4456 }
4457 Chains[i] = Part.getValue(0);
4458 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004459
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004460 if (NumRegs == 1 || Flag)
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004461 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004462 // flagged to it. That is the CopyToReg nodes and the user are considered
4463 // a single scheduling unit. If we create a TokenFactor and return it as
4464 // chain, then the TokenFactor is both a predecessor (operand) of the
4465 // user as well as a successor (the TF operands are flagged to the user).
4466 // c1, f1 = CopyToReg
4467 // c2, f2 = CopyToReg
4468 // c3 = TokenFactor c1, c2
4469 // ...
4470 // = op c3, ..., f2
4471 Chain = Chains[NumRegs-1];
4472 else
4473 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
4474}
4475
4476/// AddInlineAsmOperands - Add this value to the specified inlineasm node
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004477/// operand list. This adds the code marker and includes the number of
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004478/// values added into it.
4479void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
4480 std::vector<SDValue> &Ops) const {
4481 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4482 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
4483 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4484 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4485 MVT RegisterVT = RegVTs[Value];
Chris Lattner58f15c42008-10-17 16:21:11 +00004486 for (unsigned i = 0; i != NumRegs; ++i) {
4487 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004488 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner58f15c42008-10-17 16:21:11 +00004489 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004490 }
4491}
4492
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004493/// isAllocatableRegister - If the specified register is safe to allocate,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004494/// i.e. it isn't a stack pointer or some other special register, return the
4495/// register class for the register. Otherwise, return null.
4496static const TargetRegisterClass *
4497isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4498 const TargetLowering &TLI,
4499 const TargetRegisterInfo *TRI) {
4500 MVT FoundVT = MVT::Other;
4501 const TargetRegisterClass *FoundRC = 0;
4502 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4503 E = TRI->regclass_end(); RCI != E; ++RCI) {
4504 MVT ThisVT = MVT::Other;
4505
4506 const TargetRegisterClass *RC = *RCI;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004507 // If none of the the value types for this register class are valid, we
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004508 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4509 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4510 I != E; ++I) {
4511 if (TLI.isTypeLegal(*I)) {
4512 // If we have already found this register in a different register class,
4513 // choose the one with the largest VT specified. For example, on
4514 // PowerPC, we favor f64 register classes over f32.
4515 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4516 ThisVT = *I;
4517 break;
4518 }
4519 }
4520 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004521
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004522 if (ThisVT == MVT::Other) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004523
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004524 // NOTE: This isn't ideal. In particular, this might allocate the
4525 // frame pointer in functions that need it (due to them not being taken
4526 // out of allocation, because a variable sized allocation hasn't been seen
4527 // yet). This is a slight code pessimization, but should still work.
4528 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4529 E = RC->allocation_order_end(MF); I != E; ++I)
4530 if (*I == Reg) {
4531 // We found a matching register class. Keep looking at others in case
4532 // we find one with larger registers that this physreg is also in.
4533 FoundRC = RC;
4534 FoundVT = ThisVT;
4535 break;
4536 }
4537 }
4538 return FoundRC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004539}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004540
4541
4542namespace llvm {
4543/// AsmOperandInfo - This contains information for each constraint that we are
4544/// lowering.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004545struct VISIBILITY_HIDDEN SDISelAsmOperandInfo :
Daniel Dunbarc0c3b9a2008-09-10 04:16:29 +00004546 public TargetLowering::AsmOperandInfo {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004547 /// CallOperand - If this is the result output operand or a clobber
4548 /// this is null, otherwise it is the incoming operand to the CallInst.
4549 /// This gets modified as the asm is processed.
4550 SDValue CallOperand;
4551
4552 /// AssignedRegs - If this is a register or register class operand, this
4553 /// contains the set of register corresponding to the operand.
4554 RegsForValue AssignedRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004555
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004556 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4557 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4558 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004559
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004560 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4561 /// busy in OutputRegs/InputRegs.
4562 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004563 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004564 std::set<unsigned> &InputRegs,
4565 const TargetRegisterInfo &TRI) const {
4566 if (isOutReg) {
4567 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4568 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4569 }
4570 if (isInReg) {
4571 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4572 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4573 }
4574 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004575
Chris Lattner81249c92008-10-17 17:05:25 +00004576 /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4577 /// corresponds to. If there is no Value* for this operand, it returns
4578 /// MVT::Other.
4579 MVT getCallOperandValMVT(const TargetLowering &TLI,
4580 const TargetData *TD) const {
4581 if (CallOperandVal == 0) return MVT::Other;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004582
Chris Lattner81249c92008-10-17 17:05:25 +00004583 if (isa<BasicBlock>(CallOperandVal))
4584 return TLI.getPointerTy();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004585
Chris Lattner81249c92008-10-17 17:05:25 +00004586 const llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004587
Chris Lattner81249c92008-10-17 17:05:25 +00004588 // If this is an indirect operand, the operand is a pointer to the
4589 // accessed type.
4590 if (isIndirect)
4591 OpTy = cast<PointerType>(OpTy)->getElementType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004592
Chris Lattner81249c92008-10-17 17:05:25 +00004593 // If OpTy is not a single value, it may be a struct/union that we
4594 // can tile with integers.
4595 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4596 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4597 switch (BitSize) {
4598 default: break;
4599 case 1:
4600 case 8:
4601 case 16:
4602 case 32:
4603 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00004604 case 128:
Chris Lattner81249c92008-10-17 17:05:25 +00004605 OpTy = IntegerType::get(BitSize);
4606 break;
4607 }
4608 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004609
Chris Lattner81249c92008-10-17 17:05:25 +00004610 return TLI.getValueType(OpTy, true);
4611 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004612
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004613private:
4614 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4615 /// specified set.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004616 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004617 const TargetRegisterInfo &TRI) {
4618 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4619 Regs.insert(Reg);
4620 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4621 for (; *Aliases; ++Aliases)
4622 Regs.insert(*Aliases);
4623 }
4624};
4625} // end llvm namespace.
4626
4627
4628/// GetRegistersForValue - Assign registers (virtual or physical) for the
4629/// specified operand. We prefer to assign virtual registers, to allow the
4630/// register allocator handle the assignment process. However, if the asm uses
4631/// features that we can't model on machineinstrs, we have SDISel do the
4632/// allocation. This produces generally horrible, but correct, code.
4633///
4634/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004635/// Input and OutputRegs are the set of already allocated physical registers.
4636///
4637void SelectionDAGLowering::
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004638GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004639 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004640 std::set<unsigned> &InputRegs) {
4641 // Compute whether this value requires an input register, an output register,
4642 // or both.
4643 bool isOutReg = false;
4644 bool isInReg = false;
4645 switch (OpInfo.Type) {
4646 case InlineAsm::isOutput:
4647 isOutReg = true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004648
4649 // If there is an input constraint that matches this, we need to reserve
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004650 // the input register so no other inputs allocate to it.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004651 isInReg = OpInfo.hasMatchingInput();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004652 break;
4653 case InlineAsm::isInput:
4654 isInReg = true;
4655 isOutReg = false;
4656 break;
4657 case InlineAsm::isClobber:
4658 isOutReg = true;
4659 isInReg = true;
4660 break;
4661 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004662
4663
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004664 MachineFunction &MF = DAG.getMachineFunction();
4665 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004666
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004667 // If this is a constraint for a single physreg, or a constraint for a
4668 // register class, find it.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004669 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004670 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4671 OpInfo.ConstraintVT);
4672
4673 unsigned NumRegs = 1;
Chris Lattner01426e12008-10-21 00:45:36 +00004674 if (OpInfo.ConstraintVT != MVT::Other) {
4675 // If this is a FP input in an integer register (or visa versa) insert a bit
4676 // cast of the input value. More generally, handle any case where the input
4677 // value disagrees with the register class we plan to stick this in.
4678 if (OpInfo.Type == InlineAsm::isInput &&
4679 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4680 // Try to convert to the first MVT that the reg class contains. If the
4681 // types are identical size, use a bitcast to convert (e.g. two differing
4682 // vector types).
4683 MVT RegVT = *PhysReg.second->vt_begin();
4684 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
4685 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4686 OpInfo.CallOperand);
4687 OpInfo.ConstraintVT = RegVT;
4688 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4689 // If the input is a FP value and we want it in FP registers, do a
4690 // bitcast to the corresponding integer type. This turns an f64 value
4691 // into i64, which can be passed with two i32 values on a 32-bit
4692 // machine.
4693 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
4694 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4695 OpInfo.CallOperand);
4696 OpInfo.ConstraintVT = RegVT;
4697 }
4698 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004699
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004700 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00004701 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004702
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004703 MVT RegVT;
4704 MVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004705
4706 // If this is a constraint for a specific physical register, like {r17},
4707 // assign it now.
4708 if (PhysReg.first) {
4709 if (OpInfo.ConstraintVT == MVT::Other)
4710 ValueVT = *PhysReg.second->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004711
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004712 // Get the actual register value type. This is important, because the user
4713 // may have asked for (e.g.) the AX register in i32 type. We need to
4714 // remember that AX is actually i16 to get the right extension.
4715 RegVT = *PhysReg.second->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004716
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004717 // This is a explicit reference to a physical register.
4718 Regs.push_back(PhysReg.first);
4719
4720 // If this is an expanded reference, add the rest of the regs to Regs.
4721 if (NumRegs != 1) {
4722 TargetRegisterClass::iterator I = PhysReg.second->begin();
4723 for (; *I != PhysReg.first; ++I)
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004724 assert(I != PhysReg.second->end() && "Didn't find reg!");
4725
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004726 // Already added the first reg.
4727 --NumRegs; ++I;
4728 for (; NumRegs; --NumRegs, ++I) {
4729 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
4730 Regs.push_back(*I);
4731 }
4732 }
4733 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4734 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4735 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4736 return;
4737 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004738
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004739 // Otherwise, if this was a reference to an LLVM register class, create vregs
4740 // for this reference.
4741 std::vector<unsigned> RegClassRegs;
4742 const TargetRegisterClass *RC = PhysReg.second;
4743 if (RC) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004744 // If this is a tied register, our regalloc doesn't know how to maintain
Chris Lattner58f15c42008-10-17 16:21:11 +00004745 // the constraint, so we have to pick a register to pin the input/output to.
4746 // If it isn't a matched constraint, go ahead and create vreg and let the
4747 // regalloc do its thing.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004748 if (!OpInfo.hasMatchingInput()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004749 RegVT = *PhysReg.second->vt_begin();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004750 if (OpInfo.ConstraintVT == MVT::Other)
4751 ValueVT = RegVT;
4752
4753 // Create the appropriate number of virtual registers.
4754 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4755 for (; NumRegs; --NumRegs)
4756 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004757
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004758 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4759 return;
4760 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004761
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004762 // Otherwise, we can't allocate it. Let the code below figure out how to
4763 // maintain these constraints.
4764 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004765
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004766 } else {
4767 // This is a reference to a register class that doesn't directly correspond
4768 // to an LLVM register class. Allocate NumRegs consecutive, available,
4769 // registers from the class.
4770 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4771 OpInfo.ConstraintVT);
4772 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004773
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004774 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4775 unsigned NumAllocated = 0;
4776 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4777 unsigned Reg = RegClassRegs[i];
4778 // See if this register is available.
4779 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4780 (isInReg && InputRegs.count(Reg))) { // Already used.
4781 // Make sure we find consecutive registers.
4782 NumAllocated = 0;
4783 continue;
4784 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004785
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004786 // Check to see if this register is allocatable (i.e. don't give out the
4787 // stack pointer).
4788 if (RC == 0) {
4789 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4790 if (!RC) { // Couldn't allocate this register.
4791 // Reset NumAllocated to make sure we return consecutive registers.
4792 NumAllocated = 0;
4793 continue;
4794 }
4795 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004796
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004797 // Okay, this register is good, we can use it.
4798 ++NumAllocated;
4799
4800 // If we allocated enough consecutive registers, succeed.
4801 if (NumAllocated == NumRegs) {
4802 unsigned RegStart = (i-NumAllocated)+1;
4803 unsigned RegEnd = i+1;
4804 // Mark all of the allocated registers used.
4805 for (unsigned i = RegStart; i != RegEnd; ++i)
4806 Regs.push_back(RegClassRegs[i]);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004807
4808 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004809 OpInfo.ConstraintVT);
4810 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4811 return;
4812 }
4813 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004814
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004815 // Otherwise, we couldn't allocate enough registers for this.
4816}
4817
Evan Chengda43bcf2008-09-24 00:05:32 +00004818/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
4819/// processed uses a memory 'm' constraint.
4820static bool
4821hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
Dan Gohmane9530ec2009-01-15 16:58:17 +00004822 const TargetLowering &TLI) {
Evan Chengda43bcf2008-09-24 00:05:32 +00004823 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
4824 InlineAsm::ConstraintInfo &CI = CInfos[i];
4825 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
4826 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
4827 if (CType == TargetLowering::C_Memory)
4828 return true;
4829 }
4830 }
4831
4832 return false;
4833}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004834
4835/// visitInlineAsm - Handle a call to an InlineAsm object.
4836///
4837void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4838 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4839
4840 /// ConstraintOperands - Information about all of the constraints.
4841 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004842
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004843 SDValue Chain = getRoot();
4844 SDValue Flag;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004845
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004846 std::set<unsigned> OutputRegs, InputRegs;
4847
4848 // Do a prepass over the constraints, canonicalizing them, and building up the
4849 // ConstraintOperands list.
4850 std::vector<InlineAsm::ConstraintInfo>
4851 ConstraintInfos = IA->ParseConstraints();
4852
Evan Chengda43bcf2008-09-24 00:05:32 +00004853 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004854
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004855 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4856 unsigned ResNo = 0; // ResNo - The result number of the next output.
4857 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4858 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4859 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004860
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004861 MVT OpVT = MVT::Other;
4862
4863 // Compute the value type for each operand.
4864 switch (OpInfo.Type) {
4865 case InlineAsm::isOutput:
4866 // Indirect outputs just consume an argument.
4867 if (OpInfo.isIndirect) {
4868 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4869 break;
4870 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004871
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004872 // The return value of the call is this value. As such, there is no
4873 // corresponding argument.
4874 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4875 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4876 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4877 } else {
4878 assert(ResNo == 0 && "Asm only has one result!");
4879 OpVT = TLI.getValueType(CS.getType());
4880 }
4881 ++ResNo;
4882 break;
4883 case InlineAsm::isInput:
4884 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4885 break;
4886 case InlineAsm::isClobber:
4887 // Nothing to do.
4888 break;
4889 }
4890
4891 // If this is an input or an indirect output, process the call argument.
4892 // BasicBlocks are labels, currently appearing only in asm's.
4893 if (OpInfo.CallOperandVal) {
Chris Lattner81249c92008-10-17 17:05:25 +00004894 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004895 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00004896 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004897 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004898 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004899
Chris Lattner81249c92008-10-17 17:05:25 +00004900 OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004901 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004902
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004903 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004904 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004905
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004906 // Second pass over the constraints: compute which constraint option to use
4907 // and assign registers to constraints that want a specific physreg.
4908 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4909 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004910
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004911 // If this is an output operand with a matching input operand, look up the
Evan Cheng09dc9c02008-12-16 18:21:39 +00004912 // matching input. If their types mismatch, e.g. one is an integer, the
4913 // other is floating point, or their sizes are different, flag it as an
4914 // error.
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004915 if (OpInfo.hasMatchingInput()) {
4916 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4917 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Evan Cheng09dc9c02008-12-16 18:21:39 +00004918 if ((OpInfo.ConstraintVT.isInteger() !=
4919 Input.ConstraintVT.isInteger()) ||
4920 (OpInfo.ConstraintVT.getSizeInBits() !=
4921 Input.ConstraintVT.getSizeInBits())) {
4922 cerr << "Unsupported asm: input constraint with a matching output "
4923 << "constraint of incompatible type!\n";
4924 exit(1);
4925 }
4926 Input.ConstraintVT = OpInfo.ConstraintVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004927 }
4928 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004929
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004930 // Compute the constraint code and ConstraintType to use.
Evan Chengda43bcf2008-09-24 00:05:32 +00004931 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004932
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004933 // If this is a memory input, and if the operand is not indirect, do what we
4934 // need to to provide an address for the memory input.
4935 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4936 !OpInfo.isIndirect) {
4937 assert(OpInfo.Type == InlineAsm::isInput &&
4938 "Can only indirectify direct input operands!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004939
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004940 // Memory operands really want the address of the value. If we don't have
4941 // an indirect input, put it in the constpool if we can, otherwise spill
4942 // it to a stack slot.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004943
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004944 // If the operand is a float, integer, or vector constant, spill to a
4945 // constant pool entry to get its address.
4946 Value *OpVal = OpInfo.CallOperandVal;
4947 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4948 isa<ConstantVector>(OpVal)) {
4949 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4950 TLI.getPointerTy());
4951 } else {
4952 // Otherwise, create a stack slot and emit a store to it before the
4953 // asm.
4954 const Type *Ty = OpVal->getType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00004955 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004956 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4957 MachineFunction &MF = DAG.getMachineFunction();
4958 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4959 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4960 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4961 OpInfo.CallOperand = StackSlot;
4962 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004963
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004964 // There is no longer a Value* corresponding to this operand.
4965 OpInfo.CallOperandVal = 0;
4966 // It is now an indirect operand.
4967 OpInfo.isIndirect = true;
4968 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004969
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004970 // If this constraint is for a specific register, allocate it before
4971 // anything else.
4972 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004973 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004974 }
4975 ConstraintInfos.clear();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004976
4977
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004978 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00004979 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004980 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4981 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004982
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004983 // C_Register operands have already been allocated, Other/Memory don't need
4984 // to be.
4985 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004986 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004987 }
4988
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004989 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4990 std::vector<SDValue> AsmNodeOperands;
4991 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
4992 AsmNodeOperands.push_back(
Bill Wendling056292f2008-09-16 21:48:12 +00004993 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004994
4995
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004996 // Loop over all of the inputs, copying the operand values into the
4997 // appropriate registers and processing the output regs.
4998 RegsForValue RetValRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004999
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005000 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5001 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005002
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005003 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5004 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5005
5006 switch (OpInfo.Type) {
5007 case InlineAsm::isOutput: {
5008 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5009 OpInfo.ConstraintType != TargetLowering::C_Register) {
5010 // Memory output, or 'other' output (e.g. 'X' constraint).
5011 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5012
5013 // Add information to the INLINEASM node to know about this output.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005014 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5015 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005016 TLI.getPointerTy()));
5017 AsmNodeOperands.push_back(OpInfo.CallOperand);
5018 break;
5019 }
5020
5021 // Otherwise, this is a register or register class output.
5022
5023 // Copy the output from the appropriate register. Find a register that
5024 // we can use.
5025 if (OpInfo.AssignedRegs.Regs.empty()) {
5026 cerr << "Couldn't allocate output reg for constraint '"
5027 << OpInfo.ConstraintCode << "'!\n";
5028 exit(1);
5029 }
5030
5031 // If this is an indirect operand, store through the pointer after the
5032 // asm.
5033 if (OpInfo.isIndirect) {
5034 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5035 OpInfo.CallOperandVal));
5036 } else {
5037 // This is the result value of the call.
5038 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5039 // Concatenate this output onto the outputs list.
5040 RetValRegs.append(OpInfo.AssignedRegs);
5041 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005042
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005043 // Add information to the INLINEASM node to know that this register is
5044 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00005045 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5046 6 /* EARLYCLOBBER REGDEF */ :
5047 2 /* REGDEF */ ,
5048 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005049 break;
5050 }
5051 case InlineAsm::isInput: {
5052 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005053
Chris Lattner6bdcda32008-10-17 16:47:46 +00005054 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005055 // If this is required to match an output register we have already set,
5056 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00005057 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005058
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005059 // Scan until we find the definition we already emitted of this operand.
5060 // When we find it, create a RegsForValue operand.
5061 unsigned CurOp = 2; // The first operand.
5062 for (; OperandNo; --OperandNo) {
5063 // Advance to the next operand.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005064 unsigned NumOps =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005065 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005066 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
Dale Johannesen913d3df2008-09-12 17:49:03 +00005067 (NumOps & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
Dale Johannesen86b49f82008-09-24 01:07:17 +00005068 (NumOps & 7) == 4 /*MEM*/) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005069 "Skipped past definitions?");
5070 CurOp += (NumOps>>3)+1;
5071 }
5072
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005073 unsigned NumOps =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005074 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005075 if ((NumOps & 7) == 2 /*REGDEF*/
Dale Johannesen913d3df2008-09-12 17:49:03 +00005076 || (NumOps & 7) == 6 /* EARLYCLOBBER REGDEF */) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005077 // Add NumOps>>3 registers to MatchedRegs.
5078 RegsForValue MatchedRegs;
5079 MatchedRegs.TLI = &TLI;
5080 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5081 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
5082 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
5083 unsigned Reg =
5084 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
5085 MatchedRegs.Regs.push_back(Reg);
5086 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005087
5088 // Use the produced MatchedRegs object to
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005089 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Dale Johannesen86b49f82008-09-24 01:07:17 +00005090 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005091 break;
5092 } else {
Dale Johannesen86b49f82008-09-24 01:07:17 +00005093 assert(((NumOps & 7) == 4) && "Unknown matching constraint!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005094 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005095 // Add information to the INLINEASM node to know about this input.
Dale Johannesen91aac102008-09-17 21:13:11 +00005096 AsmNodeOperands.push_back(DAG.getTargetConstant(NumOps,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005097 TLI.getPointerTy()));
5098 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5099 break;
5100 }
5101 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005102
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005103 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005104 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005105 "Don't know how to handle indirect other inputs yet!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005106
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005107 std::vector<SDValue> Ops;
5108 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Chengda43bcf2008-09-24 00:05:32 +00005109 hasMemory, Ops, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005110 if (Ops.empty()) {
5111 cerr << "Invalid operand for inline asm constraint '"
5112 << OpInfo.ConstraintCode << "'!\n";
5113 exit(1);
5114 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005115
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005116 // Add information to the INLINEASM node to know about this input.
5117 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005118 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005119 TLI.getPointerTy()));
5120 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5121 break;
5122 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5123 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5124 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5125 "Memory operands expect pointer values");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005126
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005127 // Add information to the INLINEASM node to know about this input.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005128 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5129 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005130 TLI.getPointerTy()));
5131 AsmNodeOperands.push_back(InOperandVal);
5132 break;
5133 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005134
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005135 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5136 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5137 "Unknown constraint type!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005138 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005139 "Don't know how to handle indirect register inputs yet!");
5140
5141 // Copy the input into the appropriate registers.
Evan Chengaa765b82008-09-25 00:14:04 +00005142 if (OpInfo.AssignedRegs.Regs.empty()) {
5143 cerr << "Couldn't allocate output reg for constraint '"
5144 << OpInfo.ConstraintCode << "'!\n";
5145 exit(1);
5146 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005147
5148 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005149
Dale Johannesen86b49f82008-09-24 01:07:17 +00005150 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/,
5151 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005152 break;
5153 }
5154 case InlineAsm::isClobber: {
5155 // Add the clobbered value to the operand list, so that the register
5156 // allocator is aware that the physreg got clobbered.
5157 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesen91aac102008-09-17 21:13:11 +00005158 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
5159 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005160 break;
5161 }
5162 }
5163 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005164
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005165 // Finish up input operands.
5166 AsmNodeOperands[0] = Chain;
5167 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005168
5169 Chain = DAG.getNode(ISD::INLINEASM,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005170 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
5171 &AsmNodeOperands[0], AsmNodeOperands.size());
5172 Flag = Chain.getValue(1);
5173
5174 // If this asm returns a register value, copy the result from that register
5175 // and set it as the value of the call.
5176 if (!RetValRegs.Regs.empty()) {
5177 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005178
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005179 // FIXME: Why don't we do this for inline asms with MRVs?
5180 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5181 MVT ResultType = TLI.getValueType(CS.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005182
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005183 // If any of the results of the inline asm is a vector, it may have the
5184 // wrong width/num elts. This can happen for register classes that can
5185 // contain multiple different value types. The preg or vreg allocated may
5186 // not have the same VT as was expected. Convert it to the right type
5187 // with bit_convert.
5188 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5189 Val = DAG.getNode(ISD::BIT_CONVERT, ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005190
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005191 } else if (ResultType != Val.getValueType() &&
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005192 ResultType.isInteger() && Val.getValueType().isInteger()) {
5193 // If a result value was tied to an input value, the computed result may
5194 // have a wider width than the expected result. Extract the relevant
5195 // portion.
5196 Val = DAG.getNode(ISD::TRUNCATE, ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005197 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005198
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005199 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00005200 }
Dan Gohman95915732008-10-18 01:03:45 +00005201
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005202 setValue(CS.getInstruction(), Val);
5203 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005204
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005205 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005206
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005207 // Process indirect outputs, first output all of the flagged copies out of
5208 // physregs.
5209 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5210 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5211 Value *Ptr = IndirectStoresToEmit[i].second;
5212 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
5213 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5214 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005215
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005216 // Emit the non-flagged stores from the physregs.
5217 SmallVector<SDValue, 8> OutChains;
5218 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5219 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
5220 getValue(StoresToEmit[i].second),
5221 StoresToEmit[i].second, 0));
5222 if (!OutChains.empty())
5223 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5224 &OutChains[0], OutChains.size());
5225 DAG.setRoot(Chain);
5226}
5227
5228
5229void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5230 SDValue Src = getValue(I.getOperand(0));
5231
5232 MVT IntPtr = TLI.getPointerTy();
5233
5234 if (IntPtr.bitsLT(Src.getValueType()))
5235 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
5236 else if (IntPtr.bitsGT(Src.getValueType()))
5237 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
5238
5239 // Scale the source by the type size.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005240 uint64_t ElementSize = TD->getTypePaddedSize(I.getType()->getElementType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005241 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
5242 Src, DAG.getIntPtrConstant(ElementSize));
5243
5244 TargetLowering::ArgListTy Args;
5245 TargetLowering::ArgListEntry Entry;
5246 Entry.Node = Src;
5247 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5248 Args.push_back(Entry);
5249
5250 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005251 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005252 CallingConv::C, PerformTailCallOpt,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005253 DAG.getExternalSymbol("malloc", IntPtr),
Dan Gohman1937e2f2008-09-16 01:42:28 +00005254 Args, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005255 setValue(&I, Result.first); // Pointers always fit in registers
5256 DAG.setRoot(Result.second);
5257}
5258
5259void SelectionDAGLowering::visitFree(FreeInst &I) {
5260 TargetLowering::ArgListTy Args;
5261 TargetLowering::ArgListEntry Entry;
5262 Entry.Node = getValue(I.getOperand(0));
5263 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5264 Args.push_back(Entry);
5265 MVT IntPtr = TLI.getPointerTy();
5266 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005267 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
Dan Gohman1937e2f2008-09-16 01:42:28 +00005268 CallingConv::C, PerformTailCallOpt,
Bill Wendling056292f2008-09-16 21:48:12 +00005269 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005270 DAG.setRoot(Result.second);
5271}
5272
5273void SelectionDAGLowering::visitVAStart(CallInst &I) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005274 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
5275 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005276 DAG.getSrcValue(I.getOperand(1))));
5277}
5278
5279void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
5280 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
5281 getValue(I.getOperand(0)),
5282 DAG.getSrcValue(I.getOperand(0)));
5283 setValue(&I, V);
5284 DAG.setRoot(V.getValue(1));
5285}
5286
5287void SelectionDAGLowering::visitVAEnd(CallInst &I) {
5288 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005289 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005290 DAG.getSrcValue(I.getOperand(1))));
5291}
5292
5293void SelectionDAGLowering::visitVACopy(CallInst &I) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005294 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
5295 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005296 getValue(I.getOperand(2)),
5297 DAG.getSrcValue(I.getOperand(1)),
5298 DAG.getSrcValue(I.getOperand(2))));
5299}
5300
5301/// TargetLowering::LowerArguments - This is the default LowerArguments
5302/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005303/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005304/// integrated into SDISel.
5305void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
5306 SmallVectorImpl<SDValue> &ArgValues) {
5307 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5308 SmallVector<SDValue, 3+16> Ops;
5309 Ops.push_back(DAG.getRoot());
5310 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5311 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5312
5313 // Add one result value for each formal argument.
5314 SmallVector<MVT, 16> RetVals;
5315 unsigned j = 1;
5316 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5317 I != E; ++I, ++j) {
5318 SmallVector<MVT, 4> ValueVTs;
5319 ComputeValueVTs(*this, I->getType(), ValueVTs);
5320 for (unsigned Value = 0, NumValues = ValueVTs.size();
5321 Value != NumValues; ++Value) {
5322 MVT VT = ValueVTs[Value];
5323 const Type *ArgTy = VT.getTypeForMVT();
5324 ISD::ArgFlagsTy Flags;
5325 unsigned OriginalAlignment =
5326 getTargetData()->getABITypeAlignment(ArgTy);
5327
Devang Patel05988662008-09-25 21:00:45 +00005328 if (F.paramHasAttr(j, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005329 Flags.setZExt();
Devang Patel05988662008-09-25 21:00:45 +00005330 if (F.paramHasAttr(j, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005331 Flags.setSExt();
Devang Patel05988662008-09-25 21:00:45 +00005332 if (F.paramHasAttr(j, Attribute::InReg))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005333 Flags.setInReg();
Devang Patel05988662008-09-25 21:00:45 +00005334 if (F.paramHasAttr(j, Attribute::StructRet))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005335 Flags.setSRet();
Devang Patel05988662008-09-25 21:00:45 +00005336 if (F.paramHasAttr(j, Attribute::ByVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005337 Flags.setByVal();
5338 const PointerType *Ty = cast<PointerType>(I->getType());
5339 const Type *ElementTy = Ty->getElementType();
5340 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005341 unsigned FrameSize = getTargetData()->getTypePaddedSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005342 // For ByVal, alignment should be passed from FE. BE will guess if
5343 // this info is not there but there are cases it cannot get right.
5344 if (F.getParamAlignment(j))
5345 FrameAlign = F.getParamAlignment(j);
5346 Flags.setByValAlign(FrameAlign);
5347 Flags.setByValSize(FrameSize);
5348 }
Devang Patel05988662008-09-25 21:00:45 +00005349 if (F.paramHasAttr(j, Attribute::Nest))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005350 Flags.setNest();
5351 Flags.setOrigAlign(OriginalAlignment);
5352
5353 MVT RegisterVT = getRegisterType(VT);
5354 unsigned NumRegs = getNumRegisters(VT);
5355 for (unsigned i = 0; i != NumRegs; ++i) {
5356 RetVals.push_back(RegisterVT);
5357 ISD::ArgFlagsTy MyFlags = Flags;
5358 if (NumRegs > 1 && i == 0)
5359 MyFlags.setSplit();
5360 // if it isn't first piece, alignment must be 1
5361 else if (i > 0)
5362 MyFlags.setOrigAlign(1);
5363 Ops.push_back(DAG.getArgFlags(MyFlags));
5364 }
5365 }
5366 }
5367
5368 RetVals.push_back(MVT::Other);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005369
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005370 // Create the node.
5371 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
5372 DAG.getVTList(&RetVals[0], RetVals.size()),
5373 &Ops[0], Ops.size()).getNode();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005374
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005375 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5376 // allows exposing the loads that may be part of the argument access to the
5377 // first DAGCombiner pass.
5378 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005379
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005380 // The number of results should match up, except that the lowered one may have
5381 // an extra flag result.
5382 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5383 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5384 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5385 && "Lowering produced unexpected number of results!");
5386
5387 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5388 if (Result != TmpRes.getNode() && Result->use_empty()) {
5389 HandleSDNode Dummy(DAG.getRoot());
5390 DAG.RemoveDeadNode(Result);
5391 }
5392
5393 Result = TmpRes.getNode();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005394
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005395 unsigned NumArgRegs = Result->getNumValues() - 1;
5396 DAG.setRoot(SDValue(Result, NumArgRegs));
5397
5398 // Set up the return result vector.
5399 unsigned i = 0;
5400 unsigned Idx = 1;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005401 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005402 ++I, ++Idx) {
5403 SmallVector<MVT, 4> ValueVTs;
5404 ComputeValueVTs(*this, I->getType(), ValueVTs);
5405 for (unsigned Value = 0, NumValues = ValueVTs.size();
5406 Value != NumValues; ++Value) {
5407 MVT VT = ValueVTs[Value];
5408 MVT PartVT = getRegisterType(VT);
5409
5410 unsigned NumParts = getNumRegisters(VT);
5411 SmallVector<SDValue, 4> Parts(NumParts);
5412 for (unsigned j = 0; j != NumParts; ++j)
5413 Parts[j] = SDValue(Result, i++);
5414
5415 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Devang Patel05988662008-09-25 21:00:45 +00005416 if (F.paramHasAttr(Idx, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005417 AssertOp = ISD::AssertSext;
Devang Patel05988662008-09-25 21:00:45 +00005418 else if (F.paramHasAttr(Idx, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005419 AssertOp = ISD::AssertZext;
5420
5421 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
5422 AssertOp));
5423 }
5424 }
5425 assert(i == NumArgRegs && "Argument register count mismatch!");
5426}
5427
5428
5429/// TargetLowering::LowerCallTo - This is the default LowerCallTo
5430/// implementation, which just inserts an ISD::CALL node, which is later custom
5431/// lowered by the target to something concrete. FIXME: When all targets are
5432/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5433std::pair<SDValue, SDValue>
5434TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5435 bool RetSExt, bool RetZExt, bool isVarArg,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005436 bool isInreg,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005437 unsigned CallingConv, bool isTailCall,
5438 SDValue Callee,
5439 ArgListTy &Args, SelectionDAG &DAG) {
Dan Gohman1937e2f2008-09-16 01:42:28 +00005440 assert((!isTailCall || PerformTailCallOpt) &&
5441 "isTailCall set when tail-call optimizations are disabled!");
5442
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005443 SmallVector<SDValue, 32> Ops;
5444 Ops.push_back(Chain); // Op#0 - Chain
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005445 Ops.push_back(Callee);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005446
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005447 // Handle all of the outgoing arguments.
5448 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5449 SmallVector<MVT, 4> ValueVTs;
5450 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5451 for (unsigned Value = 0, NumValues = ValueVTs.size();
5452 Value != NumValues; ++Value) {
5453 MVT VT = ValueVTs[Value];
5454 const Type *ArgTy = VT.getTypeForMVT();
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005455 SDValue Op = SDValue(Args[i].Node.getNode(),
5456 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005457 ISD::ArgFlagsTy Flags;
5458 unsigned OriginalAlignment =
5459 getTargetData()->getABITypeAlignment(ArgTy);
5460
5461 if (Args[i].isZExt)
5462 Flags.setZExt();
5463 if (Args[i].isSExt)
5464 Flags.setSExt();
5465 if (Args[i].isInReg)
5466 Flags.setInReg();
5467 if (Args[i].isSRet)
5468 Flags.setSRet();
5469 if (Args[i].isByVal) {
5470 Flags.setByVal();
5471 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5472 const Type *ElementTy = Ty->getElementType();
5473 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005474 unsigned FrameSize = getTargetData()->getTypePaddedSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005475 // For ByVal, alignment should come from FE. BE will guess if this
5476 // info is not there but there are cases it cannot get right.
5477 if (Args[i].Alignment)
5478 FrameAlign = Args[i].Alignment;
5479 Flags.setByValAlign(FrameAlign);
5480 Flags.setByValSize(FrameSize);
5481 }
5482 if (Args[i].isNest)
5483 Flags.setNest();
5484 Flags.setOrigAlign(OriginalAlignment);
5485
5486 MVT PartVT = getRegisterType(VT);
5487 unsigned NumParts = getNumRegisters(VT);
5488 SmallVector<SDValue, 4> Parts(NumParts);
5489 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5490
5491 if (Args[i].isSExt)
5492 ExtendKind = ISD::SIGN_EXTEND;
5493 else if (Args[i].isZExt)
5494 ExtendKind = ISD::ZERO_EXTEND;
5495
5496 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5497
5498 for (unsigned i = 0; i != NumParts; ++i) {
5499 // if it isn't first piece, alignment must be 1
5500 ISD::ArgFlagsTy MyFlags = Flags;
5501 if (NumParts > 1 && i == 0)
5502 MyFlags.setSplit();
5503 else if (i != 0)
5504 MyFlags.setOrigAlign(1);
5505
5506 Ops.push_back(Parts[i]);
5507 Ops.push_back(DAG.getArgFlags(MyFlags));
5508 }
5509 }
5510 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005511
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005512 // Figure out the result value types. We start by making a list of
5513 // the potentially illegal return value types.
5514 SmallVector<MVT, 4> LoweredRetTys;
5515 SmallVector<MVT, 4> RetTys;
5516 ComputeValueVTs(*this, RetTy, RetTys);
5517
5518 // Then we translate that to a list of legal types.
5519 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5520 MVT VT = RetTys[I];
5521 MVT RegisterVT = getRegisterType(VT);
5522 unsigned NumRegs = getNumRegisters(VT);
5523 for (unsigned i = 0; i != NumRegs; ++i)
5524 LoweredRetTys.push_back(RegisterVT);
5525 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005526
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005527 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005528
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005529 // Create the CALL node.
Dale Johannesen86098bd2008-09-26 19:31:26 +00005530 SDValue Res = DAG.getCall(CallingConv, isVarArg, isTailCall, isInreg,
Dan Gohman095cc292008-09-13 01:54:27 +00005531 DAG.getVTList(&LoweredRetTys[0],
5532 LoweredRetTys.size()),
Dale Johannesen86098bd2008-09-26 19:31:26 +00005533 &Ops[0], Ops.size()
5534 );
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005535 Chain = Res.getValue(LoweredRetTys.size() - 1);
5536
5537 // Gather up the call result into a single value.
Dan Gohmanb5cc34d2008-10-07 00:12:37 +00005538 if (RetTy != Type::VoidTy && !RetTys.empty()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005539 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5540
5541 if (RetSExt)
5542 AssertOp = ISD::AssertSext;
5543 else if (RetZExt)
5544 AssertOp = ISD::AssertZext;
5545
5546 SmallVector<SDValue, 4> ReturnValues;
5547 unsigned RegNo = 0;
5548 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5549 MVT VT = RetTys[I];
5550 MVT RegisterVT = getRegisterType(VT);
5551 unsigned NumRegs = getNumRegisters(VT);
5552 unsigned RegNoEnd = NumRegs + RegNo;
5553 SmallVector<SDValue, 4> Results;
5554 for (; RegNo != RegNoEnd; ++RegNo)
5555 Results.push_back(Res.getValue(RegNo));
5556 SDValue ReturnValue =
5557 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
5558 AssertOp);
5559 ReturnValues.push_back(ReturnValue);
5560 }
Duncan Sandsaaffa052008-12-01 11:41:29 +00005561 Res = DAG.getNode(ISD::MERGE_VALUES,
5562 DAG.getVTList(&RetTys[0], RetTys.size()),
5563 &ReturnValues[0], ReturnValues.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005564 }
5565
5566 return std::make_pair(Res, Chain);
5567}
5568
Duncan Sands9fbc7e22009-01-21 09:00:29 +00005569void TargetLowering::LowerOperationWrapper(SDNode *N,
5570 SmallVectorImpl<SDValue> &Results,
5571 SelectionDAG &DAG) {
5572 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptabb326bb2009-01-21 04:48:39 +00005573 if (Res.getNode())
5574 Results.push_back(Res);
5575}
5576
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005577SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5578 assert(0 && "LowerOperation not implemented for this target!");
5579 abort();
5580 return SDValue();
5581}
5582
5583
5584void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5585 SDValue Op = getValue(V);
5586 assert((Op.getOpcode() != ISD::CopyFromReg ||
5587 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5588 "Copy from a reg to the same reg!");
5589 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5590
5591 RegsForValue RFV(TLI, Reg, V->getType());
5592 SDValue Chain = DAG.getEntryNode();
5593 RFV.getCopyToRegs(Op, DAG, Chain, 0);
5594 PendingExports.push_back(Chain);
5595}
5596
5597#include "llvm/CodeGen/SelectionDAGISel.h"
5598
5599void SelectionDAGISel::
5600LowerArguments(BasicBlock *LLVMBB) {
5601 // If this is the entry block, emit arguments.
5602 Function &F = *LLVMBB->getParent();
5603 SDValue OldRoot = SDL->DAG.getRoot();
5604 SmallVector<SDValue, 16> Args;
5605 TLI.LowerArguments(F, SDL->DAG, Args);
5606
5607 unsigned a = 0;
5608 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5609 AI != E; ++AI) {
5610 SmallVector<MVT, 4> ValueVTs;
5611 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5612 unsigned NumValues = ValueVTs.size();
5613 if (!AI->use_empty()) {
5614 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues));
5615 // If this argument is live outside of the entry block, insert a copy from
5616 // whereever we got it to the vreg that other BB's will reference it as.
5617 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5618 if (VMI != FuncInfo->ValueMap.end()) {
5619 SDL->CopyValueToVirtualRegister(AI, VMI->second);
5620 }
5621 }
5622 a += NumValues;
5623 }
5624
5625 // Finally, if the target has anything special to do, allow it to do so.
5626 // FIXME: this should insert code into the DAG!
5627 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5628}
5629
5630/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5631/// ensure constants are generated when needed. Remember the virtual registers
5632/// that need to be added to the Machine PHI nodes as input. We cannot just
5633/// directly add them, because expansion might result in multiple MBB's for one
5634/// BB. As such, the start of the BB might correspond to a different MBB than
5635/// the end.
5636///
5637void
5638SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5639 TerminatorInst *TI = LLVMBB->getTerminator();
5640
5641 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5642
5643 // Check successor nodes' PHI nodes that expect a constant to be available
5644 // from this block.
5645 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5646 BasicBlock *SuccBB = TI->getSuccessor(succ);
5647 if (!isa<PHINode>(SuccBB->begin())) continue;
5648 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005649
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005650 // If this terminator has multiple identical successors (common for
5651 // switches), only handle each succ once.
5652 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005653
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005654 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5655 PHINode *PN;
5656
5657 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5658 // nodes and Machine PHI nodes, but the incoming operands have not been
5659 // emitted yet.
5660 for (BasicBlock::iterator I = SuccBB->begin();
5661 (PN = dyn_cast<PHINode>(I)); ++I) {
5662 // Ignore dead phi's.
5663 if (PN->use_empty()) continue;
5664
5665 unsigned Reg;
5666 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5667
5668 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5669 unsigned &RegOut = SDL->ConstantsOut[C];
5670 if (RegOut == 0) {
5671 RegOut = FuncInfo->CreateRegForValue(C);
5672 SDL->CopyValueToVirtualRegister(C, RegOut);
5673 }
5674 Reg = RegOut;
5675 } else {
5676 Reg = FuncInfo->ValueMap[PHIOp];
5677 if (Reg == 0) {
5678 assert(isa<AllocaInst>(PHIOp) &&
5679 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5680 "Didn't codegen value into a register!??");
5681 Reg = FuncInfo->CreateRegForValue(PHIOp);
5682 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5683 }
5684 }
5685
5686 // Remember that this register needs to added to the machine PHI node as
5687 // the input for this MBB.
5688 SmallVector<MVT, 4> ValueVTs;
5689 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5690 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5691 MVT VT = ValueVTs[vti];
5692 unsigned NumRegisters = TLI.getNumRegisters(VT);
5693 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5694 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5695 Reg += NumRegisters;
5696 }
5697 }
5698 }
5699 SDL->ConstantsOut.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005700}
5701
Dan Gohman3df24e62008-09-03 23:12:08 +00005702/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5703/// supports legal types, and it emits MachineInstrs directly instead of
5704/// creating SelectionDAG nodes.
5705///
5706bool
5707SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5708 FastISel *F) {
5709 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005710
Dan Gohman3df24e62008-09-03 23:12:08 +00005711 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5712 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5713
5714 // Check successor nodes' PHI nodes that expect a constant to be available
5715 // from this block.
5716 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5717 BasicBlock *SuccBB = TI->getSuccessor(succ);
5718 if (!isa<PHINode>(SuccBB->begin())) continue;
5719 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005720
Dan Gohman3df24e62008-09-03 23:12:08 +00005721 // If this terminator has multiple identical successors (common for
5722 // switches), only handle each succ once.
5723 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005724
Dan Gohman3df24e62008-09-03 23:12:08 +00005725 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5726 PHINode *PN;
5727
5728 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5729 // nodes and Machine PHI nodes, but the incoming operands have not been
5730 // emitted yet.
5731 for (BasicBlock::iterator I = SuccBB->begin();
5732 (PN = dyn_cast<PHINode>(I)); ++I) {
5733 // Ignore dead phi's.
5734 if (PN->use_empty()) continue;
5735
5736 // Only handle legal types. Two interesting things to note here. First,
5737 // by bailing out early, we may leave behind some dead instructions,
5738 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5739 // own moves. Second, this check is necessary becuase FastISel doesn't
5740 // use CreateRegForValue to create registers, so it always creates
5741 // exactly one register for each non-void instruction.
5742 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5743 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
Dan Gohman74321ab2008-09-10 21:01:31 +00005744 // Promote MVT::i1.
5745 if (VT == MVT::i1)
5746 VT = TLI.getTypeToTransformTo(VT);
5747 else {
5748 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5749 return false;
5750 }
Dan Gohman3df24e62008-09-03 23:12:08 +00005751 }
5752
5753 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5754
5755 unsigned Reg = F->getRegForValue(PHIOp);
5756 if (Reg == 0) {
5757 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5758 return false;
5759 }
5760 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
5761 }
5762 }
5763
5764 return true;
5765}