blob: a0154cb0a0d4c85ca74fdb9c607984088e08d0d9 [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).
Duncan Sands0b3aa262009-01-28 14:42:54 +0000377static SDValue getCopyFromParts(SelectionDAG &DAG, const SDValue *Parts,
378 unsigned NumParts, MVT PartVT, MVT ValueVT,
379 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000380 assert(NumParts > 0 && "No parts to assemble!");
Dan Gohmane9530ec2009-01-15 16:58:17 +0000381 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000382 SDValue Val = Parts[0];
383
384 if (NumParts > 1) {
385 // Assemble the value from multiple parts.
386 if (!ValueVT.isVector()) {
387 unsigned PartBits = PartVT.getSizeInBits();
388 unsigned ValueBits = ValueVT.getSizeInBits();
389
390 // Assemble the power of 2 part.
391 unsigned RoundParts = NumParts & (NumParts - 1) ?
392 1 << Log2_32(NumParts) : NumParts;
393 unsigned RoundBits = PartBits * RoundParts;
394 MVT RoundVT = RoundBits == ValueBits ?
395 ValueVT : MVT::getIntegerVT(RoundBits);
396 SDValue Lo, Hi;
397
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000398 MVT HalfVT = ValueVT.isInteger() ?
399 MVT::getIntegerVT(RoundBits/2) :
400 MVT::getFloatingPointVT(RoundBits/2);
401
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000402 if (RoundParts > 2) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000403 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
404 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
405 PartVT, HalfVT);
406 } else {
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000407 Lo = DAG.getNode(ISD::BIT_CONVERT, HalfVT, Parts[0]);
408 Hi = DAG.getNode(ISD::BIT_CONVERT, HalfVT, Parts[1]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000409 }
410 if (TLI.isBigEndian())
411 std::swap(Lo, Hi);
412 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
413
414 if (RoundParts < NumParts) {
415 // Assemble the trailing non-power-of-2 part.
416 unsigned OddParts = NumParts - RoundParts;
417 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
418 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
419
420 // Combine the round and odd parts.
421 Lo = Val;
422 if (TLI.isBigEndian())
423 std::swap(Lo, Hi);
424 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
425 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
426 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
427 DAG.getConstant(Lo.getValueType().getSizeInBits(),
428 TLI.getShiftAmountTy()));
429 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
430 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
431 }
432 } else {
433 // Handle a multi-element vector.
434 MVT IntermediateVT, RegisterVT;
435 unsigned NumIntermediates;
436 unsigned NumRegs =
437 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
438 RegisterVT);
439 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
440 NumParts = NumRegs; // Silence a compiler warning.
441 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
442 assert(RegisterVT == Parts[0].getValueType() &&
443 "Part type doesn't match part!");
444
445 // Assemble the parts into intermediate operands.
446 SmallVector<SDValue, 8> Ops(NumIntermediates);
447 if (NumIntermediates == NumParts) {
448 // If the register was not expanded, truncate or copy the value,
449 // as appropriate.
450 for (unsigned i = 0; i != NumParts; ++i)
451 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
452 PartVT, IntermediateVT);
453 } else if (NumParts > 0) {
454 // If the intermediate type was expanded, build the intermediate operands
455 // from the parts.
456 assert(NumParts % NumIntermediates == 0 &&
457 "Must expand into a divisible number of parts!");
458 unsigned Factor = NumParts / NumIntermediates;
459 for (unsigned i = 0; i != NumIntermediates; ++i)
460 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
461 PartVT, IntermediateVT);
462 }
463
464 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
465 // operands.
466 Val = DAG.getNode(IntermediateVT.isVector() ?
467 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
468 ValueVT, &Ops[0], NumIntermediates);
469 }
470 }
471
472 // There is now one part, held in Val. Correct it to match ValueVT.
473 PartVT = Val.getValueType();
474
475 if (PartVT == ValueVT)
476 return Val;
477
478 if (PartVT.isVector()) {
479 assert(ValueVT.isVector() && "Unknown vector conversion!");
480 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
481 }
482
483 if (ValueVT.isVector()) {
484 assert(ValueVT.getVectorElementType() == PartVT &&
485 ValueVT.getVectorNumElements() == 1 &&
486 "Only trivial scalar-to-vector conversions should get here!");
487 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
488 }
489
490 if (PartVT.isInteger() &&
491 ValueVT.isInteger()) {
492 if (ValueVT.bitsLT(PartVT)) {
493 // For a truncate, see if we have any information to
494 // indicate whether the truncated bits will always be
495 // zero or sign-extension.
496 if (AssertOp != ISD::DELETED_NODE)
497 Val = DAG.getNode(AssertOp, PartVT, Val,
498 DAG.getValueType(ValueVT));
499 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
500 } else {
501 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
502 }
503 }
504
505 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
506 if (ValueVT.bitsLT(Val.getValueType()))
507 // FP_ROUND's are always exact here.
508 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
509 DAG.getIntPtrConstant(1));
510 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
511 }
512
513 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
514 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
515
516 assert(0 && "Unknown mismatch!");
517 return SDValue();
518}
519
520/// getCopyToParts - Create a series of nodes that contain the specified value
521/// split into legal parts. If the parts contain more bits than Val, then, for
522/// integers, ExtendKind can be used to specify how to generate the extra bits.
Chris Lattner01426e12008-10-21 00:45:36 +0000523static void getCopyToParts(SelectionDAG &DAG, SDValue Val,
524 SDValue *Parts, unsigned NumParts, MVT PartVT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000525 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohmane9530ec2009-01-15 16:58:17 +0000526 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000527 MVT PtrVT = TLI.getPointerTy();
528 MVT ValueVT = Val.getValueType();
529 unsigned PartBits = PartVT.getSizeInBits();
530 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
531
532 if (!NumParts)
533 return;
534
535 if (!ValueVT.isVector()) {
536 if (PartVT == ValueVT) {
537 assert(NumParts == 1 && "No-op copy with multiple parts!");
538 Parts[0] = Val;
539 return;
540 }
541
542 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
543 // If the parts cover more bits than the value has, promote the value.
544 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
545 assert(NumParts == 1 && "Do not know what to promote to!");
546 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
547 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
548 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
549 Val = DAG.getNode(ExtendKind, ValueVT, Val);
550 } else {
551 assert(0 && "Unknown mismatch!");
552 }
553 } else if (PartBits == ValueVT.getSizeInBits()) {
554 // Different types of the same size.
555 assert(NumParts == 1 && PartVT != ValueVT);
556 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
557 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
558 // If the parts cover less bits than value has, truncate the value.
559 if (PartVT.isInteger() && ValueVT.isInteger()) {
560 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
561 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
562 } else {
563 assert(0 && "Unknown mismatch!");
564 }
565 }
566
567 // The value may have changed - recompute ValueVT.
568 ValueVT = Val.getValueType();
569 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
570 "Failed to tile the value with PartVT!");
571
572 if (NumParts == 1) {
573 assert(PartVT == ValueVT && "Type conversion failed!");
574 Parts[0] = Val;
575 return;
576 }
577
578 // Expand the value into multiple parts.
579 if (NumParts & (NumParts - 1)) {
580 // The number of parts is not a power of 2. Split off and copy the tail.
581 assert(PartVT.isInteger() && ValueVT.isInteger() &&
582 "Do not know what to expand to!");
583 unsigned RoundParts = 1 << Log2_32(NumParts);
584 unsigned RoundBits = RoundParts * PartBits;
585 unsigned OddParts = NumParts - RoundParts;
586 SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000587 DAG.getConstant(RoundBits,
588 TLI.getShiftAmountTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000589 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
590 if (TLI.isBigEndian())
591 // The odd parts were reversed by getCopyToParts - unreverse them.
592 std::reverse(Parts + RoundParts, Parts + NumParts);
593 NumParts = RoundParts;
594 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
595 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
596 }
597
598 // The number of parts is a power of 2. Repeatedly bisect the value using
599 // EXTRACT_ELEMENT.
600 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
601 MVT::getIntegerVT(ValueVT.getSizeInBits()),
602 Val);
603 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
604 for (unsigned i = 0; i < NumParts; i += StepSize) {
605 unsigned ThisBits = StepSize * PartBits / 2;
606 MVT ThisVT = MVT::getIntegerVT (ThisBits);
607 SDValue &Part0 = Parts[i];
608 SDValue &Part1 = Parts[i+StepSize/2];
609
610 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
611 DAG.getConstant(1, PtrVT));
612 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
613 DAG.getConstant(0, PtrVT));
614
615 if (ThisBits == PartBits && ThisVT != PartVT) {
616 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
617 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
618 }
619 }
620 }
621
622 if (TLI.isBigEndian())
623 std::reverse(Parts, Parts + NumParts);
624
625 return;
626 }
627
628 // Vector ValueVT.
629 if (NumParts == 1) {
630 if (PartVT != ValueVT) {
631 if (PartVT.isVector()) {
632 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
633 } else {
634 assert(ValueVT.getVectorElementType() == PartVT &&
635 ValueVT.getVectorNumElements() == 1 &&
636 "Only trivial vector-to-scalar conversions should get here!");
637 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
638 DAG.getConstant(0, PtrVT));
639 }
640 }
641
642 Parts[0] = Val;
643 return;
644 }
645
646 // Handle a multi-element vector.
647 MVT IntermediateVT, RegisterVT;
648 unsigned NumIntermediates;
Dan Gohmane9530ec2009-01-15 16:58:17 +0000649 unsigned NumRegs = TLI
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000650 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
651 RegisterVT);
652 unsigned NumElements = ValueVT.getVectorNumElements();
653
654 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
655 NumParts = NumRegs; // Silence a compiler warning.
656 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
657
658 // Split the vector into intermediate operands.
659 SmallVector<SDValue, 8> Ops(NumIntermediates);
660 for (unsigned i = 0; i != NumIntermediates; ++i)
661 if (IntermediateVT.isVector())
662 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
663 IntermediateVT, Val,
664 DAG.getConstant(i * (NumElements / NumIntermediates),
665 PtrVT));
666 else
667 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000668 IntermediateVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000669 DAG.getConstant(i, PtrVT));
670
671 // Split the intermediate operands into legal parts.
672 if (NumParts == NumIntermediates) {
673 // If the register was not expanded, promote or copy the value,
674 // as appropriate.
675 for (unsigned i = 0; i != NumParts; ++i)
676 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
677 } else if (NumParts > 0) {
678 // If the intermediate type was expanded, split each the value into
679 // legal parts.
680 assert(NumParts % NumIntermediates == 0 &&
681 "Must expand into a divisible number of parts!");
682 unsigned Factor = NumParts / NumIntermediates;
683 for (unsigned i = 0; i != NumIntermediates; ++i)
684 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
685 }
686}
687
688
689void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
690 AA = &aa;
691 GFI = gfi;
692 TD = DAG.getTarget().getTargetData();
693}
694
695/// clear - Clear out the curret SelectionDAG and the associated
696/// state and prepare this SelectionDAGLowering object to be used
697/// for a new block. This doesn't clear out information about
698/// additional blocks that are needed to complete switch lowering
699/// or PHI node updating; that information is cleared out as it is
700/// consumed.
701void SelectionDAGLowering::clear() {
702 NodeMap.clear();
703 PendingLoads.clear();
704 PendingExports.clear();
705 DAG.clear();
706}
707
708/// getRoot - Return the current virtual root of the Selection DAG,
709/// flushing any PendingLoad items. This must be done before emitting
710/// a store or any other node that may need to be ordered after any
711/// prior load instructions.
712///
713SDValue SelectionDAGLowering::getRoot() {
714 if (PendingLoads.empty())
715 return DAG.getRoot();
716
717 if (PendingLoads.size() == 1) {
718 SDValue Root = PendingLoads[0];
719 DAG.setRoot(Root);
720 PendingLoads.clear();
721 return Root;
722 }
723
724 // Otherwise, we have to make a token factor node.
725 SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
726 &PendingLoads[0], PendingLoads.size());
727 PendingLoads.clear();
728 DAG.setRoot(Root);
729 return Root;
730}
731
732/// getControlRoot - Similar to getRoot, but instead of flushing all the
733/// PendingLoad items, flush all the PendingExports items. It is necessary
734/// to do this before emitting a terminator instruction.
735///
736SDValue SelectionDAGLowering::getControlRoot() {
737 SDValue Root = DAG.getRoot();
738
739 if (PendingExports.empty())
740 return Root;
741
742 // Turn all of the CopyToReg chains into one factored node.
743 if (Root.getOpcode() != ISD::EntryToken) {
744 unsigned i = 0, e = PendingExports.size();
745 for (; i != e; ++i) {
746 assert(PendingExports[i].getNode()->getNumOperands() > 1);
747 if (PendingExports[i].getNode()->getOperand(0) == Root)
748 break; // Don't add the root if we already indirectly depend on it.
749 }
750
751 if (i == e)
752 PendingExports.push_back(Root);
753 }
754
755 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
756 &PendingExports[0],
757 PendingExports.size());
758 PendingExports.clear();
759 DAG.setRoot(Root);
760 return Root;
761}
762
763void SelectionDAGLowering::visit(Instruction &I) {
764 visit(I.getOpcode(), I);
765}
766
767void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
768 // Note: this doesn't use InstVisitor, because it has to work with
769 // ConstantExpr's in addition to instructions.
770 switch (Opcode) {
771 default: assert(0 && "Unknown instruction type encountered!");
772 abort();
773 // Build the switch statement using the Instruction.def file.
774#define HANDLE_INST(NUM, OPCODE, CLASS) \
775 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
776#include "llvm/Instruction.def"
777 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000778}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000779
780void SelectionDAGLowering::visitAdd(User &I) {
781 if (I.getType()->isFPOrFPVector())
782 visitBinary(I, ISD::FADD);
783 else
784 visitBinary(I, ISD::ADD);
785}
786
787void SelectionDAGLowering::visitMul(User &I) {
788 if (I.getType()->isFPOrFPVector())
789 visitBinary(I, ISD::FMUL);
790 else
791 visitBinary(I, ISD::MUL);
792}
793
794SDValue SelectionDAGLowering::getValue(const Value *V) {
795 SDValue &N = NodeMap[V];
796 if (N.getNode()) return N;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000797
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000798 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
799 MVT VT = TLI.getValueType(V->getType(), true);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000800
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000801 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000802 return N = DAG.getConstant(*CI, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000803
804 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
805 return N = DAG.getGlobalAddress(GV, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000806
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000807 if (isa<ConstantPointerNull>(C))
808 return N = DAG.getConstant(0, TLI.getPointerTy());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000809
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000810 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000811 return N = DAG.getConstantFP(*CFP, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000812
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000813 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
814 !V->getType()->isAggregateType())
815 return N = DAG.getNode(ISD::UNDEF, VT);
816
817 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
818 visit(CE->getOpcode(), *CE);
819 SDValue N1 = NodeMap[V];
820 assert(N1.getNode() && "visit didn't populate the ValueMap!");
821 return N1;
822 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000823
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000824 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
825 SmallVector<SDValue, 4> Constants;
826 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
827 OI != OE; ++OI) {
828 SDNode *Val = getValue(*OI).getNode();
829 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
830 Constants.push_back(SDValue(Val, i));
831 }
832 return DAG.getMergeValues(&Constants[0], Constants.size());
833 }
834
835 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
836 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
837 "Unknown struct or array constant!");
838
839 SmallVector<MVT, 4> ValueVTs;
840 ComputeValueVTs(TLI, C->getType(), ValueVTs);
841 unsigned NumElts = ValueVTs.size();
842 if (NumElts == 0)
843 return SDValue(); // empty struct
844 SmallVector<SDValue, 4> Constants(NumElts);
845 for (unsigned i = 0; i != NumElts; ++i) {
846 MVT EltVT = ValueVTs[i];
847 if (isa<UndefValue>(C))
848 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
849 else if (EltVT.isFloatingPoint())
850 Constants[i] = DAG.getConstantFP(0, EltVT);
851 else
852 Constants[i] = DAG.getConstant(0, EltVT);
853 }
854 return DAG.getMergeValues(&Constants[0], NumElts);
855 }
856
857 const VectorType *VecTy = cast<VectorType>(V->getType());
858 unsigned NumElements = VecTy->getNumElements();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000859
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000860 // Now that we know the number and type of the elements, get that number of
861 // elements into the Ops array based on what kind of constant it is.
862 SmallVector<SDValue, 16> Ops;
863 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
864 for (unsigned i = 0; i != NumElements; ++i)
865 Ops.push_back(getValue(CP->getOperand(i)));
866 } else {
867 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
868 "Unknown vector constant!");
869 MVT EltVT = TLI.getValueType(VecTy->getElementType());
870
871 SDValue Op;
872 if (isa<UndefValue>(C))
873 Op = DAG.getNode(ISD::UNDEF, EltVT);
874 else if (EltVT.isFloatingPoint())
875 Op = DAG.getConstantFP(0, EltVT);
876 else
877 Op = DAG.getConstant(0, EltVT);
878 Ops.assign(NumElements, Op);
879 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000880
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000881 // Create a BUILD_VECTOR node.
882 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
883 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000884
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000885 // If this is a static alloca, generate it as the frameindex instead of
886 // computation.
887 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
888 DenseMap<const AllocaInst*, int>::iterator SI =
889 FuncInfo.StaticAllocaMap.find(AI);
890 if (SI != FuncInfo.StaticAllocaMap.end())
891 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
892 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000893
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000894 unsigned InReg = FuncInfo.ValueMap[V];
895 assert(InReg && "Value not in map!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000896
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000897 RegsForValue RFV(TLI, InReg, V->getType());
898 SDValue Chain = DAG.getEntryNode();
899 return RFV.getCopyFromRegs(DAG, Chain, NULL);
900}
901
902
903void SelectionDAGLowering::visitRet(ReturnInst &I) {
904 if (I.getNumOperands() == 0) {
905 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
906 return;
907 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000908
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000909 SmallVector<SDValue, 8> NewValues;
910 NewValues.push_back(getControlRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000911 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000912 SmallVector<MVT, 4> ValueVTs;
913 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
Dan Gohman7ea1ca62008-10-21 20:00:42 +0000914 unsigned NumValues = ValueVTs.size();
915 if (NumValues == 0) continue;
916
917 SDValue RetOp = getValue(I.getOperand(i));
918 for (unsigned j = 0, f = NumValues; j != f; ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000919 MVT VT = ValueVTs[j];
920
921 // FIXME: C calling convention requires the return type to be promoted to
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000922 // at least 32-bit. But this is not necessary for non-C calling
923 // conventions.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000924 if (VT.isInteger()) {
925 MVT MinVT = TLI.getRegisterType(MVT::i32);
926 if (VT.bitsLT(MinVT))
927 VT = MinVT;
928 }
929
930 unsigned NumParts = TLI.getNumRegisters(VT);
931 MVT PartVT = TLI.getRegisterType(VT);
932 SmallVector<SDValue, 4> Parts(NumParts);
933 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000934
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000935 const Function *F = I.getParent()->getParent();
Devang Patel05988662008-09-25 21:00:45 +0000936 if (F->paramHasAttr(0, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000937 ExtendKind = ISD::SIGN_EXTEND;
Devang Patel05988662008-09-25 21:00:45 +0000938 else if (F->paramHasAttr(0, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000939 ExtendKind = ISD::ZERO_EXTEND;
940
941 getCopyToParts(DAG, SDValue(RetOp.getNode(), RetOp.getResNo() + j),
942 &Parts[0], NumParts, PartVT, ExtendKind);
943
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000944 // 'inreg' on function refers to return value
945 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Devang Patel05988662008-09-25 21:00:45 +0000946 if (F->paramHasAttr(0, Attribute::InReg))
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000947 Flags.setInReg();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000948 for (unsigned i = 0; i < NumParts; ++i) {
949 NewValues.push_back(Parts[i]);
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000950 NewValues.push_back(DAG.getArgFlags(Flags));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000951 }
952 }
953 }
954 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
955 &NewValues[0], NewValues.size()));
956}
957
958/// ExportFromCurrentBlock - If this condition isn't known to be exported from
959/// the current basic block, add it to ValueMap now so that we'll get a
960/// CopyTo/FromReg.
961void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
962 // No need to export constants.
963 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000964
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000965 // Already exported?
966 if (FuncInfo.isExportedInst(V)) return;
967
968 unsigned Reg = FuncInfo.InitializeRegForValue(V);
969 CopyValueToVirtualRegister(V, Reg);
970}
971
972bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
973 const BasicBlock *FromBB) {
974 // The operands of the setcc have to be in this block. We don't know
975 // how to export them from some other block.
976 if (Instruction *VI = dyn_cast<Instruction>(V)) {
977 // Can export from current BB.
978 if (VI->getParent() == FromBB)
979 return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000980
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000981 // Is already exported, noop.
982 return FuncInfo.isExportedInst(V);
983 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000984
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000985 // If this is an argument, we can export it if the BB is the entry block or
986 // if it is already exported.
987 if (isa<Argument>(V)) {
988 if (FromBB == &FromBB->getParent()->getEntryBlock())
989 return true;
990
991 // Otherwise, can only export this if it is already exported.
992 return FuncInfo.isExportedInst(V);
993 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000994
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000995 // Otherwise, constants can always be exported.
996 return true;
997}
998
999static bool InBlock(const Value *V, const BasicBlock *BB) {
1000 if (const Instruction *I = dyn_cast<Instruction>(V))
1001 return I->getParent() == BB;
1002 return true;
1003}
1004
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001005/// getFCmpCondCode - Return the ISD condition code corresponding to
1006/// the given LLVM IR floating-point condition code. This includes
1007/// consideration of global floating-point math flags.
1008///
1009static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1010 ISD::CondCode FPC, FOC;
1011 switch (Pred) {
1012 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1013 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1014 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1015 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1016 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1017 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1018 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1019 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1020 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1021 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1022 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1023 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1024 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1025 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1026 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1027 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1028 default:
1029 assert(0 && "Invalid FCmp predicate opcode!");
1030 FOC = FPC = ISD::SETFALSE;
1031 break;
1032 }
1033 if (FiniteOnlyFPMath())
1034 return FOC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001035 else
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001036 return FPC;
1037}
1038
1039/// getICmpCondCode - Return the ISD condition code corresponding to
1040/// the given LLVM IR integer condition code.
1041///
1042static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1043 switch (Pred) {
1044 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1045 case ICmpInst::ICMP_NE: return ISD::SETNE;
1046 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1047 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1048 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1049 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1050 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1051 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1052 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1053 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1054 default:
1055 assert(0 && "Invalid ICmp predicate opcode!");
1056 return ISD::SETNE;
1057 }
1058}
1059
Dan Gohmanc2277342008-10-17 21:16:08 +00001060/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1061/// This function emits a branch and is used at the leaves of an OR or an
1062/// AND operator tree.
1063///
1064void
1065SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1066 MachineBasicBlock *TBB,
1067 MachineBasicBlock *FBB,
1068 MachineBasicBlock *CurBB) {
1069 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001070
Dan Gohmanc2277342008-10-17 21:16:08 +00001071 // If the leaf of the tree is a comparison, merge the condition into
1072 // the caseblock.
1073 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1074 // The operands of the cmp have to be in this block. We don't know
1075 // how to export them from some other block. If this is the first block
1076 // of the sequence, no exporting is needed.
1077 if (CurBB == CurMBB ||
1078 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1079 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001080 ISD::CondCode Condition;
1081 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001082 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001083 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001084 Condition = getFCmpCondCode(FC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001085 } else {
1086 Condition = ISD::SETEQ; // silence warning.
1087 assert(0 && "Unknown compare instruction");
1088 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001089
1090 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001091 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1092 SwitchCases.push_back(CB);
1093 return;
1094 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001095 }
1096
1097 // Create a CaseBlock record representing this branch.
1098 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1099 NULL, TBB, FBB, CurBB);
1100 SwitchCases.push_back(CB);
1101}
1102
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001103/// FindMergedConditions - If Cond is an expression like
Dan Gohmanc2277342008-10-17 21:16:08 +00001104void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1105 MachineBasicBlock *TBB,
1106 MachineBasicBlock *FBB,
1107 MachineBasicBlock *CurBB,
1108 unsigned Opc) {
1109 // If this node is not part of the or/and tree, emit it as a branch.
1110 Instruction *BOp = dyn_cast<Instruction>(Cond);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001111 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohmanc2277342008-10-17 21:16:08 +00001112 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1113 BOp->getParent() != CurBB->getBasicBlock() ||
1114 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1115 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1116 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001117 return;
1118 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001119
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001120 // Create TmpBB after CurBB.
1121 MachineFunction::iterator BBI = CurBB;
1122 MachineFunction &MF = DAG.getMachineFunction();
1123 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1124 CurBB->getParent()->insert(++BBI, TmpBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001125
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001126 if (Opc == Instruction::Or) {
1127 // Codegen X | Y as:
1128 // jmp_if_X TBB
1129 // jmp TmpBB
1130 // TmpBB:
1131 // jmp_if_Y TBB
1132 // jmp FBB
1133 //
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001134
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001135 // Emit the LHS condition.
1136 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001137
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001138 // Emit the RHS condition into TmpBB.
1139 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1140 } else {
1141 assert(Opc == Instruction::And && "Unknown merge op!");
1142 // Codegen X & Y as:
1143 // jmp_if_X TmpBB
1144 // jmp FBB
1145 // TmpBB:
1146 // jmp_if_Y TBB
1147 // jmp FBB
1148 //
1149 // This requires creation of TmpBB after CurBB.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001150
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001151 // Emit the LHS condition.
1152 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001153
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001154 // Emit the RHS condition into TmpBB.
1155 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1156 }
1157}
1158
1159/// If the set of cases should be emitted as a series of branches, return true.
1160/// If we should emit this as a bunch of and/or'd together conditions, return
1161/// false.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001162bool
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001163SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1164 if (Cases.size() != 2) return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001165
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001166 // If this is two comparisons of the same values or'd or and'd together, they
1167 // will get folded into a single comparison, so don't emit two blocks.
1168 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1169 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1170 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1171 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1172 return false;
1173 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001174
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001175 return true;
1176}
1177
1178void SelectionDAGLowering::visitBr(BranchInst &I) {
1179 // Update machine-CFG edges.
1180 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1181
1182 // Figure out which block is immediately after the current one.
1183 MachineBasicBlock *NextBlock = 0;
1184 MachineFunction::iterator BBI = CurMBB;
1185 if (++BBI != CurMBB->getParent()->end())
1186 NextBlock = BBI;
1187
1188 if (I.isUnconditional()) {
1189 // Update machine-CFG edges.
1190 CurMBB->addSuccessor(Succ0MBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001191
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001192 // If this is not a fall-through branch, emit the branch.
1193 if (Succ0MBB != NextBlock)
1194 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1195 DAG.getBasicBlock(Succ0MBB)));
1196 return;
1197 }
1198
1199 // If this condition is one of the special cases we handle, do special stuff
1200 // now.
1201 Value *CondVal = I.getCondition();
1202 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1203
1204 // If this is a series of conditions that are or'd or and'd together, emit
1205 // this as a sequence of branches instead of setcc's with and/or operations.
1206 // For example, instead of something like:
1207 // cmp A, B
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001208 // C = seteq
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001209 // cmp D, E
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001210 // F = setle
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001211 // or C, F
1212 // jnz foo
1213 // Emit:
1214 // cmp A, B
1215 // je foo
1216 // cmp D, E
1217 // jle foo
1218 //
1219 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001220 if (BOp->hasOneUse() &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001221 (BOp->getOpcode() == Instruction::And ||
1222 BOp->getOpcode() == Instruction::Or)) {
1223 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1224 // If the compares in later blocks need to use values not currently
1225 // exported from this block, export them now. This block should always
1226 // be the first entry.
1227 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001228
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001229 // Allow some cases to be rejected.
1230 if (ShouldEmitAsBranches(SwitchCases)) {
1231 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1232 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1233 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1234 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001235
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001236 // Emit the branch for this block.
1237 visitSwitchCase(SwitchCases[0]);
1238 SwitchCases.erase(SwitchCases.begin());
1239 return;
1240 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001241
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001242 // Okay, we decided not to do this, remove any inserted MBB's and clear
1243 // SwitchCases.
1244 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1245 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001246
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001247 SwitchCases.clear();
1248 }
1249 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001250
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001251 // Create a CaseBlock record representing this branch.
1252 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1253 NULL, Succ0MBB, Succ1MBB, CurMBB);
1254 // Use visitSwitchCase to actually insert the fast branch sequence for this
1255 // cond branch.
1256 visitSwitchCase(CB);
1257}
1258
1259/// visitSwitchCase - Emits the necessary code to represent a single node in
1260/// the binary search tree resulting from lowering a switch instruction.
1261void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1262 SDValue Cond;
1263 SDValue CondLHS = getValue(CB.CmpLHS);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001264
1265 // Build the setcc now.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001266 if (CB.CmpMHS == NULL) {
1267 // Fold "(X == true)" to X and "(X == false)" to !X to
1268 // handle common cases produced by branch lowering.
1269 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1270 Cond = CondLHS;
1271 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1272 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1273 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1274 } else
1275 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1276 } else {
1277 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1278
Anton Korobeynikov23218582008-12-23 22:25:27 +00001279 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1280 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001281
1282 SDValue CmpOp = getValue(CB.CmpMHS);
1283 MVT VT = CmpOp.getValueType();
1284
1285 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1286 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1287 } else {
1288 SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1289 Cond = DAG.getSetCC(MVT::i1, SUB,
1290 DAG.getConstant(High-Low, VT), ISD::SETULE);
1291 }
1292 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001293
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001294 // Update successor info
1295 CurMBB->addSuccessor(CB.TrueBB);
1296 CurMBB->addSuccessor(CB.FalseBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001297
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001298 // Set NextBlock to be the MBB immediately after the current one, if any.
1299 // This is used to avoid emitting unnecessary branches to the next block.
1300 MachineBasicBlock *NextBlock = 0;
1301 MachineFunction::iterator BBI = CurMBB;
1302 if (++BBI != CurMBB->getParent()->end())
1303 NextBlock = BBI;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001304
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001305 // If the lhs block is the next block, invert the condition so that we can
1306 // fall through to the lhs instead of the rhs block.
1307 if (CB.TrueBB == NextBlock) {
1308 std::swap(CB.TrueBB, CB.FalseBB);
1309 SDValue True = DAG.getConstant(1, Cond.getValueType());
1310 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1311 }
1312 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1313 DAG.getBasicBlock(CB.TrueBB));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001314
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001315 // If the branch was constant folded, fix up the CFG.
1316 if (BrCond.getOpcode() == ISD::BR) {
1317 CurMBB->removeSuccessor(CB.FalseBB);
1318 DAG.setRoot(BrCond);
1319 } else {
1320 // Otherwise, go ahead and insert the false branch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001321 if (BrCond == getControlRoot())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001322 CurMBB->removeSuccessor(CB.TrueBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001323
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001324 if (CB.FalseBB == NextBlock)
1325 DAG.setRoot(BrCond);
1326 else
Anton Korobeynikov23218582008-12-23 22:25:27 +00001327 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001328 DAG.getBasicBlock(CB.FalseBB)));
1329 }
1330}
1331
1332/// visitJumpTable - Emit JumpTable node in the current MBB
1333void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1334 // Emit the code for the jump table
1335 assert(JT.Reg != -1U && "Should lower JT Header first!");
1336 MVT PTy = TLI.getPointerTy();
1337 SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1338 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1339 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1340 Table, Index));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001341}
1342
1343/// visitJumpTableHeader - This function emits necessary code to produce index
1344/// in the JumpTable from switch case.
1345void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1346 JumpTableHeader &JTH) {
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001347 // Subtract the lowest switch case value from the value being switched on and
1348 // conditional branch to default mbb if the result is greater than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001349 // difference between smallest and largest cases.
1350 SDValue SwitchOp = getValue(JTH.SValue);
1351 MVT VT = SwitchOp.getValueType();
1352 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001353 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001354
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001355 // The SDNode we just created, which holds the value being switched on minus
1356 // the the smallest case value, needs to be copied to a virtual register so it
1357 // can be used as an index into the jump table in a subsequent basic block.
1358 // This value may be smaller or larger than the target's pointer type, and
1359 // therefore require extension or truncating.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001360 if (VT.bitsGT(TLI.getPointerTy()))
1361 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1362 else
1363 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001364
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001365 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1366 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1367 JT.Reg = JumpTableReg;
1368
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001369 // Emit the range check for the jump table, and branch to the default block
1370 // for the switch statement if the value being switched on exceeds the largest
1371 // case in the switch.
Duncan Sands5480c042009-01-01 15:52:00 +00001372 SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB.getValueType()), SUB,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001373 DAG.getConstant(JTH.Last-JTH.First,VT),
1374 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001375
1376 // Set NextBlock to be the MBB immediately after the current one, if any.
1377 // This is used to avoid emitting unnecessary branches to the next block.
1378 MachineBasicBlock *NextBlock = 0;
1379 MachineFunction::iterator BBI = CurMBB;
1380 if (++BBI != CurMBB->getParent()->end())
1381 NextBlock = BBI;
1382
1383 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001384 DAG.getBasicBlock(JT.Default));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001385
1386 if (JT.MBB == NextBlock)
1387 DAG.setRoot(BrCond);
1388 else
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001389 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001390 DAG.getBasicBlock(JT.MBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001391}
1392
1393/// visitBitTestHeader - This function emits necessary code to produce value
1394/// suitable for "bit tests"
1395void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1396 // Subtract the minimum value
1397 SDValue SwitchOp = getValue(B.SValue);
1398 MVT VT = SwitchOp.getValueType();
1399 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001400 DAG.getConstant(B.First, VT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001401
1402 // Check range
Duncan Sands5480c042009-01-01 15:52:00 +00001403 SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB.getValueType()), SUB,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001404 DAG.getConstant(B.Range, VT),
1405 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001406
1407 SDValue ShiftOp;
1408 if (VT.bitsGT(TLI.getShiftAmountTy()))
1409 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1410 else
1411 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1412
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001413 B.Reg = FuncInfo.MakeReg(TLI.getShiftAmountTy());
1414 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), B.Reg, ShiftOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001415
1416 // Set NextBlock to be the MBB immediately after the current one, if any.
1417 // This is used to avoid emitting unnecessary branches to the next block.
1418 MachineBasicBlock *NextBlock = 0;
1419 MachineFunction::iterator BBI = CurMBB;
1420 if (++BBI != CurMBB->getParent()->end())
1421 NextBlock = BBI;
1422
1423 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1424
1425 CurMBB->addSuccessor(B.Default);
1426 CurMBB->addSuccessor(MBB);
1427
1428 SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001429 DAG.getBasicBlock(B.Default));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001430
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001431 if (MBB == NextBlock)
1432 DAG.setRoot(BrRange);
1433 else
1434 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1435 DAG.getBasicBlock(MBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001436}
1437
1438/// visitBitTestCase - this function produces one "bit test"
1439void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1440 unsigned Reg,
1441 BitTestCase &B) {
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001442 // Make desired shift
1443 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), Reg,
1444 TLI.getShiftAmountTy());
1445 SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1446 DAG.getConstant(1, TLI.getPointerTy()),
1447 ShiftOp);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001448
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001449 // Emit bit tests and jumps
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001450 SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001451 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Duncan Sands5480c042009-01-01 15:52:00 +00001452 SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp.getValueType()),
1453 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001454 ISD::SETNE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001455
1456 CurMBB->addSuccessor(B.TargetBB);
1457 CurMBB->addSuccessor(NextMBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001458
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001459 SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001460 AndCmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001461
1462 // Set NextBlock to be the MBB immediately after the current one, if any.
1463 // This is used to avoid emitting unnecessary branches to the next block.
1464 MachineBasicBlock *NextBlock = 0;
1465 MachineFunction::iterator BBI = CurMBB;
1466 if (++BBI != CurMBB->getParent()->end())
1467 NextBlock = BBI;
1468
1469 if (NextMBB == NextBlock)
1470 DAG.setRoot(BrAnd);
1471 else
1472 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1473 DAG.getBasicBlock(NextMBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001474}
1475
1476void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1477 // Retrieve successors.
1478 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1479 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1480
Gabor Greifb67e6b32009-01-15 11:10:44 +00001481 const Value *Callee(I.getCalledValue());
1482 if (isa<InlineAsm>(Callee))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001483 visitInlineAsm(&I);
1484 else
Gabor Greifb67e6b32009-01-15 11:10:44 +00001485 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001486
1487 // If the value of the invoke is used outside of its defining block, make it
1488 // available as a virtual register.
1489 if (!I.use_empty()) {
1490 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1491 if (VMI != FuncInfo.ValueMap.end())
1492 CopyValueToVirtualRegister(&I, VMI->second);
1493 }
1494
1495 // Update successor info
1496 CurMBB->addSuccessor(Return);
1497 CurMBB->addSuccessor(LandingPad);
1498
1499 // Drop into normal successor.
1500 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1501 DAG.getBasicBlock(Return)));
1502}
1503
1504void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1505}
1506
1507/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1508/// small case ranges).
1509bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1510 CaseRecVector& WorkList,
1511 Value* SV,
1512 MachineBasicBlock* Default) {
1513 Case& BackCase = *(CR.Range.second-1);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001514
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001515 // Size is the number of Cases represented by this range.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001516 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001517 if (Size > 3)
Anton Korobeynikov23218582008-12-23 22:25:27 +00001518 return false;
1519
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001520 // Get the MachineFunction which holds the current MBB. This is used when
1521 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001522 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001523
1524 // Figure out which block is immediately after the current one.
1525 MachineBasicBlock *NextBlock = 0;
1526 MachineFunction::iterator BBI = CR.CaseBB;
1527
1528 if (++BBI != CurMBB->getParent()->end())
1529 NextBlock = BBI;
1530
1531 // TODO: If any two of the cases has the same destination, and if one value
1532 // is the same as the other, but has one bit unset that the other has set,
1533 // use bit manipulation to do two compares at once. For example:
1534 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Anton Korobeynikov23218582008-12-23 22:25:27 +00001535
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001536 // Rearrange the case blocks so that the last one falls through if possible.
1537 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1538 // The last case block won't fall through into 'NextBlock' if we emit the
1539 // branches in this order. See if rearranging a case value would help.
1540 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1541 if (I->BB == NextBlock) {
1542 std::swap(*I, BackCase);
1543 break;
1544 }
1545 }
1546 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001547
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001548 // Create a CaseBlock record representing a conditional branch to
1549 // the Case's target mbb if the value being switched on SV is equal
1550 // to C.
1551 MachineBasicBlock *CurBlock = CR.CaseBB;
1552 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1553 MachineBasicBlock *FallThrough;
1554 if (I != E-1) {
1555 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1556 CurMF->insert(BBI, FallThrough);
1557 } else {
1558 // If the last case doesn't match, go to the default block.
1559 FallThrough = Default;
1560 }
1561
1562 Value *RHS, *LHS, *MHS;
1563 ISD::CondCode CC;
1564 if (I->High == I->Low) {
1565 // This is just small small case range :) containing exactly 1 case
1566 CC = ISD::SETEQ;
1567 LHS = SV; RHS = I->High; MHS = NULL;
1568 } else {
1569 CC = ISD::SETLE;
1570 LHS = I->Low; MHS = SV; RHS = I->High;
1571 }
1572 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001573
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001574 // If emitting the first comparison, just call visitSwitchCase to emit the
1575 // code into the current block. Otherwise, push the CaseBlock onto the
1576 // vector to be later processed by SDISel, and insert the node's MBB
1577 // before the next MBB.
1578 if (CurBlock == CurMBB)
1579 visitSwitchCase(CB);
1580 else
1581 SwitchCases.push_back(CB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001582
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001583 CurBlock = FallThrough;
1584 }
1585
1586 return true;
1587}
1588
1589static inline bool areJTsAllowed(const TargetLowering &TLI) {
1590 return !DisableJumpTables &&
Dan Gohmanf560ffa2009-01-28 17:46:25 +00001591 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1592 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001593}
Anton Korobeynikov23218582008-12-23 22:25:27 +00001594
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001595static APInt ComputeRange(const APInt &First, const APInt &Last) {
1596 APInt LastExt(Last), FirstExt(First);
1597 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1598 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1599 return (LastExt - FirstExt + 1ULL);
1600}
1601
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001602/// handleJTSwitchCase - Emit jumptable for current switch case range
1603bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1604 CaseRecVector& WorkList,
1605 Value* SV,
1606 MachineBasicBlock* Default) {
1607 Case& FrontCase = *CR.Range.first;
1608 Case& BackCase = *(CR.Range.second-1);
1609
Anton Korobeynikov23218582008-12-23 22:25:27 +00001610 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1611 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001612
Anton Korobeynikov23218582008-12-23 22:25:27 +00001613 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001614 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1615 I!=E; ++I)
1616 TSize += I->size();
1617
1618 if (!areJTsAllowed(TLI) || TSize <= 3)
1619 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001620
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001621 APInt Range = ComputeRange(First, Last);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001622 double Density = (double)TSize / Range.roundToDouble();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001623 if (Density < 0.4)
1624 return false;
1625
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001626 DEBUG(errs() << "Lowering jump table\n"
1627 << "First entry: " << First << ". Last entry: " << Last << '\n'
1628 << "Range: " << Range
1629 << "Size: " << TSize << ". Density: " << Density << "\n\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001630
1631 // Get the MachineFunction which holds the current MBB. This is used when
1632 // inserting any additional MBBs necessary to represent the switch.
1633 MachineFunction *CurMF = CurMBB->getParent();
1634
1635 // Figure out which block is immediately after the current one.
1636 MachineBasicBlock *NextBlock = 0;
1637 MachineFunction::iterator BBI = CR.CaseBB;
1638
1639 if (++BBI != CurMBB->getParent()->end())
1640 NextBlock = BBI;
1641
1642 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1643
1644 // Create a new basic block to hold the code for loading the address
1645 // of the jump table, and jumping to it. Update successor information;
1646 // we will either branch to the default case for the switch, or the jump
1647 // table.
1648 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1649 CurMF->insert(BBI, JumpTableBB);
1650 CR.CaseBB->addSuccessor(Default);
1651 CR.CaseBB->addSuccessor(JumpTableBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001652
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001653 // Build a vector of destination BBs, corresponding to each target
1654 // of the jump table. If the value of the jump table slot corresponds to
1655 // a case statement, push the case's BB onto the vector, otherwise, push
1656 // the default BB.
1657 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001658 APInt TEI = First;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001659 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001660 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1661 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1662
1663 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001664 DestBBs.push_back(I->BB);
1665 if (TEI==High)
1666 ++I;
1667 } else {
1668 DestBBs.push_back(Default);
1669 }
1670 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001671
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001672 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001673 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1674 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001675 E = DestBBs.end(); I != E; ++I) {
1676 if (!SuccsHandled[(*I)->getNumber()]) {
1677 SuccsHandled[(*I)->getNumber()] = true;
1678 JumpTableBB->addSuccessor(*I);
1679 }
1680 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001681
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001682 // Create a jump table index for this jump table, or return an existing
1683 // one.
1684 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001685
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001686 // Set the jump table information so that we can codegen it as a second
1687 // MachineBasicBlock
1688 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1689 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1690 if (CR.CaseBB == CurMBB)
1691 visitJumpTableHeader(JT, JTH);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001692
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001693 JTCases.push_back(JumpTableBlock(JTH, JT));
1694
1695 return true;
1696}
1697
1698/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1699/// 2 subtrees.
1700bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1701 CaseRecVector& WorkList,
1702 Value* SV,
1703 MachineBasicBlock* Default) {
1704 // Get the MachineFunction which holds the current MBB. This is used when
1705 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001706 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001707
1708 // Figure out which block is immediately after the current one.
1709 MachineBasicBlock *NextBlock = 0;
1710 MachineFunction::iterator BBI = CR.CaseBB;
1711
1712 if (++BBI != CurMBB->getParent()->end())
1713 NextBlock = BBI;
1714
1715 Case& FrontCase = *CR.Range.first;
1716 Case& BackCase = *(CR.Range.second-1);
1717 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1718
1719 // Size is the number of Cases represented by this range.
1720 unsigned Size = CR.Range.second - CR.Range.first;
1721
Anton Korobeynikov23218582008-12-23 22:25:27 +00001722 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1723 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001724 double FMetric = 0;
1725 CaseItr Pivot = CR.Range.first + Size/2;
1726
1727 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1728 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001729 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001730 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1731 I!=E; ++I)
1732 TSize += I->size();
1733
Anton Korobeynikov23218582008-12-23 22:25:27 +00001734 size_t LSize = FrontCase.size();
1735 size_t RSize = TSize-LSize;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001736 DEBUG(errs() << "Selecting best pivot: \n"
1737 << "First: " << First << ", Last: " << Last <<'\n'
1738 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001739 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1740 J!=E; ++I, ++J) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001741 const APInt& LEnd = cast<ConstantInt>(I->High)->getValue();
1742 const APInt& RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001743 APInt Range = ComputeRange(LEnd, RBegin);
1744 assert((Range - 2ULL).isNonNegative() &&
1745 "Invalid case distance");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001746 double LDensity = (double)LSize / (LEnd - First + 1ULL).roundToDouble();
1747 double RDensity = (double)RSize / (Last - RBegin + 1ULL).roundToDouble();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001748 double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001749 // Should always split in some non-trivial place
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001750 DEBUG(errs() <<"=>Step\n"
1751 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1752 << "LDensity: " << LDensity
1753 << ", RDensity: " << RDensity << '\n'
1754 << "Metric: " << Metric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001755 if (FMetric < Metric) {
1756 Pivot = J;
1757 FMetric = Metric;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001758 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001759 }
1760
1761 LSize += J->size();
1762 RSize -= J->size();
1763 }
1764 if (areJTsAllowed(TLI)) {
1765 // If our case is dense we *really* should handle it earlier!
1766 assert((FMetric > 0) && "Should handle dense range earlier!");
1767 } else {
1768 Pivot = CR.Range.first + Size/2;
1769 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001770
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001771 CaseRange LHSR(CR.Range.first, Pivot);
1772 CaseRange RHSR(Pivot, CR.Range.second);
1773 Constant *C = Pivot->Low;
1774 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001775
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001776 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001777 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001778 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001779 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001780 // Pivot's Value, then we can branch directly to the LHS's Target,
1781 // rather than creating a leaf node for it.
1782 if ((LHSR.second - LHSR.first) == 1 &&
1783 LHSR.first->High == CR.GE &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001784 cast<ConstantInt>(C)->getValue() ==
1785 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001786 TrueBB = LHSR.first->BB;
1787 } else {
1788 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1789 CurMF->insert(BBI, TrueBB);
1790 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1791 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001792
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001793 // Similar to the optimization above, if the Value being switched on is
1794 // known to be less than the Constant CR.LT, and the current Case Value
1795 // is CR.LT - 1, then we can branch directly to the target block for
1796 // the current Case Value, rather than emitting a RHS leaf node for it.
1797 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001798 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1799 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001800 FalseBB = RHSR.first->BB;
1801 } else {
1802 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1803 CurMF->insert(BBI, FalseBB);
1804 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1805 }
1806
1807 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001808 // the LHS node if the value being switched on SV is less than C.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001809 // Otherwise, branch to LHS.
1810 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1811
1812 if (CR.CaseBB == CurMBB)
1813 visitSwitchCase(CB);
1814 else
1815 SwitchCases.push_back(CB);
1816
1817 return true;
1818}
1819
1820/// handleBitTestsSwitchCase - if current case range has few destination and
1821/// range span less, than machine word bitwidth, encode case range into series
1822/// of masks and emit bit tests with these masks.
1823bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1824 CaseRecVector& WorkList,
1825 Value* SV,
1826 MachineBasicBlock* Default){
1827 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1828
1829 Case& FrontCase = *CR.Range.first;
1830 Case& BackCase = *(CR.Range.second-1);
1831
1832 // Get the MachineFunction which holds the current MBB. This is used when
1833 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001834 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001835
Anton Korobeynikov23218582008-12-23 22:25:27 +00001836 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001837 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1838 I!=E; ++I) {
1839 // Single case counts one, case range - two.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001840 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001841 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001842
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001843 // Count unique destinations
1844 SmallSet<MachineBasicBlock*, 4> Dests;
1845 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1846 Dests.insert(I->BB);
1847 if (Dests.size() > 3)
1848 // Don't bother the code below, if there are too much unique destinations
1849 return false;
1850 }
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001851 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1852 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001853
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001854 // Compute span of values.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001855 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1856 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001857 APInt cmpRange = maxValue - minValue;
1858
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001859 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1860 << "Low bound: " << minValue << '\n'
1861 << "High bound: " << maxValue << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001862
1863 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001864 (!(Dests.size() == 1 && numCmps >= 3) &&
1865 !(Dests.size() == 2 && numCmps >= 5) &&
1866 !(Dests.size() >= 3 && numCmps >= 6)))
1867 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001868
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001869 DEBUG(errs() << "Emitting bit tests\n");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001870 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1871
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001872 // Optimize the case where all the case values fit in a
1873 // word without having to subtract minValue. In this case,
1874 // we can optimize away the subtraction.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001875 if (minValue.isNonNegative() &&
1876 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1877 cmpRange = maxValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001878 } else {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001879 lowBound = minValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001880 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001881
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001882 CaseBitsVector CasesBits;
1883 unsigned i, count = 0;
1884
1885 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1886 MachineBasicBlock* Dest = I->BB;
1887 for (i = 0; i < count; ++i)
1888 if (Dest == CasesBits[i].BB)
1889 break;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001890
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001891 if (i == count) {
1892 assert((count < 3) && "Too much destinations to test!");
1893 CasesBits.push_back(CaseBits(0, Dest, 0));
1894 count++;
1895 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001896
1897 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1898 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1899
1900 uint64_t lo = (lowValue - lowBound).getZExtValue();
1901 uint64_t hi = (highValue - lowBound).getZExtValue();
1902
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001903 for (uint64_t j = lo; j <= hi; j++) {
1904 CasesBits[i].Mask |= 1ULL << j;
1905 CasesBits[i].Bits++;
1906 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001907
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001908 }
1909 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001910
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001911 BitTestInfo BTC;
1912
1913 // Figure out which block is immediately after the current one.
1914 MachineFunction::iterator BBI = CR.CaseBB;
1915 ++BBI;
1916
1917 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1918
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001919 DEBUG(errs() << "Cases:\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001920 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001921 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
1922 << ", Bits: " << CasesBits[i].Bits
1923 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001924
1925 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1926 CurMF->insert(BBI, CaseBB);
1927 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1928 CaseBB,
1929 CasesBits[i].BB));
1930 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001931
1932 BitTestBlock BTB(lowBound, cmpRange, SV,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001933 -1U, (CR.CaseBB == CurMBB),
1934 CR.CaseBB, Default, BTC);
1935
1936 if (CR.CaseBB == CurMBB)
1937 visitBitTestHeader(BTB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001938
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001939 BitTestCases.push_back(BTB);
1940
1941 return true;
1942}
1943
1944
1945/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov23218582008-12-23 22:25:27 +00001946size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001947 const SwitchInst& SI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001948 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001949
1950 // Start with "simple" cases
Anton Korobeynikov23218582008-12-23 22:25:27 +00001951 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001952 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1953 Cases.push_back(Case(SI.getSuccessorValue(i),
1954 SI.getSuccessorValue(i),
1955 SMBB));
1956 }
1957 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1958
1959 // Merge case into clusters
Anton Korobeynikov23218582008-12-23 22:25:27 +00001960 if (Cases.size() >= 2)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001961 // Must recompute end() each iteration because it may be
1962 // invalidated by erase if we hold on to it
Anton Korobeynikov23218582008-12-23 22:25:27 +00001963 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
1964 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
1965 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001966 MachineBasicBlock* nextBB = J->BB;
1967 MachineBasicBlock* currentBB = I->BB;
1968
1969 // If the two neighboring cases go to the same destination, merge them
1970 // into a single case.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001971 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001972 I->High = J->High;
1973 J = Cases.erase(J);
1974 } else {
1975 I = J++;
1976 }
1977 }
1978
1979 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1980 if (I->Low != I->High)
1981 // A range counts double, since it requires two compares.
1982 ++numCmps;
1983 }
1984
1985 return numCmps;
1986}
1987
Anton Korobeynikov23218582008-12-23 22:25:27 +00001988void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001989 // Figure out which block is immediately after the current one.
1990 MachineBasicBlock *NextBlock = 0;
1991 MachineFunction::iterator BBI = CurMBB;
1992
1993 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1994
1995 // If there is only the default destination, branch to it if it is not the
1996 // next basic block. Otherwise, just fall through.
1997 if (SI.getNumOperands() == 2) {
1998 // Update machine-CFG edges.
1999
2000 // If this is not a fall-through branch, emit the branch.
2001 CurMBB->addSuccessor(Default);
2002 if (Default != NextBlock)
2003 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
2004 DAG.getBasicBlock(Default)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002005 return;
2006 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002007
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002008 // If there are any non-default case statements, create a vector of Cases
2009 // representing each one, and sort the vector so that we can efficiently
2010 // create a binary search tree from them.
2011 CaseVector Cases;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002012 size_t numCmps = Clusterify(Cases, SI);
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002013 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2014 << ". Total compares: " << numCmps << '\n');
Devang Patel8a84e442009-01-05 17:31:22 +00002015 numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002016
2017 // Get the Value to be switched on and default basic blocks, which will be
2018 // inserted into CaseBlock records, representing basic blocks in the binary
2019 // search tree.
2020 Value *SV = SI.getOperand(0);
2021
2022 // Push the initial CaseRec onto the worklist
2023 CaseRecVector WorkList;
2024 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2025
2026 while (!WorkList.empty()) {
2027 // Grab a record representing a case range to process off the worklist
2028 CaseRec CR = WorkList.back();
2029 WorkList.pop_back();
2030
2031 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2032 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002033
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002034 // If the range has few cases (two or less) emit a series of specific
2035 // tests.
2036 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2037 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002038
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002039 // If the switch has more than 5 blocks, and at least 40% dense, and the
2040 // target supports indirect branches, then emit a jump table rather than
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002041 // lowering the switch to a binary tree of conditional branches.
2042 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2043 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002044
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002045 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2046 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2047 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2048 }
2049}
2050
2051
2052void SelectionDAGLowering::visitSub(User &I) {
2053 // -0.0 - X --> fneg
2054 const Type *Ty = I.getType();
2055 if (isa<VectorType>(Ty)) {
2056 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2057 const VectorType *DestTy = cast<VectorType>(I.getType());
2058 const Type *ElTy = DestTy->getElementType();
2059 if (ElTy->isFloatingPoint()) {
2060 unsigned VL = DestTy->getNumElements();
2061 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2062 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2063 if (CV == CNZ) {
2064 SDValue Op2 = getValue(I.getOperand(1));
2065 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2066 return;
2067 }
2068 }
2069 }
2070 }
2071 if (Ty->isFloatingPoint()) {
2072 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2073 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2074 SDValue Op2 = getValue(I.getOperand(1));
2075 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2076 return;
2077 }
2078 }
2079
2080 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2081}
2082
2083void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2084 SDValue Op1 = getValue(I.getOperand(0));
2085 SDValue Op2 = getValue(I.getOperand(1));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002086
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002087 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2088}
2089
2090void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2091 SDValue Op1 = getValue(I.getOperand(0));
2092 SDValue Op2 = getValue(I.getOperand(1));
2093 if (!isa<VectorType>(I.getType())) {
2094 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2095 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2096 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2097 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2098 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002099
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002100 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2101}
2102
2103void SelectionDAGLowering::visitICmp(User &I) {
2104 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2105 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2106 predicate = IC->getPredicate();
2107 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2108 predicate = ICmpInst::Predicate(IC->getPredicate());
2109 SDValue Op1 = getValue(I.getOperand(0));
2110 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002111 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002112 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2113}
2114
2115void SelectionDAGLowering::visitFCmp(User &I) {
2116 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2117 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2118 predicate = FC->getPredicate();
2119 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2120 predicate = FCmpInst::Predicate(FC->getPredicate());
2121 SDValue Op1 = getValue(I.getOperand(0));
2122 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002123 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002124 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2125}
2126
2127void SelectionDAGLowering::visitVICmp(User &I) {
2128 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2129 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2130 predicate = IC->getPredicate();
2131 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2132 predicate = ICmpInst::Predicate(IC->getPredicate());
2133 SDValue Op1 = getValue(I.getOperand(0));
2134 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002135 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002136 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2137}
2138
2139void SelectionDAGLowering::visitVFCmp(User &I) {
2140 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2141 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2142 predicate = FC->getPredicate();
2143 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2144 predicate = FCmpInst::Predicate(FC->getPredicate());
2145 SDValue Op1 = getValue(I.getOperand(0));
2146 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002147 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002148 MVT DestVT = TLI.getValueType(I.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002149
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002150 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2151}
2152
2153void SelectionDAGLowering::visitSelect(User &I) {
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002154 SmallVector<MVT, 4> ValueVTs;
2155 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2156 unsigned NumValues = ValueVTs.size();
2157 if (NumValues != 0) {
2158 SmallVector<SDValue, 4> Values(NumValues);
2159 SDValue Cond = getValue(I.getOperand(0));
2160 SDValue TrueVal = getValue(I.getOperand(1));
2161 SDValue FalseVal = getValue(I.getOperand(2));
2162
2163 for (unsigned i = 0; i != NumValues; ++i)
2164 Values[i] = DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2165 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2166 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2167
Duncan Sandsaaffa052008-12-01 11:41:29 +00002168 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2169 DAG.getVTList(&ValueVTs[0], NumValues),
2170 &Values[0], NumValues));
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002171 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002172}
2173
2174
2175void SelectionDAGLowering::visitTrunc(User &I) {
2176 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2177 SDValue N = getValue(I.getOperand(0));
2178 MVT DestVT = TLI.getValueType(I.getType());
2179 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2180}
2181
2182void SelectionDAGLowering::visitZExt(User &I) {
2183 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2184 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2185 SDValue N = getValue(I.getOperand(0));
2186 MVT DestVT = TLI.getValueType(I.getType());
2187 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2188}
2189
2190void SelectionDAGLowering::visitSExt(User &I) {
2191 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2192 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2193 SDValue N = getValue(I.getOperand(0));
2194 MVT DestVT = TLI.getValueType(I.getType());
2195 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2196}
2197
2198void SelectionDAGLowering::visitFPTrunc(User &I) {
2199 // FPTrunc is never a no-op cast, no need to check
2200 SDValue N = getValue(I.getOperand(0));
2201 MVT DestVT = TLI.getValueType(I.getType());
2202 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2203}
2204
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002205void SelectionDAGLowering::visitFPExt(User &I){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002206 // FPTrunc is never a no-op cast, no need to check
2207 SDValue N = getValue(I.getOperand(0));
2208 MVT DestVT = TLI.getValueType(I.getType());
2209 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2210}
2211
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002212void SelectionDAGLowering::visitFPToUI(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002213 // FPToUI is never a no-op cast, no need to check
2214 SDValue N = getValue(I.getOperand(0));
2215 MVT DestVT = TLI.getValueType(I.getType());
2216 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2217}
2218
2219void SelectionDAGLowering::visitFPToSI(User &I) {
2220 // FPToSI is never a no-op cast, no need to check
2221 SDValue N = getValue(I.getOperand(0));
2222 MVT DestVT = TLI.getValueType(I.getType());
2223 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2224}
2225
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002226void SelectionDAGLowering::visitUIToFP(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002227 // UIToFP is never a no-op cast, no need to check
2228 SDValue N = getValue(I.getOperand(0));
2229 MVT DestVT = TLI.getValueType(I.getType());
2230 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2231}
2232
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002233void SelectionDAGLowering::visitSIToFP(User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002234 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002235 SDValue N = getValue(I.getOperand(0));
2236 MVT DestVT = TLI.getValueType(I.getType());
2237 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2238}
2239
2240void SelectionDAGLowering::visitPtrToInt(User &I) {
2241 // What to do depends on the size of the integer and the size of the pointer.
2242 // We can either truncate, zero extend, or no-op, accordingly.
2243 SDValue N = getValue(I.getOperand(0));
2244 MVT SrcVT = N.getValueType();
2245 MVT DestVT = TLI.getValueType(I.getType());
2246 SDValue Result;
2247 if (DestVT.bitsLT(SrcVT))
2248 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002249 else
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002250 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2251 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2252 setValue(&I, Result);
2253}
2254
2255void SelectionDAGLowering::visitIntToPtr(User &I) {
2256 // What to do depends on the size of the integer and the size of the pointer.
2257 // We can either truncate, zero extend, or no-op, accordingly.
2258 SDValue N = getValue(I.getOperand(0));
2259 MVT SrcVT = N.getValueType();
2260 MVT DestVT = TLI.getValueType(I.getType());
2261 if (DestVT.bitsLT(SrcVT))
2262 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002263 else
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002264 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2265 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2266}
2267
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002268void SelectionDAGLowering::visitBitCast(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002269 SDValue N = getValue(I.getOperand(0));
2270 MVT DestVT = TLI.getValueType(I.getType());
2271
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002272 // BitCast assures us that source and destination are the same size so this
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002273 // is either a BIT_CONVERT or a no-op.
2274 if (DestVT != N.getValueType())
2275 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2276 else
2277 setValue(&I, N); // noop cast.
2278}
2279
2280void SelectionDAGLowering::visitInsertElement(User &I) {
2281 SDValue InVec = getValue(I.getOperand(0));
2282 SDValue InVal = getValue(I.getOperand(1));
2283 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2284 getValue(I.getOperand(2)));
2285
2286 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2287 TLI.getValueType(I.getType()),
2288 InVec, InVal, InIdx));
2289}
2290
2291void SelectionDAGLowering::visitExtractElement(User &I) {
2292 SDValue InVec = getValue(I.getOperand(0));
2293 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2294 getValue(I.getOperand(1)));
2295 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2296 TLI.getValueType(I.getType()), InVec, InIdx));
2297}
2298
Mon P Wangaeb06d22008-11-10 04:46:22 +00002299
2300// Utility for visitShuffleVector - Returns true if the mask is mask starting
2301// from SIndx and increasing to the element length (undefs are allowed).
2302static bool SequentialMask(SDValue Mask, unsigned SIndx) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002303 unsigned MaskNumElts = Mask.getNumOperands();
2304 for (unsigned i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002305 if (Mask.getOperand(i).getOpcode() != ISD::UNDEF) {
2306 unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2307 if (Idx != i + SIndx)
2308 return false;
2309 }
2310 }
2311 return true;
2312}
2313
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002314void SelectionDAGLowering::visitShuffleVector(User &I) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002315 SDValue Src1 = getValue(I.getOperand(0));
2316 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002317 SDValue Mask = getValue(I.getOperand(2));
2318
Mon P Wangaeb06d22008-11-10 04:46:22 +00002319 MVT VT = TLI.getValueType(I.getType());
Mon P Wang230e4fa2008-11-21 04:25:21 +00002320 MVT SrcVT = Src1.getValueType();
Mon P Wangc7849c22008-11-16 05:06:27 +00002321 int MaskNumElts = Mask.getNumOperands();
2322 int SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002323
Mon P Wangc7849c22008-11-16 05:06:27 +00002324 if (SrcNumElts == MaskNumElts) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002325 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002326 return;
2327 }
2328
2329 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002330 MVT MaskEltVT = Mask.getValueType().getVectorElementType();
2331
2332 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2333 // Mask is longer than the source vectors and is a multiple of the source
2334 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang230e4fa2008-11-21 04:25:21 +00002335 // lengths match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002336 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2337 // The shuffle is concatenating two vectors together.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002338 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, VT, Src1, Src2));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002339 return;
2340 }
2341
Mon P Wangc7849c22008-11-16 05:06:27 +00002342 // Pad both vectors with undefs to make them the same length as the mask.
2343 unsigned NumConcat = MaskNumElts / SrcNumElts;
2344 SDValue UndefVal = DAG.getNode(ISD::UNDEF, SrcVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002345
Mon P Wang230e4fa2008-11-21 04:25:21 +00002346 SDValue* MOps1 = new SDValue[NumConcat];
2347 SDValue* MOps2 = new SDValue[NumConcat];
2348 MOps1[0] = Src1;
2349 MOps2[0] = Src2;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002350 for (unsigned i = 1; i != NumConcat; ++i) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002351 MOps1[i] = UndefVal;
2352 MOps2[i] = UndefVal;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002353 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002354 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, VT, MOps1, NumConcat);
2355 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, VT, MOps2, NumConcat);
2356
2357 delete [] MOps1;
2358 delete [] MOps2;
2359
Mon P Wangaeb06d22008-11-10 04:46:22 +00002360 // Readjust mask for new input vector length.
2361 SmallVector<SDValue, 8> MappedOps;
Mon P Wangc7849c22008-11-16 05:06:27 +00002362 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002363 if (Mask.getOperand(i).getOpcode() == ISD::UNDEF) {
2364 MappedOps.push_back(Mask.getOperand(i));
2365 } else {
Mon P Wangc7849c22008-11-16 05:06:27 +00002366 int Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2367 if (Idx < SrcNumElts)
2368 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2369 else
2370 MappedOps.push_back(DAG.getConstant(Idx + MaskNumElts - SrcNumElts,
2371 MaskEltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002372 }
2373 }
2374 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2375 &MappedOps[0], MappedOps.size());
2376
Mon P Wang230e4fa2008-11-21 04:25:21 +00002377 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002378 return;
2379 }
2380
Mon P Wangc7849c22008-11-16 05:06:27 +00002381 if (SrcNumElts > MaskNumElts) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002382 // Resulting vector is shorter than the incoming vector.
Mon P Wangc7849c22008-11-16 05:06:27 +00002383 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,0)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002384 // Shuffle extracts 1st vector.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002385 setValue(&I, Src1);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002386 return;
2387 }
2388
Mon P Wangc7849c22008-11-16 05:06:27 +00002389 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,MaskNumElts)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002390 // Shuffle extracts 2nd vector.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002391 setValue(&I, Src2);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002392 return;
2393 }
2394
Mon P Wangc7849c22008-11-16 05:06:27 +00002395 // Analyze the access pattern of the vector to see if we can extract
2396 // two subvectors and do the shuffle. The analysis is done by calculating
2397 // the range of elements the mask access on both vectors.
2398 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2399 int MaxRange[2] = {-1, -1};
2400
2401 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002402 SDValue Arg = Mask.getOperand(i);
2403 if (Arg.getOpcode() != ISD::UNDEF) {
2404 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Mon P Wangc7849c22008-11-16 05:06:27 +00002405 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2406 int Input = 0;
2407 if (Idx >= SrcNumElts) {
2408 Input = 1;
2409 Idx -= SrcNumElts;
2410 }
2411 if (Idx > MaxRange[Input])
2412 MaxRange[Input] = Idx;
2413 if (Idx < MinRange[Input])
2414 MinRange[Input] = Idx;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002415 }
2416 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002417
Mon P Wangc7849c22008-11-16 05:06:27 +00002418 // Check if the access is smaller than the vector size and can we find
2419 // a reasonable extract index.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002420 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
Mon P Wangc7849c22008-11-16 05:06:27 +00002421 int StartIdx[2]; // StartIdx to extract from
2422 for (int Input=0; Input < 2; ++Input) {
2423 if (MinRange[Input] == SrcNumElts+1 && MaxRange[Input] == -1) {
2424 RangeUse[Input] = 0; // Unused
2425 StartIdx[Input] = 0;
2426 } else if (MaxRange[Input] - MinRange[Input] < MaskNumElts) {
2427 // Fits within range but we should see if we can find a good
Mon P Wang230e4fa2008-11-21 04:25:21 +00002428 // start index that is a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002429 if (MaxRange[Input] < MaskNumElts) {
2430 RangeUse[Input] = 1; // Extract from beginning of the vector
2431 StartIdx[Input] = 0;
2432 } else {
2433 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
Mon P Wang6cce3da2008-11-23 04:35:05 +00002434 if (MaxRange[Input] - StartIdx[Input] < MaskNumElts &&
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002435 StartIdx[Input] + MaskNumElts < SrcNumElts)
Mon P Wangc7849c22008-11-16 05:06:27 +00002436 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002437 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002438 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002439 }
2440
2441 if (RangeUse[0] == 0 && RangeUse[0] == 0) {
2442 setValue(&I, DAG.getNode(ISD::UNDEF, VT)); // Vectors are not used.
2443 return;
2444 }
2445 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2446 // Extract appropriate subvector and generate a vector shuffle
2447 for (int Input=0; Input < 2; ++Input) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002448 SDValue& Src = Input == 0 ? Src1 : Src2;
Mon P Wangc7849c22008-11-16 05:06:27 +00002449 if (RangeUse[Input] == 0) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002450 Src = DAG.getNode(ISD::UNDEF, VT);
Mon P Wangc7849c22008-11-16 05:06:27 +00002451 } else {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002452 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, VT, Src,
2453 DAG.getIntPtrConstant(StartIdx[Input]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002454 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002455 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002456 // Calculate new mask.
2457 SmallVector<SDValue, 8> MappedOps;
2458 for (int i = 0; i != MaskNumElts; ++i) {
2459 SDValue Arg = Mask.getOperand(i);
2460 if (Arg.getOpcode() == ISD::UNDEF) {
2461 MappedOps.push_back(Arg);
2462 } else {
2463 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2464 if (Idx < SrcNumElts)
2465 MappedOps.push_back(DAG.getConstant(Idx - StartIdx[0], MaskEltVT));
2466 else {
2467 Idx = Idx - SrcNumElts - StartIdx[1] + MaskNumElts;
2468 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002469 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002470 }
2471 }
2472 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2473 &MappedOps[0], MappedOps.size());
Mon P Wang230e4fa2008-11-21 04:25:21 +00002474 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
Mon P Wangc7849c22008-11-16 05:06:27 +00002475 return;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002476 }
2477 }
2478
Mon P Wangc7849c22008-11-16 05:06:27 +00002479 // We can't use either concat vectors or extract subvectors so fall back to
2480 // replacing the shuffle with extract and build vector.
2481 // to insert and build vector.
Mon P Wangaeb06d22008-11-10 04:46:22 +00002482 MVT EltVT = VT.getVectorElementType();
2483 MVT PtrVT = TLI.getPointerTy();
2484 SmallVector<SDValue,8> Ops;
Mon P Wangc7849c22008-11-16 05:06:27 +00002485 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002486 SDValue Arg = Mask.getOperand(i);
2487 if (Arg.getOpcode() == ISD::UNDEF) {
2488 Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2489 } else {
2490 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Mon P Wangc7849c22008-11-16 05:06:27 +00002491 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2492 if (Idx < SrcNumElts)
Mon P Wang230e4fa2008-11-21 04:25:21 +00002493 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Src1,
Mon P Wangaeb06d22008-11-10 04:46:22 +00002494 DAG.getConstant(Idx, PtrVT)));
2495 else
Mon P Wang230e4fa2008-11-21 04:25:21 +00002496 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Src2,
Mon P Wangc7849c22008-11-16 05:06:27 +00002497 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002498 }
2499 }
2500 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002501}
2502
2503void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2504 const Value *Op0 = I.getOperand(0);
2505 const Value *Op1 = I.getOperand(1);
2506 const Type *AggTy = I.getType();
2507 const Type *ValTy = Op1->getType();
2508 bool IntoUndef = isa<UndefValue>(Op0);
2509 bool FromUndef = isa<UndefValue>(Op1);
2510
2511 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2512 I.idx_begin(), I.idx_end());
2513
2514 SmallVector<MVT, 4> AggValueVTs;
2515 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2516 SmallVector<MVT, 4> ValValueVTs;
2517 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2518
2519 unsigned NumAggValues = AggValueVTs.size();
2520 unsigned NumValValues = ValValueVTs.size();
2521 SmallVector<SDValue, 4> Values(NumAggValues);
2522
2523 SDValue Agg = getValue(Op0);
2524 SDValue Val = getValue(Op1);
2525 unsigned i = 0;
2526 // Copy the beginning value(s) from the original aggregate.
2527 for (; i != LinearIndex; ++i)
2528 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2529 SDValue(Agg.getNode(), Agg.getResNo() + i);
2530 // Copy values from the inserted value(s).
2531 for (; i != LinearIndex + NumValValues; ++i)
2532 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2533 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2534 // Copy remaining value(s) from the original aggregate.
2535 for (; i != NumAggValues; ++i)
2536 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2537 SDValue(Agg.getNode(), Agg.getResNo() + i);
2538
Duncan Sandsaaffa052008-12-01 11:41:29 +00002539 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2540 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2541 &Values[0], NumAggValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002542}
2543
2544void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2545 const Value *Op0 = I.getOperand(0);
2546 const Type *AggTy = Op0->getType();
2547 const Type *ValTy = I.getType();
2548 bool OutOfUndef = isa<UndefValue>(Op0);
2549
2550 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2551 I.idx_begin(), I.idx_end());
2552
2553 SmallVector<MVT, 4> ValValueVTs;
2554 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2555
2556 unsigned NumValValues = ValValueVTs.size();
2557 SmallVector<SDValue, 4> Values(NumValValues);
2558
2559 SDValue Agg = getValue(Op0);
2560 // Copy out the selected value(s).
2561 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2562 Values[i - LinearIndex] =
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002563 OutOfUndef ?
2564 DAG.getNode(ISD::UNDEF,
2565 Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2566 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002567
Duncan Sandsaaffa052008-12-01 11:41:29 +00002568 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2569 DAG.getVTList(&ValValueVTs[0], NumValValues),
2570 &Values[0], NumValValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002571}
2572
2573
2574void SelectionDAGLowering::visitGetElementPtr(User &I) {
2575 SDValue N = getValue(I.getOperand(0));
2576 const Type *Ty = I.getOperand(0)->getType();
2577
2578 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2579 OI != E; ++OI) {
2580 Value *Idx = *OI;
2581 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2582 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2583 if (Field) {
2584 // N = N + Offset
2585 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2586 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2587 DAG.getIntPtrConstant(Offset));
2588 }
2589 Ty = StTy->getElementType(Field);
2590 } else {
2591 Ty = cast<SequentialType>(Ty)->getElementType();
2592
2593 // If this is a constant subscript, handle it quickly.
2594 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2595 if (CI->getZExtValue() == 0) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002596 uint64_t Offs =
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00002597 TD->getTypePaddedSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002598 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2599 DAG.getIntPtrConstant(Offs));
2600 continue;
2601 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002602
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002603 // N = N + Idx * ElementSize;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00002604 uint64_t ElementSize = TD->getTypePaddedSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002605 SDValue IdxN = getValue(Idx);
2606
2607 // If the index is smaller or larger than intptr_t, truncate or extend
2608 // it.
2609 if (IdxN.getValueType().bitsLT(N.getValueType()))
2610 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2611 else if (IdxN.getValueType().bitsGT(N.getValueType()))
2612 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2613
2614 // If this is a multiply by a power of two, turn it into a shl
2615 // immediately. This is a very common case.
2616 if (ElementSize != 1) {
2617 if (isPowerOf2_64(ElementSize)) {
2618 unsigned Amt = Log2_64(ElementSize);
2619 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2620 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2621 } else {
2622 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2623 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2624 }
2625 }
2626
2627 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2628 }
2629 }
2630 setValue(&I, N);
2631}
2632
2633void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2634 // If this is a fixed sized alloca in the entry block of the function,
2635 // allocate it statically on the stack.
2636 if (FuncInfo.StaticAllocaMap.count(&I))
2637 return; // getValue will auto-populate this.
2638
2639 const Type *Ty = I.getAllocatedType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00002640 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002641 unsigned Align =
2642 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2643 I.getAlignment());
2644
2645 SDValue AllocSize = getValue(I.getArraySize());
2646 MVT IntPtr = TLI.getPointerTy();
2647 if (IntPtr.bitsLT(AllocSize.getValueType()))
2648 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2649 else if (IntPtr.bitsGT(AllocSize.getValueType()))
2650 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2651
2652 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2653 DAG.getIntPtrConstant(TySize));
2654
2655 // Handle alignment. If the requested alignment is less than or equal to
2656 // the stack alignment, ignore it. If the size is greater than or equal to
2657 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2658 unsigned StackAlign =
2659 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2660 if (Align <= StackAlign)
2661 Align = 0;
2662
2663 // Round the size of the allocation up to the stack alignment size
2664 // by add SA-1 to the size.
2665 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2666 DAG.getIntPtrConstant(StackAlign-1));
2667 // Mask out the low bits for alignment purposes.
2668 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2669 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2670
2671 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2672 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2673 MVT::Other);
2674 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2675 setValue(&I, DSA);
2676 DAG.setRoot(DSA.getValue(1));
2677
2678 // Inform the Frame Information that we have just allocated a variable-sized
2679 // object.
2680 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2681}
2682
2683void SelectionDAGLowering::visitLoad(LoadInst &I) {
2684 const Value *SV = I.getOperand(0);
2685 SDValue Ptr = getValue(SV);
2686
2687 const Type *Ty = I.getType();
2688 bool isVolatile = I.isVolatile();
2689 unsigned Alignment = I.getAlignment();
2690
2691 SmallVector<MVT, 4> ValueVTs;
2692 SmallVector<uint64_t, 4> Offsets;
2693 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2694 unsigned NumValues = ValueVTs.size();
2695 if (NumValues == 0)
2696 return;
2697
2698 SDValue Root;
2699 bool ConstantMemory = false;
2700 if (I.isVolatile())
2701 // Serialize volatile loads with other side effects.
2702 Root = getRoot();
2703 else if (AA->pointsToConstantMemory(SV)) {
2704 // Do not serialize (non-volatile) loads of constant memory with anything.
2705 Root = DAG.getEntryNode();
2706 ConstantMemory = true;
2707 } else {
2708 // Do not serialize non-volatile loads against each other.
2709 Root = DAG.getRoot();
2710 }
2711
2712 SmallVector<SDValue, 4> Values(NumValues);
2713 SmallVector<SDValue, 4> Chains(NumValues);
2714 MVT PtrVT = Ptr.getValueType();
2715 for (unsigned i = 0; i != NumValues; ++i) {
2716 SDValue L = DAG.getLoad(ValueVTs[i], Root,
2717 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2718 DAG.getConstant(Offsets[i], PtrVT)),
2719 SV, Offsets[i],
2720 isVolatile, Alignment);
2721 Values[i] = L;
2722 Chains[i] = L.getValue(1);
2723 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002724
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002725 if (!ConstantMemory) {
2726 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2727 &Chains[0], NumValues);
2728 if (isVolatile)
2729 DAG.setRoot(Chain);
2730 else
2731 PendingLoads.push_back(Chain);
2732 }
2733
Duncan Sandsaaffa052008-12-01 11:41:29 +00002734 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2735 DAG.getVTList(&ValueVTs[0], NumValues),
2736 &Values[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002737}
2738
2739
2740void SelectionDAGLowering::visitStore(StoreInst &I) {
2741 Value *SrcV = I.getOperand(0);
2742 Value *PtrV = I.getOperand(1);
2743
2744 SmallVector<MVT, 4> ValueVTs;
2745 SmallVector<uint64_t, 4> Offsets;
2746 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2747 unsigned NumValues = ValueVTs.size();
2748 if (NumValues == 0)
2749 return;
2750
2751 // Get the lowered operands. Note that we do this after
2752 // checking if NumResults is zero, because with zero results
2753 // the operands won't have values in the map.
2754 SDValue Src = getValue(SrcV);
2755 SDValue Ptr = getValue(PtrV);
2756
2757 SDValue Root = getRoot();
2758 SmallVector<SDValue, 4> Chains(NumValues);
2759 MVT PtrVT = Ptr.getValueType();
2760 bool isVolatile = I.isVolatile();
2761 unsigned Alignment = I.getAlignment();
2762 for (unsigned i = 0; i != NumValues; ++i)
2763 Chains[i] = DAG.getStore(Root, SDValue(Src.getNode(), Src.getResNo() + i),
2764 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2765 DAG.getConstant(Offsets[i], PtrVT)),
2766 PtrV, Offsets[i],
2767 isVolatile, Alignment);
2768
2769 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2770}
2771
2772/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2773/// node.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002774void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002775 unsigned Intrinsic) {
2776 bool HasChain = !I.doesNotAccessMemory();
2777 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2778
2779 // Build the operand list.
2780 SmallVector<SDValue, 8> Ops;
2781 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2782 if (OnlyLoad) {
2783 // We don't need to serialize loads against other loads.
2784 Ops.push_back(DAG.getRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002785 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002786 Ops.push_back(getRoot());
2787 }
2788 }
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002789
2790 // Info is set by getTgtMemInstrinsic
2791 TargetLowering::IntrinsicInfo Info;
2792 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2793
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002794 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002795 if (!IsTgtIntrinsic)
2796 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002797
2798 // Add all operands of the call to the operand list.
2799 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2800 SDValue Op = getValue(I.getOperand(i));
2801 assert(TLI.isTypeLegal(Op.getValueType()) &&
2802 "Intrinsic uses a non-legal type?");
2803 Ops.push_back(Op);
2804 }
2805
2806 std::vector<MVT> VTs;
2807 if (I.getType() != Type::VoidTy) {
2808 MVT VT = TLI.getValueType(I.getType());
2809 if (VT.isVector()) {
2810 const VectorType *DestTy = cast<VectorType>(I.getType());
2811 MVT EltVT = TLI.getValueType(DestTy->getElementType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002812
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002813 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2814 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2815 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002816
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002817 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2818 VTs.push_back(VT);
2819 }
2820 if (HasChain)
2821 VTs.push_back(MVT::Other);
2822
2823 const MVT *VTList = DAG.getNodeValueTypes(VTs);
2824
2825 // Create the node.
2826 SDValue Result;
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002827 if (IsTgtIntrinsic) {
2828 // This is target intrinsic that touches memory
2829 Result = DAG.getMemIntrinsicNode(Info.opc, VTList, VTs.size(),
2830 &Ops[0], Ops.size(),
2831 Info.memVT, Info.ptrVal, Info.offset,
2832 Info.align, Info.vol,
2833 Info.readMem, Info.writeMem);
2834 }
2835 else if (!HasChain)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002836 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2837 &Ops[0], Ops.size());
2838 else if (I.getType() != Type::VoidTy)
2839 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2840 &Ops[0], Ops.size());
2841 else
2842 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2843 &Ops[0], Ops.size());
2844
2845 if (HasChain) {
2846 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2847 if (OnlyLoad)
2848 PendingLoads.push_back(Chain);
2849 else
2850 DAG.setRoot(Chain);
2851 }
2852 if (I.getType() != Type::VoidTy) {
2853 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2854 MVT VT = TLI.getValueType(PTy);
2855 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002856 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002857 setValue(&I, Result);
2858 }
2859}
2860
2861/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2862static GlobalVariable *ExtractTypeInfo(Value *V) {
2863 V = V->stripPointerCasts();
2864 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2865 assert ((GV || isa<ConstantPointerNull>(V)) &&
2866 "TypeInfo must be a global variable or NULL");
2867 return GV;
2868}
2869
2870namespace llvm {
2871
2872/// AddCatchInfo - Extract the personality and type infos from an eh.selector
2873/// call, and add them to the specified machine basic block.
2874void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2875 MachineBasicBlock *MBB) {
2876 // Inform the MachineModuleInfo of the personality for this landing pad.
2877 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2878 assert(CE->getOpcode() == Instruction::BitCast &&
2879 isa<Function>(CE->getOperand(0)) &&
2880 "Personality should be a function");
2881 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2882
2883 // Gather all the type infos for this landing pad and pass them along to
2884 // MachineModuleInfo.
2885 std::vector<GlobalVariable *> TyInfo;
2886 unsigned N = I.getNumOperands();
2887
2888 for (unsigned i = N - 1; i > 2; --i) {
2889 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2890 unsigned FilterLength = CI->getZExtValue();
2891 unsigned FirstCatch = i + FilterLength + !FilterLength;
2892 assert (FirstCatch <= N && "Invalid filter length");
2893
2894 if (FirstCatch < N) {
2895 TyInfo.reserve(N - FirstCatch);
2896 for (unsigned j = FirstCatch; j < N; ++j)
2897 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2898 MMI->addCatchTypeInfo(MBB, TyInfo);
2899 TyInfo.clear();
2900 }
2901
2902 if (!FilterLength) {
2903 // Cleanup.
2904 MMI->addCleanup(MBB);
2905 } else {
2906 // Filter.
2907 TyInfo.reserve(FilterLength - 1);
2908 for (unsigned j = i + 1; j < FirstCatch; ++j)
2909 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2910 MMI->addFilterTypeInfo(MBB, TyInfo);
2911 TyInfo.clear();
2912 }
2913
2914 N = i;
2915 }
2916 }
2917
2918 if (N > 3) {
2919 TyInfo.reserve(N - 3);
2920 for (unsigned j = 3; j < N; ++j)
2921 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2922 MMI->addCatchTypeInfo(MBB, TyInfo);
2923 }
2924}
2925
2926}
2927
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002928/// GetSignificand - Get the significand and build it into a floating-point
2929/// number with exponent of 1:
2930///
2931/// Op = (Op & 0x007fffff) | 0x3f800000;
2932///
2933/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002934static SDValue
2935GetSignificand(SelectionDAG &DAG, SDValue Op) {
Bill Wendlinge9a72862009-01-20 21:17:57 +00002936 SDValue t1 = DAG.getNode(ISD::AND, MVT::i32, Op,
2937 DAG.getConstant(0x007fffff, MVT::i32));
2938 SDValue t2 = DAG.getNode(ISD::OR, MVT::i32, t1,
2939 DAG.getConstant(0x3f800000, MVT::i32));
2940 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00002941}
2942
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002943/// GetExponent - Get the exponent:
2944///
Bill Wendlinge9a72862009-01-20 21:17:57 +00002945/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002946///
2947/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002948static SDValue
Bill Wendling6c533342009-01-20 06:10:42 +00002949GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI) {
Bill Wendlinge9a72862009-01-20 21:17:57 +00002950 SDValue t0 = DAG.getNode(ISD::AND, MVT::i32, Op,
2951 DAG.getConstant(0x7f800000, MVT::i32));
2952 SDValue t1 = DAG.getNode(ISD::SRL, MVT::i32, t0,
2953 DAG.getConstant(23, TLI.getShiftAmountTy()));
2954 SDValue t2 = DAG.getNode(ISD::SUB, MVT::i32, t1,
2955 DAG.getConstant(127, MVT::i32));
2956 return DAG.getNode(ISD::SINT_TO_FP, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00002957}
2958
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002959/// getF32Constant - Get 32-bit floating point constant.
2960static SDValue
2961getF32Constant(SelectionDAG &DAG, unsigned Flt) {
2962 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
2963}
2964
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002965/// Inlined utility function to implement binary input atomic intrinsics for
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002966/// visitIntrinsicCall: I is a call instruction
2967/// Op is the associated NodeType for I
2968const char *
2969SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002970 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00002971 SDValue L =
2972 DAG.getAtomic(Op, getValue(I.getOperand(2)).getValueType().getSimpleVT(),
2973 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002974 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00002975 getValue(I.getOperand(2)),
2976 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002977 setValue(&I, L);
2978 DAG.setRoot(L.getValue(1));
2979 return 0;
2980}
2981
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002982// implVisitAluOverflow - Lower arithmetic overflow instrinsics.
Bill Wendling74c37652008-12-09 22:08:41 +00002983const char *
2984SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002985 SDValue Op1 = getValue(I.getOperand(1));
2986 SDValue Op2 = getValue(I.getOperand(2));
Bill Wendling74c37652008-12-09 22:08:41 +00002987
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002988 MVT ValueVTs[] = { Op1.getValueType(), MVT::i1 };
2989 SDValue Ops[] = { Op1, Op2 };
Bill Wendling74c37652008-12-09 22:08:41 +00002990
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002991 SDValue Result = DAG.getNode(Op, DAG.getVTList(&ValueVTs[0], 2), &Ops[0], 2);
Bill Wendling74c37652008-12-09 22:08:41 +00002992
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002993 setValue(&I, Result);
2994 return 0;
2995}
Bill Wendling74c37652008-12-09 22:08:41 +00002996
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002997/// visitExp - Lower an exp intrinsic. Handles the special sequences for
2998/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00002999void
3000SelectionDAGLowering::visitExp(CallInst &I) {
3001 SDValue result;
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003002
3003 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3004 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3005 SDValue Op = getValue(I.getOperand(1));
3006
3007 // Put the exponent in the right bit position for later addition to the
3008 // final result:
3009 //
3010 // #define LOG2OFe 1.4426950f
3011 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3012 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003013 getF32Constant(DAG, 0x3fb8aa3b));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003014 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3015
3016 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3017 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3018 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3019
3020 // IntegerPartOfX <<= 23;
3021 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
Bill Wendling6c533342009-01-20 06:10:42 +00003022 DAG.getConstant(23, TLI.getShiftAmountTy()));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003023
3024 if (LimitFloatPrecision <= 6) {
3025 // For floating-point precision of 6:
3026 //
3027 // TwoToFractionalPartOfX =
3028 // 0.997535578f +
3029 // (0.735607626f + 0.252464424f * x) * x;
3030 //
3031 // error 0.0144103317, which is 6 bits
3032 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003033 getF32Constant(DAG, 0x3e814304));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003034 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003035 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003036 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3037 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003038 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003039 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3040
3041 // Add the exponent into the result in integer domain.
3042 SDValue t6 = DAG.getNode(ISD::ADD, MVT::i32,
3043 TwoToFracPartOfX, IntegerPartOfX);
3044
3045 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t6);
3046 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3047 // For floating-point precision of 12:
3048 //
3049 // TwoToFractionalPartOfX =
3050 // 0.999892986f +
3051 // (0.696457318f +
3052 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3053 //
3054 // 0.000107046256 error, which is 13 to 14 bits
3055 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003056 getF32Constant(DAG, 0x3da235e3));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003057 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003058 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003059 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3060 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003061 getF32Constant(DAG, 0x3f324b07));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003062 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3063 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003064 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003065 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3066
3067 // Add the exponent into the result in integer domain.
3068 SDValue t8 = DAG.getNode(ISD::ADD, MVT::i32,
3069 TwoToFracPartOfX, IntegerPartOfX);
3070
3071 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t8);
3072 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3073 // For floating-point precision of 18:
3074 //
3075 // TwoToFractionalPartOfX =
3076 // 0.999999982f +
3077 // (0.693148872f +
3078 // (0.240227044f +
3079 // (0.554906021e-1f +
3080 // (0.961591928e-2f +
3081 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3082 //
3083 // error 2.47208000*10^(-7), which is better than 18 bits
3084 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003085 getF32Constant(DAG, 0x3924b03e));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003086 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003087 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003088 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3089 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003090 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003091 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3092 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003093 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003094 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3095 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003096 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003097 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3098 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003099 getF32Constant(DAG, 0x3f317234));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003100 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3101 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003102 getF32Constant(DAG, 0x3f800000));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003103 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3104
3105 // Add the exponent into the result in integer domain.
3106 SDValue t14 = DAG.getNode(ISD::ADD, MVT::i32,
3107 TwoToFracPartOfX, IntegerPartOfX);
3108
3109 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t14);
3110 }
3111 } else {
3112 // No special expansion.
3113 result = DAG.getNode(ISD::FEXP,
3114 getValue(I.getOperand(1)).getValueType(),
3115 getValue(I.getOperand(1)));
3116 }
3117
Dale Johannesen59e577f2008-09-05 18:38:42 +00003118 setValue(&I, result);
3119}
3120
Bill Wendling39150252008-09-09 20:39:27 +00003121/// visitLog - Lower a log intrinsic. Handles the special sequences for
3122/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003123void
3124SelectionDAGLowering::visitLog(CallInst &I) {
3125 SDValue result;
Bill Wendling39150252008-09-09 20:39:27 +00003126
3127 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3128 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3129 SDValue Op = getValue(I.getOperand(1));
3130 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3131
3132 // Scale the exponent by log(2) [0.69314718f].
Bill Wendling6c533342009-01-20 06:10:42 +00003133 SDValue Exp = GetExponent(DAG, Op1, TLI);
Bill Wendling39150252008-09-09 20:39:27 +00003134 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003135 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003136
3137 // Get the significand and build it into a floating-point number with
3138 // exponent of 1.
3139 SDValue X = GetSignificand(DAG, Op1);
3140
3141 if (LimitFloatPrecision <= 6) {
3142 // For floating-point precision of 6:
3143 //
3144 // LogofMantissa =
3145 // -1.1609546f +
3146 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003147 //
Bill Wendling39150252008-09-09 20:39:27 +00003148 // error 0.0034276066, which is better than 8 bits
3149 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003150 getF32Constant(DAG, 0xbe74c456));
Bill Wendling39150252008-09-09 20:39:27 +00003151 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003152 getF32Constant(DAG, 0x3fb3a2b1));
Bill Wendling39150252008-09-09 20:39:27 +00003153 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3154 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003155 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00003156
3157 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3158 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3159 // For floating-point precision of 12:
3160 //
3161 // LogOfMantissa =
3162 // -1.7417939f +
3163 // (2.8212026f +
3164 // (-1.4699568f +
3165 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3166 //
3167 // error 0.000061011436, which is 14 bits
3168 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003169 getF32Constant(DAG, 0xbd67b6d6));
Bill Wendling39150252008-09-09 20:39:27 +00003170 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003171 getF32Constant(DAG, 0x3ee4f4b8));
Bill Wendling39150252008-09-09 20:39:27 +00003172 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3173 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003174 getF32Constant(DAG, 0x3fbc278b));
Bill Wendling39150252008-09-09 20:39:27 +00003175 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3176 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003177 getF32Constant(DAG, 0x40348e95));
Bill Wendling39150252008-09-09 20:39:27 +00003178 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3179 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003180 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00003181
3182 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3183 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3184 // For floating-point precision of 18:
3185 //
3186 // LogOfMantissa =
3187 // -2.1072184f +
3188 // (4.2372794f +
3189 // (-3.7029485f +
3190 // (2.2781945f +
3191 // (-0.87823314f +
3192 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3193 //
3194 // error 0.0000023660568, which is better than 18 bits
3195 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003196 getF32Constant(DAG, 0xbc91e5ac));
Bill Wendling39150252008-09-09 20:39:27 +00003197 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003198 getF32Constant(DAG, 0x3e4350aa));
Bill Wendling39150252008-09-09 20:39:27 +00003199 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3200 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003201 getF32Constant(DAG, 0x3f60d3e3));
Bill Wendling39150252008-09-09 20:39:27 +00003202 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3203 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003204 getF32Constant(DAG, 0x4011cdf0));
Bill Wendling39150252008-09-09 20:39:27 +00003205 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3206 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003207 getF32Constant(DAG, 0x406cfd1c));
Bill Wendling39150252008-09-09 20:39:27 +00003208 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3209 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003210 getF32Constant(DAG, 0x408797cb));
Bill Wendling39150252008-09-09 20:39:27 +00003211 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3212 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003213 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003214
3215 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3216 }
3217 } else {
3218 // No special expansion.
3219 result = DAG.getNode(ISD::FLOG,
3220 getValue(I.getOperand(1)).getValueType(),
3221 getValue(I.getOperand(1)));
3222 }
3223
Dale Johannesen59e577f2008-09-05 18:38:42 +00003224 setValue(&I, result);
3225}
3226
Bill Wendling3eb59402008-09-09 00:28:24 +00003227/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3228/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003229void
3230SelectionDAGLowering::visitLog2(CallInst &I) {
3231 SDValue result;
Bill Wendling3eb59402008-09-09 00:28:24 +00003232
Dale Johannesen853244f2008-09-05 23:49:37 +00003233 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003234 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3235 SDValue Op = getValue(I.getOperand(1));
3236 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3237
Bill Wendling39150252008-09-09 20:39:27 +00003238 // Get the exponent.
Bill Wendling6c533342009-01-20 06:10:42 +00003239 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI);
Bill Wendling3eb59402008-09-09 00:28:24 +00003240
3241 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003242 // exponent of 1.
3243 SDValue X = GetSignificand(DAG, Op1);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003244
Bill Wendling3eb59402008-09-09 00:28:24 +00003245 // Different possible minimax approximations of significand in
3246 // floating-point for various degrees of accuracy over [1,2].
3247 if (LimitFloatPrecision <= 6) {
3248 // For floating-point precision of 6:
3249 //
3250 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3251 //
3252 // error 0.0049451742, which is more than 7 bits
Bill Wendling39150252008-09-09 20:39:27 +00003253 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003254 getF32Constant(DAG, 0xbeb08fe0));
Bill Wendling39150252008-09-09 20:39:27 +00003255 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003256 getF32Constant(DAG, 0x40019463));
Bill Wendling39150252008-09-09 20:39:27 +00003257 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3258 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003259 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003260
3261 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3262 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3263 // For floating-point precision of 12:
3264 //
3265 // Log2ofMantissa =
3266 // -2.51285454f +
3267 // (4.07009056f +
3268 // (-2.12067489f +
3269 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003270 //
Bill Wendling3eb59402008-09-09 00:28:24 +00003271 // error 0.0000876136000, which is better than 13 bits
Bill Wendling39150252008-09-09 20:39:27 +00003272 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003273 getF32Constant(DAG, 0xbda7262e));
Bill Wendling39150252008-09-09 20:39:27 +00003274 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003275 getF32Constant(DAG, 0x3f25280b));
Bill Wendling39150252008-09-09 20:39:27 +00003276 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3277 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003278 getF32Constant(DAG, 0x4007b923));
Bill Wendling39150252008-09-09 20:39:27 +00003279 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3280 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003281 getF32Constant(DAG, 0x40823e2f));
Bill Wendling39150252008-09-09 20:39:27 +00003282 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3283 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003284 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003285
3286 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3287 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3288 // For floating-point precision of 18:
3289 //
3290 // Log2ofMantissa =
3291 // -3.0400495f +
3292 // (6.1129976f +
3293 // (-5.3420409f +
3294 // (3.2865683f +
3295 // (-1.2669343f +
3296 // (0.27515199f -
3297 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3298 //
3299 // error 0.0000018516, which is better than 18 bits
Bill Wendling39150252008-09-09 20:39:27 +00003300 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003301 getF32Constant(DAG, 0xbcd2769e));
Bill Wendling39150252008-09-09 20:39:27 +00003302 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003303 getF32Constant(DAG, 0x3e8ce0b9));
Bill Wendling39150252008-09-09 20:39:27 +00003304 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3305 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003306 getF32Constant(DAG, 0x3fa22ae7));
Bill Wendling39150252008-09-09 20:39:27 +00003307 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3308 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003309 getF32Constant(DAG, 0x40525723));
Bill Wendling39150252008-09-09 20:39:27 +00003310 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3311 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003312 getF32Constant(DAG, 0x40aaf200));
Bill Wendling39150252008-09-09 20:39:27 +00003313 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3314 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003315 getF32Constant(DAG, 0x40c39dad));
Bill Wendling3eb59402008-09-09 00:28:24 +00003316 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
Bill Wendling39150252008-09-09 20:39:27 +00003317 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003318 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003319
3320 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3321 }
Dale Johannesen853244f2008-09-05 23:49:37 +00003322 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003323 // No special expansion.
Dale Johannesen853244f2008-09-05 23:49:37 +00003324 result = DAG.getNode(ISD::FLOG2,
3325 getValue(I.getOperand(1)).getValueType(),
3326 getValue(I.getOperand(1)));
3327 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003328
Dale Johannesen59e577f2008-09-05 18:38:42 +00003329 setValue(&I, result);
3330}
3331
Bill Wendling3eb59402008-09-09 00:28:24 +00003332/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3333/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003334void
3335SelectionDAGLowering::visitLog10(CallInst &I) {
3336 SDValue result;
Bill Wendling181b6272008-10-19 20:34:04 +00003337
Dale Johannesen852680a2008-09-05 21:27:19 +00003338 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003339 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3340 SDValue Op = getValue(I.getOperand(1));
3341 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3342
Bill Wendling39150252008-09-09 20:39:27 +00003343 // Scale the exponent by log10(2) [0.30102999f].
Bill Wendling6c533342009-01-20 06:10:42 +00003344 SDValue Exp = GetExponent(DAG, Op1, TLI);
Bill Wendling39150252008-09-09 20:39:27 +00003345 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003346 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003347
3348 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003349 // exponent of 1.
3350 SDValue X = GetSignificand(DAG, Op1);
Bill Wendling3eb59402008-09-09 00:28:24 +00003351
3352 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003353 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003354 //
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003355 // Log10ofMantissa =
3356 // -0.50419619f +
3357 // (0.60948995f - 0.10380950f * x) * x;
3358 //
3359 // error 0.0014886165, which is 6 bits
Bill Wendling39150252008-09-09 20:39:27 +00003360 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003361 getF32Constant(DAG, 0xbdd49a13));
Bill Wendling39150252008-09-09 20:39:27 +00003362 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003363 getF32Constant(DAG, 0x3f1c0789));
Bill Wendling39150252008-09-09 20:39:27 +00003364 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3365 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003366 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003367
3368 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003369 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3370 // For floating-point precision of 12:
3371 //
3372 // Log10ofMantissa =
3373 // -0.64831180f +
3374 // (0.91751397f +
3375 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3376 //
3377 // error 0.00019228036, which is better than 12 bits
Bill Wendling39150252008-09-09 20:39:27 +00003378 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003379 getF32Constant(DAG, 0x3d431f31));
Bill Wendling39150252008-09-09 20:39:27 +00003380 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003381 getF32Constant(DAG, 0x3ea21fb2));
Bill Wendling39150252008-09-09 20:39:27 +00003382 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3383 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003384 getF32Constant(DAG, 0x3f6ae232));
Bill Wendling39150252008-09-09 20:39:27 +00003385 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3386 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003387 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00003388
3389 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3390 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003391 // For floating-point precision of 18:
3392 //
3393 // Log10ofMantissa =
3394 // -0.84299375f +
3395 // (1.5327582f +
3396 // (-1.0688956f +
3397 // (0.49102474f +
3398 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3399 //
3400 // error 0.0000037995730, which is better than 18 bits
Bill Wendling39150252008-09-09 20:39:27 +00003401 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003402 getF32Constant(DAG, 0x3c5d51ce));
Bill Wendling39150252008-09-09 20:39:27 +00003403 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003404 getF32Constant(DAG, 0x3e00685a));
Bill Wendling39150252008-09-09 20:39:27 +00003405 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3406 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003407 getF32Constant(DAG, 0x3efb6798));
Bill Wendling39150252008-09-09 20:39:27 +00003408 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3409 SDValue t5 = DAG.getNode(ISD::FSUB, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003410 getF32Constant(DAG, 0x3f88d192));
Bill Wendling39150252008-09-09 20:39:27 +00003411 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3412 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003413 getF32Constant(DAG, 0x3fc4316c));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003414 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
Bill Wendling39150252008-09-09 20:39:27 +00003415 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003416 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003417
3418 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003419 }
Dale Johannesen852680a2008-09-05 21:27:19 +00003420 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003421 // No special expansion.
Dale Johannesen852680a2008-09-05 21:27:19 +00003422 result = DAG.getNode(ISD::FLOG10,
3423 getValue(I.getOperand(1)).getValueType(),
3424 getValue(I.getOperand(1)));
3425 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003426
Dale Johannesen59e577f2008-09-05 18:38:42 +00003427 setValue(&I, result);
3428}
3429
Bill Wendlinge10c8142008-09-09 22:39:21 +00003430/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3431/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003432void
3433SelectionDAGLowering::visitExp2(CallInst &I) {
3434 SDValue result;
Bill Wendlinge10c8142008-09-09 22:39:21 +00003435
Dale Johannesen601d3c02008-09-05 01:48:15 +00003436 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00003437 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3438 SDValue Op = getValue(I.getOperand(1));
3439
3440 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, Op);
3441
3442 // FractionalPartOfX = x - (float)IntegerPartOfX;
3443 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3444 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, Op, t1);
3445
3446 // IntegerPartOfX <<= 23;
3447 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
Bill Wendling6c533342009-01-20 06:10:42 +00003448 DAG.getConstant(23, TLI.getShiftAmountTy()));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003449
3450 if (LimitFloatPrecision <= 6) {
3451 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003452 //
Bill Wendlinge10c8142008-09-09 22:39:21 +00003453 // TwoToFractionalPartOfX =
3454 // 0.997535578f +
3455 // (0.735607626f + 0.252464424f * x) * x;
3456 //
3457 // error 0.0144103317, which is 6 bits
3458 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003459 getF32Constant(DAG, 0x3e814304));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003460 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003461 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003462 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003463 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003464 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003465 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3466 SDValue TwoToFractionalPartOfX =
3467 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3468
3469 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3470 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3471 // For floating-point precision of 12:
3472 //
3473 // TwoToFractionalPartOfX =
3474 // 0.999892986f +
3475 // (0.696457318f +
3476 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3477 //
3478 // error 0.000107046256, which is 13 to 14 bits
3479 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003480 getF32Constant(DAG, 0x3da235e3));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003481 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003482 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003483 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003484 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003485 getF32Constant(DAG, 0x3f324b07));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003486 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3487 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003488 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003489 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3490 SDValue TwoToFractionalPartOfX =
3491 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3492
3493 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3494 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3495 // For floating-point precision of 18:
3496 //
3497 // TwoToFractionalPartOfX =
3498 // 0.999999982f +
3499 // (0.693148872f +
3500 // (0.240227044f +
3501 // (0.554906021e-1f +
3502 // (0.961591928e-2f +
3503 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3504 // error 2.47208000*10^(-7), which is better than 18 bits
3505 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003506 getF32Constant(DAG, 0x3924b03e));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003507 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003508 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003509 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003510 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003511 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003512 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3513 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003514 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003515 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3516 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003517 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003518 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3519 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003520 getF32Constant(DAG, 0x3f317234));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003521 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3522 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003523 getF32Constant(DAG, 0x3f800000));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003524 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3525 SDValue TwoToFractionalPartOfX =
3526 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3527
3528 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3529 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00003530 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003531 // No special expansion.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003532 result = DAG.getNode(ISD::FEXP2,
3533 getValue(I.getOperand(1)).getValueType(),
3534 getValue(I.getOperand(1)));
3535 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00003536
Dale Johannesen601d3c02008-09-05 01:48:15 +00003537 setValue(&I, result);
3538}
3539
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003540/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3541/// limited-precision mode with x == 10.0f.
3542void
3543SelectionDAGLowering::visitPow(CallInst &I) {
3544 SDValue result;
3545 Value *Val = I.getOperand(1);
3546 bool IsExp10 = false;
3547
3548 if (getValue(Val).getValueType() == MVT::f32 &&
Bill Wendling277fc242008-09-10 00:24:59 +00003549 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003550 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3551 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3552 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3553 APFloat Ten(10.0f);
3554 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3555 }
3556 }
3557 }
3558
3559 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3560 SDValue Op = getValue(I.getOperand(2));
3561
3562 // Put the exponent in the right bit position for later addition to the
3563 // final result:
3564 //
3565 // #define LOG2OF10 3.3219281f
3566 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3567 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003568 getF32Constant(DAG, 0x40549a78));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003569 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3570
3571 // FractionalPartOfX = x - (float)IntegerPartOfX;
3572 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3573 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3574
3575 // IntegerPartOfX <<= 23;
3576 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
Bill Wendling6c533342009-01-20 06:10:42 +00003577 DAG.getConstant(23, TLI.getShiftAmountTy()));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003578
3579 if (LimitFloatPrecision <= 6) {
3580 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003581 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003582 // twoToFractionalPartOfX =
3583 // 0.997535578f +
3584 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003585 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003586 // error 0.0144103317, which is 6 bits
3587 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003588 getF32Constant(DAG, 0x3e814304));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003589 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003590 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003591 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003592 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003593 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003594 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3595 SDValue TwoToFractionalPartOfX =
3596 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3597
3598 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3599 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3600 // For floating-point precision of 12:
3601 //
3602 // TwoToFractionalPartOfX =
3603 // 0.999892986f +
3604 // (0.696457318f +
3605 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3606 //
3607 // error 0.000107046256, which is 13 to 14 bits
3608 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003609 getF32Constant(DAG, 0x3da235e3));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003610 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003611 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003612 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003613 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003614 getF32Constant(DAG, 0x3f324b07));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003615 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3616 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003617 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003618 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3619 SDValue TwoToFractionalPartOfX =
3620 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3621
3622 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3623 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3624 // For floating-point precision of 18:
3625 //
3626 // TwoToFractionalPartOfX =
3627 // 0.999999982f +
3628 // (0.693148872f +
3629 // (0.240227044f +
3630 // (0.554906021e-1f +
3631 // (0.961591928e-2f +
3632 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3633 // error 2.47208000*10^(-7), which is better than 18 bits
3634 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003635 getF32Constant(DAG, 0x3924b03e));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003636 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003637 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003638 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003639 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003640 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003641 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3642 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003643 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003644 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3645 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003646 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003647 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3648 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003649 getF32Constant(DAG, 0x3f317234));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003650 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3651 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003652 getF32Constant(DAG, 0x3f800000));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003653 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3654 SDValue TwoToFractionalPartOfX =
3655 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3656
3657 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3658 }
3659 } else {
3660 // No special expansion.
3661 result = DAG.getNode(ISD::FPOW,
3662 getValue(I.getOperand(1)).getValueType(),
3663 getValue(I.getOperand(1)),
3664 getValue(I.getOperand(2)));
3665 }
3666
3667 setValue(&I, result);
3668}
3669
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003670/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3671/// we want to emit this as a call to a named external function, return the name
3672/// otherwise lower it and return null.
3673const char *
3674SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3675 switch (Intrinsic) {
3676 default:
3677 // By default, turn this into a target intrinsic node.
3678 visitTargetIntrinsic(I, Intrinsic);
3679 return 0;
3680 case Intrinsic::vastart: visitVAStart(I); return 0;
3681 case Intrinsic::vaend: visitVAEnd(I); return 0;
3682 case Intrinsic::vacopy: visitVACopy(I); return 0;
3683 case Intrinsic::returnaddress:
3684 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3685 getValue(I.getOperand(1))));
3686 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00003687 case Intrinsic::frameaddress:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003688 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3689 getValue(I.getOperand(1))));
3690 return 0;
3691 case Intrinsic::setjmp:
3692 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3693 break;
3694 case Intrinsic::longjmp:
3695 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3696 break;
Chris Lattner824b9582008-11-21 16:42:48 +00003697 case Intrinsic::memcpy: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003698 SDValue Op1 = getValue(I.getOperand(1));
3699 SDValue Op2 = getValue(I.getOperand(2));
3700 SDValue Op3 = getValue(I.getOperand(3));
3701 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3702 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3703 I.getOperand(1), 0, I.getOperand(2), 0));
3704 return 0;
3705 }
Chris Lattner824b9582008-11-21 16:42:48 +00003706 case Intrinsic::memset: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003707 SDValue Op1 = getValue(I.getOperand(1));
3708 SDValue Op2 = getValue(I.getOperand(2));
3709 SDValue Op3 = getValue(I.getOperand(3));
3710 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3711 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3712 I.getOperand(1), 0));
3713 return 0;
3714 }
Chris Lattner824b9582008-11-21 16:42:48 +00003715 case Intrinsic::memmove: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003716 SDValue Op1 = getValue(I.getOperand(1));
3717 SDValue Op2 = getValue(I.getOperand(2));
3718 SDValue Op3 = getValue(I.getOperand(3));
3719 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3720
3721 // If the source and destination are known to not be aliases, we can
3722 // lower memmove as memcpy.
3723 uint64_t Size = -1ULL;
3724 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003725 Size = C->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003726 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3727 AliasAnalysis::NoAlias) {
3728 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3729 I.getOperand(1), 0, I.getOperand(2), 0));
3730 return 0;
3731 }
3732
3733 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3734 I.getOperand(1), 0, I.getOperand(2), 0));
3735 return 0;
3736 }
3737 case Intrinsic::dbg_stoppoint: {
Devang Patel83489bb2009-01-13 00:35:13 +00003738 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003739 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Devang Patelb79b5352009-01-19 23:21:49 +00003740 if (DW && DW->ValidDebugInfo(SPI.getContext()))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003741 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3742 SPI.getLine(),
3743 SPI.getColumn(),
Devang Patel83489bb2009-01-13 00:35:13 +00003744 SPI.getContext()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003745 return 0;
3746 }
3747 case Intrinsic::dbg_region_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003748 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003749 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Devang Patelb79b5352009-01-19 23:21:49 +00003750 if (DW && DW->ValidDebugInfo(RSI.getContext())) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003751 unsigned LabelID =
Devang Patel83489bb2009-01-13 00:35:13 +00003752 DW->RecordRegionStart(cast<GlobalVariable>(RSI.getContext()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003753 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3754 }
3755
3756 return 0;
3757 }
3758 case Intrinsic::dbg_region_end: {
Devang Patel83489bb2009-01-13 00:35:13 +00003759 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003760 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Devang Patelb79b5352009-01-19 23:21:49 +00003761 if (DW && DW->ValidDebugInfo(REI.getContext())) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003762 unsigned LabelID =
Devang Patel83489bb2009-01-13 00:35:13 +00003763 DW->RecordRegionEnd(cast<GlobalVariable>(REI.getContext()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003764 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3765 }
3766
3767 return 0;
3768 }
3769 case Intrinsic::dbg_func_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003770 DwarfWriter *DW = DAG.getDwarfWriter();
3771 if (!DW) return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003772 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3773 Value *SP = FSI.getSubprogram();
Devang Patelcf3a4482009-01-15 23:41:32 +00003774 if (SP && DW->ValidDebugInfo(SP)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003775 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3776 // what (most?) gdb expects.
Devang Patel83489bb2009-01-13 00:35:13 +00003777 DISubprogram Subprogram(cast<GlobalVariable>(SP));
3778 DICompileUnit CompileUnit = Subprogram.getCompileUnit();
3779 unsigned SrcFile = DW->RecordSource(CompileUnit.getDirectory(),
3780 CompileUnit.getFilename());
Devang Patel20dd0462008-11-06 00:30:09 +00003781 // Record the source line but does not create a label for the normal
3782 // function start. It will be emitted at asm emission time. However,
3783 // create a label if this is a beginning of inlined function.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003784 unsigned LabelID =
Devang Patel83489bb2009-01-13 00:35:13 +00003785 DW->RecordSourceLine(Subprogram.getLineNumber(), 0, SrcFile);
3786 if (DW->getRecordSourceLineCount() != 1)
Devang Patel20dd0462008-11-06 00:30:09 +00003787 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003788 }
3789
3790 return 0;
3791 }
3792 case Intrinsic::dbg_declare: {
Devang Patel83489bb2009-01-13 00:35:13 +00003793 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003794 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3795 Value *Variable = DI.getVariable();
Devang Patelb79b5352009-01-19 23:21:49 +00003796 if (DW && DW->ValidDebugInfo(Variable))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003797 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3798 getValue(DI.getAddress()), getValue(Variable)));
3799 return 0;
3800 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003801
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003802 case Intrinsic::eh_exception: {
3803 if (!CurMBB->isLandingPad()) {
3804 // FIXME: Mark exception register as live in. Hack for PR1508.
3805 unsigned Reg = TLI.getExceptionAddressRegister();
3806 if (Reg) CurMBB->addLiveIn(Reg);
3807 }
3808 // Insert the EXCEPTIONADDR instruction.
3809 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3810 SDValue Ops[1];
3811 Ops[0] = DAG.getRoot();
3812 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3813 setValue(&I, Op);
3814 DAG.setRoot(Op.getValue(1));
3815 return 0;
3816 }
3817
3818 case Intrinsic::eh_selector_i32:
3819 case Intrinsic::eh_selector_i64: {
3820 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3821 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3822 MVT::i32 : MVT::i64);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003823
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003824 if (MMI) {
3825 if (CurMBB->isLandingPad())
3826 AddCatchInfo(I, MMI, CurMBB);
3827 else {
3828#ifndef NDEBUG
3829 FuncInfo.CatchInfoLost.insert(&I);
3830#endif
3831 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3832 unsigned Reg = TLI.getExceptionSelectorRegister();
3833 if (Reg) CurMBB->addLiveIn(Reg);
3834 }
3835
3836 // Insert the EHSELECTION instruction.
3837 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3838 SDValue Ops[2];
3839 Ops[0] = getValue(I.getOperand(1));
3840 Ops[1] = getRoot();
3841 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3842 setValue(&I, Op);
3843 DAG.setRoot(Op.getValue(1));
3844 } else {
3845 setValue(&I, DAG.getConstant(0, VT));
3846 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003847
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003848 return 0;
3849 }
3850
3851 case Intrinsic::eh_typeid_for_i32:
3852 case Intrinsic::eh_typeid_for_i64: {
3853 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3854 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3855 MVT::i32 : MVT::i64);
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003856
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003857 if (MMI) {
3858 // Find the type id for the given typeinfo.
3859 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3860
3861 unsigned TypeID = MMI->getTypeIDFor(GV);
3862 setValue(&I, DAG.getConstant(TypeID, VT));
3863 } else {
3864 // Return something different to eh_selector.
3865 setValue(&I, DAG.getConstant(1, VT));
3866 }
3867
3868 return 0;
3869 }
3870
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003871 case Intrinsic::eh_return_i32:
3872 case Intrinsic::eh_return_i64:
3873 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003874 MMI->setCallsEHReturn(true);
3875 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3876 MVT::Other,
3877 getControlRoot(),
3878 getValue(I.getOperand(1)),
3879 getValue(I.getOperand(2))));
3880 } else {
3881 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3882 }
3883
3884 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003885 case Intrinsic::eh_unwind_init:
3886 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3887 MMI->setCallsUnwindInit(true);
3888 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003889
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003890 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003891
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003892 case Intrinsic::eh_dwarf_cfa: {
3893 MVT VT = getValue(I.getOperand(1)).getValueType();
3894 SDValue CfaArg;
3895 if (VT.bitsGT(TLI.getPointerTy()))
3896 CfaArg = DAG.getNode(ISD::TRUNCATE,
3897 TLI.getPointerTy(), getValue(I.getOperand(1)));
3898 else
3899 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3900 TLI.getPointerTy(), getValue(I.getOperand(1)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003901
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003902 SDValue Offset = DAG.getNode(ISD::ADD,
3903 TLI.getPointerTy(),
3904 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3905 TLI.getPointerTy()),
3906 CfaArg);
3907 setValue(&I, DAG.getNode(ISD::ADD,
3908 TLI.getPointerTy(),
3909 DAG.getNode(ISD::FRAMEADDR,
3910 TLI.getPointerTy(),
3911 DAG.getConstant(0,
3912 TLI.getPointerTy())),
3913 Offset));
3914 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003915 }
3916
Mon P Wang77cdf302008-11-10 20:54:11 +00003917 case Intrinsic::convertff:
3918 case Intrinsic::convertfsi:
3919 case Intrinsic::convertfui:
3920 case Intrinsic::convertsif:
3921 case Intrinsic::convertuif:
3922 case Intrinsic::convertss:
3923 case Intrinsic::convertsu:
3924 case Intrinsic::convertus:
3925 case Intrinsic::convertuu: {
3926 ISD::CvtCode Code = ISD::CVT_INVALID;
3927 switch (Intrinsic) {
3928 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
3929 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
3930 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
3931 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
3932 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
3933 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
3934 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
3935 case Intrinsic::convertus: Code = ISD::CVT_US; break;
3936 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
3937 }
3938 MVT DestVT = TLI.getValueType(I.getType());
3939 Value* Op1 = I.getOperand(1);
3940 setValue(&I, DAG.getConvertRndSat(DestVT, getValue(Op1),
3941 DAG.getValueType(DestVT),
3942 DAG.getValueType(getValue(Op1).getValueType()),
3943 getValue(I.getOperand(2)),
3944 getValue(I.getOperand(3)),
3945 Code));
3946 return 0;
3947 }
3948
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003949 case Intrinsic::sqrt:
3950 setValue(&I, DAG.getNode(ISD::FSQRT,
3951 getValue(I.getOperand(1)).getValueType(),
3952 getValue(I.getOperand(1))));
3953 return 0;
3954 case Intrinsic::powi:
3955 setValue(&I, DAG.getNode(ISD::FPOWI,
3956 getValue(I.getOperand(1)).getValueType(),
3957 getValue(I.getOperand(1)),
3958 getValue(I.getOperand(2))));
3959 return 0;
3960 case Intrinsic::sin:
3961 setValue(&I, DAG.getNode(ISD::FSIN,
3962 getValue(I.getOperand(1)).getValueType(),
3963 getValue(I.getOperand(1))));
3964 return 0;
3965 case Intrinsic::cos:
3966 setValue(&I, DAG.getNode(ISD::FCOS,
3967 getValue(I.getOperand(1)).getValueType(),
3968 getValue(I.getOperand(1))));
3969 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003970 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003971 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003972 return 0;
3973 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003974 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003975 return 0;
3976 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003977 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003978 return 0;
3979 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003980 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003981 return 0;
3982 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00003983 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003984 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003985 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003986 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003987 return 0;
3988 case Intrinsic::pcmarker: {
3989 SDValue Tmp = getValue(I.getOperand(1));
3990 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3991 return 0;
3992 }
3993 case Intrinsic::readcyclecounter: {
3994 SDValue Op = getRoot();
3995 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3996 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3997 &Op, 1);
3998 setValue(&I, Tmp);
3999 DAG.setRoot(Tmp.getValue(1));
4000 return 0;
4001 }
4002 case Intrinsic::part_select: {
4003 // Currently not implemented: just abort
4004 assert(0 && "part_select intrinsic not implemented");
4005 abort();
4006 }
4007 case Intrinsic::part_set: {
4008 // Currently not implemented: just abort
4009 assert(0 && "part_set intrinsic not implemented");
4010 abort();
4011 }
4012 case Intrinsic::bswap:
4013 setValue(&I, DAG.getNode(ISD::BSWAP,
4014 getValue(I.getOperand(1)).getValueType(),
4015 getValue(I.getOperand(1))));
4016 return 0;
4017 case Intrinsic::cttz: {
4018 SDValue Arg = getValue(I.getOperand(1));
4019 MVT Ty = Arg.getValueType();
4020 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
4021 setValue(&I, result);
4022 return 0;
4023 }
4024 case Intrinsic::ctlz: {
4025 SDValue Arg = getValue(I.getOperand(1));
4026 MVT Ty = Arg.getValueType();
4027 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
4028 setValue(&I, result);
4029 return 0;
4030 }
4031 case Intrinsic::ctpop: {
4032 SDValue Arg = getValue(I.getOperand(1));
4033 MVT Ty = Arg.getValueType();
4034 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
4035 setValue(&I, result);
4036 return 0;
4037 }
4038 case Intrinsic::stacksave: {
4039 SDValue Op = getRoot();
4040 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
4041 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
4042 setValue(&I, Tmp);
4043 DAG.setRoot(Tmp.getValue(1));
4044 return 0;
4045 }
4046 case Intrinsic::stackrestore: {
4047 SDValue Tmp = getValue(I.getOperand(1));
4048 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
4049 return 0;
4050 }
Bill Wendling57344502008-11-18 11:01:33 +00004051 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00004052 // Emit code into the DAG to store the stack guard onto the stack.
4053 MachineFunction &MF = DAG.getMachineFunction();
4054 MachineFrameInfo *MFI = MF.getFrameInfo();
4055 MVT PtrTy = TLI.getPointerTy();
4056
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004057 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4058 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
Bill Wendlingb2a42982008-11-06 02:29:10 +00004059
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004060 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00004061 MFI->setStackProtectorIndex(FI);
4062
4063 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4064
4065 // Store the stack protector onto the stack.
4066 SDValue Result = DAG.getStore(getRoot(), Src, FIN,
4067 PseudoSourceValue::getFixedStack(FI),
4068 0, true);
4069 setValue(&I, Result);
4070 DAG.setRoot(Result);
4071 return 0;
4072 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004073 case Intrinsic::var_annotation:
4074 // Discard annotate attributes
4075 return 0;
4076
4077 case Intrinsic::init_trampoline: {
4078 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4079
4080 SDValue Ops[6];
4081 Ops[0] = getRoot();
4082 Ops[1] = getValue(I.getOperand(1));
4083 Ops[2] = getValue(I.getOperand(2));
4084 Ops[3] = getValue(I.getOperand(3));
4085 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4086 Ops[5] = DAG.getSrcValue(F);
4087
4088 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
4089 DAG.getNodeValueTypes(TLI.getPointerTy(),
4090 MVT::Other), 2,
4091 Ops, 6);
4092
4093 setValue(&I, Tmp);
4094 DAG.setRoot(Tmp.getValue(1));
4095 return 0;
4096 }
4097
4098 case Intrinsic::gcroot:
4099 if (GFI) {
4100 Value *Alloca = I.getOperand(1);
4101 Constant *TypeMap = cast<Constant>(I.getOperand(2));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004102
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004103 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4104 GFI->addStackRoot(FI->getIndex(), TypeMap);
4105 }
4106 return 0;
4107
4108 case Intrinsic::gcread:
4109 case Intrinsic::gcwrite:
4110 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
4111 return 0;
4112
4113 case Intrinsic::flt_rounds: {
4114 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
4115 return 0;
4116 }
4117
4118 case Intrinsic::trap: {
4119 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
4120 return 0;
4121 }
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004122
Bill Wendlingef375462008-11-21 02:38:44 +00004123 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00004124 return implVisitAluOverflow(I, ISD::UADDO);
4125 case Intrinsic::sadd_with_overflow:
4126 return implVisitAluOverflow(I, ISD::SADDO);
4127 case Intrinsic::usub_with_overflow:
4128 return implVisitAluOverflow(I, ISD::USUBO);
4129 case Intrinsic::ssub_with_overflow:
4130 return implVisitAluOverflow(I, ISD::SSUBO);
4131 case Intrinsic::umul_with_overflow:
4132 return implVisitAluOverflow(I, ISD::UMULO);
4133 case Intrinsic::smul_with_overflow:
4134 return implVisitAluOverflow(I, ISD::SMULO);
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004135
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004136 case Intrinsic::prefetch: {
4137 SDValue Ops[4];
4138 Ops[0] = getRoot();
4139 Ops[1] = getValue(I.getOperand(1));
4140 Ops[2] = getValue(I.getOperand(2));
4141 Ops[3] = getValue(I.getOperand(3));
4142 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
4143 return 0;
4144 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004145
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004146 case Intrinsic::memory_barrier: {
4147 SDValue Ops[6];
4148 Ops[0] = getRoot();
4149 for (int x = 1; x < 6; ++x)
4150 Ops[x] = getValue(I.getOperand(x));
4151
4152 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
4153 return 0;
4154 }
4155 case Intrinsic::atomic_cmp_swap: {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004156 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004157 SDValue L =
4158 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP,
4159 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4160 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004161 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004162 getValue(I.getOperand(2)),
4163 getValue(I.getOperand(3)),
4164 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004165 setValue(&I, L);
4166 DAG.setRoot(L.getValue(1));
4167 return 0;
4168 }
4169 case Intrinsic::atomic_load_add:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004170 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004171 case Intrinsic::atomic_load_sub:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004172 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004173 case Intrinsic::atomic_load_or:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004174 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004175 case Intrinsic::atomic_load_xor:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004176 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004177 case Intrinsic::atomic_load_and:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004178 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004179 case Intrinsic::atomic_load_nand:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004180 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004181 case Intrinsic::atomic_load_max:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004182 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004183 case Intrinsic::atomic_load_min:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004184 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004185 case Intrinsic::atomic_load_umin:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004186 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004187 case Intrinsic::atomic_load_umax:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004188 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004189 case Intrinsic::atomic_swap:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004190 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004191 }
4192}
4193
4194
4195void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4196 bool IsTailCall,
4197 MachineBasicBlock *LandingPad) {
4198 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4199 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4200 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4201 unsigned BeginLabel = 0, EndLabel = 0;
4202
4203 TargetLowering::ArgListTy Args;
4204 TargetLowering::ArgListEntry Entry;
4205 Args.reserve(CS.arg_size());
4206 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4207 i != e; ++i) {
4208 SDValue ArgNode = getValue(*i);
4209 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4210
4211 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00004212 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4213 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4214 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4215 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4216 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4217 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004218 Entry.Alignment = CS.getParamAlignment(attrInd);
4219 Args.push_back(Entry);
4220 }
4221
4222 if (LandingPad && MMI) {
4223 // Insert a label before the invoke call to mark the try range. This can be
4224 // used to detect deletion of the invoke via the MachineModuleInfo.
4225 BeginLabel = MMI->NextLabelID();
4226 // Both PendingLoads and PendingExports must be flushed here;
4227 // this call might not return.
4228 (void)getRoot();
4229 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
4230 }
4231
4232 std::pair<SDValue,SDValue> Result =
4233 TLI.LowerCallTo(getRoot(), CS.getType(),
Devang Patel05988662008-09-25 21:00:45 +00004234 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004235 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4236 CS.paramHasAttr(0, Attribute::InReg),
4237 CS.getCallingConv(),
Dan Gohman1937e2f2008-09-16 01:42:28 +00004238 IsTailCall && PerformTailCallOpt,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004239 Callee, Args, DAG);
4240 if (CS.getType() != Type::VoidTy)
4241 setValue(CS.getInstruction(), Result.first);
4242 DAG.setRoot(Result.second);
4243
4244 if (LandingPad && MMI) {
4245 // Insert a label at the end of the invoke call to mark the try range. This
4246 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4247 EndLabel = MMI->NextLabelID();
4248 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
4249
4250 // Inform MachineModuleInfo of range.
4251 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4252 }
4253}
4254
4255
4256void SelectionDAGLowering::visitCall(CallInst &I) {
4257 const char *RenameFn = 0;
4258 if (Function *F = I.getCalledFunction()) {
4259 if (F->isDeclaration()) {
4260 if (unsigned IID = F->getIntrinsicID()) {
4261 RenameFn = visitIntrinsicCall(I, IID);
4262 if (!RenameFn)
4263 return;
4264 }
4265 }
4266
4267 // Check for well-known libc/libm calls. If the function is internal, it
4268 // can't be a library call.
4269 unsigned NameLen = F->getNameLen();
Rafael Espindolabb46f522009-01-15 20:18:42 +00004270 if (!F->hasLocalLinkage() && NameLen) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004271 const char *NameStr = F->getNameStart();
4272 if (NameStr[0] == 'c' &&
4273 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4274 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4275 if (I.getNumOperands() == 3 && // Basic sanity checks.
4276 I.getOperand(1)->getType()->isFloatingPoint() &&
4277 I.getType() == I.getOperand(1)->getType() &&
4278 I.getType() == I.getOperand(2)->getType()) {
4279 SDValue LHS = getValue(I.getOperand(1));
4280 SDValue RHS = getValue(I.getOperand(2));
4281 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
4282 LHS, RHS));
4283 return;
4284 }
4285 } else if (NameStr[0] == 'f' &&
4286 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4287 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4288 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4289 if (I.getNumOperands() == 2 && // Basic sanity checks.
4290 I.getOperand(1)->getType()->isFloatingPoint() &&
4291 I.getType() == I.getOperand(1)->getType()) {
4292 SDValue Tmp = getValue(I.getOperand(1));
4293 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
4294 return;
4295 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004296 } else if (NameStr[0] == 's' &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004297 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4298 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4299 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4300 if (I.getNumOperands() == 2 && // Basic sanity checks.
4301 I.getOperand(1)->getType()->isFloatingPoint() &&
4302 I.getType() == I.getOperand(1)->getType()) {
4303 SDValue Tmp = getValue(I.getOperand(1));
4304 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
4305 return;
4306 }
4307 } else if (NameStr[0] == 'c' &&
4308 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4309 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4310 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4311 if (I.getNumOperands() == 2 && // Basic sanity checks.
4312 I.getOperand(1)->getType()->isFloatingPoint() &&
4313 I.getType() == I.getOperand(1)->getType()) {
4314 SDValue Tmp = getValue(I.getOperand(1));
4315 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
4316 return;
4317 }
4318 }
4319 }
4320 } else if (isa<InlineAsm>(I.getOperand(0))) {
4321 visitInlineAsm(&I);
4322 return;
4323 }
4324
4325 SDValue Callee;
4326 if (!RenameFn)
4327 Callee = getValue(I.getOperand(0));
4328 else
Bill Wendling056292f2008-09-16 21:48:12 +00004329 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004330
4331 LowerCallTo(&I, Callee, I.isTailCall());
4332}
4333
4334
4335/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004336/// this value and returns the result as a ValueVT value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004337/// Chain/Flag as the input and updates them for the output Chain/Flag.
4338/// If the Flag pointer is NULL, no flag is used.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004339SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004340 SDValue &Chain,
4341 SDValue *Flag) const {
4342 // Assemble the legal parts into the final values.
4343 SmallVector<SDValue, 4> Values(ValueVTs.size());
4344 SmallVector<SDValue, 8> Parts;
4345 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4346 // Copy the legal parts from the registers.
4347 MVT ValueVT = ValueVTs[Value];
4348 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4349 MVT RegisterVT = RegVTs[Value];
4350
4351 Parts.resize(NumRegs);
4352 for (unsigned i = 0; i != NumRegs; ++i) {
4353 SDValue P;
4354 if (Flag == 0)
4355 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
4356 else {
4357 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
4358 *Flag = P.getValue(2);
4359 }
4360 Chain = P.getValue(1);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004361
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004362 // If the source register was virtual and if we know something about it,
4363 // add an assert node.
4364 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4365 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4366 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4367 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4368 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4369 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004370
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004371 unsigned RegSize = RegisterVT.getSizeInBits();
4372 unsigned NumSignBits = LOI.NumSignBits;
4373 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004374
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004375 // FIXME: We capture more information than the dag can represent. For
4376 // now, just use the tightest assertzext/assertsext possible.
4377 bool isSExt = true;
4378 MVT FromVT(MVT::Other);
4379 if (NumSignBits == RegSize)
4380 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4381 else if (NumZeroBits >= RegSize-1)
4382 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4383 else if (NumSignBits > RegSize-8)
4384 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4385 else if (NumZeroBits >= RegSize-9)
4386 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4387 else if (NumSignBits > RegSize-16)
Bill Wendling181b6272008-10-19 20:34:04 +00004388 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004389 else if (NumZeroBits >= RegSize-17)
Bill Wendling181b6272008-10-19 20:34:04 +00004390 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004391 else if (NumSignBits > RegSize-32)
Bill Wendling181b6272008-10-19 20:34:04 +00004392 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004393 else if (NumZeroBits >= RegSize-33)
Bill Wendling181b6272008-10-19 20:34:04 +00004394 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004395
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004396 if (FromVT != MVT::Other) {
4397 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
4398 RegisterVT, P, DAG.getValueType(FromVT));
4399
4400 }
4401 }
4402 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004403
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004404 Parts[i] = P;
4405 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004406
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004407 Values[Value] = getCopyFromParts(DAG, Parts.begin(), NumRegs, RegisterVT,
4408 ValueVT);
4409 Part += NumRegs;
4410 Parts.clear();
4411 }
4412
Duncan Sandsaaffa052008-12-01 11:41:29 +00004413 return DAG.getNode(ISD::MERGE_VALUES,
4414 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4415 &Values[0], ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004416}
4417
4418/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004419/// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004420/// Chain/Flag as the input and updates them for the output Chain/Flag.
4421/// If the Flag pointer is NULL, no flag is used.
4422void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
4423 SDValue &Chain, SDValue *Flag) const {
4424 // Get the list of the values's legal parts.
4425 unsigned NumRegs = Regs.size();
4426 SmallVector<SDValue, 8> Parts(NumRegs);
4427 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4428 MVT ValueVT = ValueVTs[Value];
4429 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4430 MVT RegisterVT = RegVTs[Value];
4431
4432 getCopyToParts(DAG, Val.getValue(Val.getResNo() + Value),
4433 &Parts[Part], NumParts, RegisterVT);
4434 Part += NumParts;
4435 }
4436
4437 // Copy the parts into the registers.
4438 SmallVector<SDValue, 8> Chains(NumRegs);
4439 for (unsigned i = 0; i != NumRegs; ++i) {
4440 SDValue Part;
4441 if (Flag == 0)
4442 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
4443 else {
4444 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
4445 *Flag = Part.getValue(1);
4446 }
4447 Chains[i] = Part.getValue(0);
4448 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004449
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004450 if (NumRegs == 1 || Flag)
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004451 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004452 // flagged to it. That is the CopyToReg nodes and the user are considered
4453 // a single scheduling unit. If we create a TokenFactor and return it as
4454 // chain, then the TokenFactor is both a predecessor (operand) of the
4455 // user as well as a successor (the TF operands are flagged to the user).
4456 // c1, f1 = CopyToReg
4457 // c2, f2 = CopyToReg
4458 // c3 = TokenFactor c1, c2
4459 // ...
4460 // = op c3, ..., f2
4461 Chain = Chains[NumRegs-1];
4462 else
4463 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
4464}
4465
4466/// AddInlineAsmOperands - Add this value to the specified inlineasm node
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004467/// operand list. This adds the code marker and includes the number of
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004468/// values added into it.
4469void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
4470 std::vector<SDValue> &Ops) const {
4471 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4472 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
4473 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4474 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4475 MVT RegisterVT = RegVTs[Value];
Chris Lattner58f15c42008-10-17 16:21:11 +00004476 for (unsigned i = 0; i != NumRegs; ++i) {
4477 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004478 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner58f15c42008-10-17 16:21:11 +00004479 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004480 }
4481}
4482
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004483/// isAllocatableRegister - If the specified register is safe to allocate,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004484/// i.e. it isn't a stack pointer or some other special register, return the
4485/// register class for the register. Otherwise, return null.
4486static const TargetRegisterClass *
4487isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4488 const TargetLowering &TLI,
4489 const TargetRegisterInfo *TRI) {
4490 MVT FoundVT = MVT::Other;
4491 const TargetRegisterClass *FoundRC = 0;
4492 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4493 E = TRI->regclass_end(); RCI != E; ++RCI) {
4494 MVT ThisVT = MVT::Other;
4495
4496 const TargetRegisterClass *RC = *RCI;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004497 // If none of the the value types for this register class are valid, we
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004498 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4499 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4500 I != E; ++I) {
4501 if (TLI.isTypeLegal(*I)) {
4502 // If we have already found this register in a different register class,
4503 // choose the one with the largest VT specified. For example, on
4504 // PowerPC, we favor f64 register classes over f32.
4505 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4506 ThisVT = *I;
4507 break;
4508 }
4509 }
4510 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004511
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004512 if (ThisVT == MVT::Other) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004513
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004514 // NOTE: This isn't ideal. In particular, this might allocate the
4515 // frame pointer in functions that need it (due to them not being taken
4516 // out of allocation, because a variable sized allocation hasn't been seen
4517 // yet). This is a slight code pessimization, but should still work.
4518 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4519 E = RC->allocation_order_end(MF); I != E; ++I)
4520 if (*I == Reg) {
4521 // We found a matching register class. Keep looking at others in case
4522 // we find one with larger registers that this physreg is also in.
4523 FoundRC = RC;
4524 FoundVT = ThisVT;
4525 break;
4526 }
4527 }
4528 return FoundRC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004529}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004530
4531
4532namespace llvm {
4533/// AsmOperandInfo - This contains information for each constraint that we are
4534/// lowering.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004535struct VISIBILITY_HIDDEN SDISelAsmOperandInfo :
Daniel Dunbarc0c3b9a2008-09-10 04:16:29 +00004536 public TargetLowering::AsmOperandInfo {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004537 /// CallOperand - If this is the result output operand or a clobber
4538 /// this is null, otherwise it is the incoming operand to the CallInst.
4539 /// This gets modified as the asm is processed.
4540 SDValue CallOperand;
4541
4542 /// AssignedRegs - If this is a register or register class operand, this
4543 /// contains the set of register corresponding to the operand.
4544 RegsForValue AssignedRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004545
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004546 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4547 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4548 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004549
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004550 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4551 /// busy in OutputRegs/InputRegs.
4552 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004553 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004554 std::set<unsigned> &InputRegs,
4555 const TargetRegisterInfo &TRI) const {
4556 if (isOutReg) {
4557 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4558 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4559 }
4560 if (isInReg) {
4561 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4562 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4563 }
4564 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004565
Chris Lattner81249c92008-10-17 17:05:25 +00004566 /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4567 /// corresponds to. If there is no Value* for this operand, it returns
4568 /// MVT::Other.
4569 MVT getCallOperandValMVT(const TargetLowering &TLI,
4570 const TargetData *TD) const {
4571 if (CallOperandVal == 0) return MVT::Other;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004572
Chris Lattner81249c92008-10-17 17:05:25 +00004573 if (isa<BasicBlock>(CallOperandVal))
4574 return TLI.getPointerTy();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004575
Chris Lattner81249c92008-10-17 17:05:25 +00004576 const llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004577
Chris Lattner81249c92008-10-17 17:05:25 +00004578 // If this is an indirect operand, the operand is a pointer to the
4579 // accessed type.
4580 if (isIndirect)
4581 OpTy = cast<PointerType>(OpTy)->getElementType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004582
Chris Lattner81249c92008-10-17 17:05:25 +00004583 // If OpTy is not a single value, it may be a struct/union that we
4584 // can tile with integers.
4585 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4586 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4587 switch (BitSize) {
4588 default: break;
4589 case 1:
4590 case 8:
4591 case 16:
4592 case 32:
4593 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00004594 case 128:
Chris Lattner81249c92008-10-17 17:05:25 +00004595 OpTy = IntegerType::get(BitSize);
4596 break;
4597 }
4598 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004599
Chris Lattner81249c92008-10-17 17:05:25 +00004600 return TLI.getValueType(OpTy, true);
4601 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004602
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004603private:
4604 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4605 /// specified set.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004606 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004607 const TargetRegisterInfo &TRI) {
4608 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4609 Regs.insert(Reg);
4610 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4611 for (; *Aliases; ++Aliases)
4612 Regs.insert(*Aliases);
4613 }
4614};
4615} // end llvm namespace.
4616
4617
4618/// GetRegistersForValue - Assign registers (virtual or physical) for the
4619/// specified operand. We prefer to assign virtual registers, to allow the
4620/// register allocator handle the assignment process. However, if the asm uses
4621/// features that we can't model on machineinstrs, we have SDISel do the
4622/// allocation. This produces generally horrible, but correct, code.
4623///
4624/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004625/// Input and OutputRegs are the set of already allocated physical registers.
4626///
4627void SelectionDAGLowering::
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004628GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004629 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004630 std::set<unsigned> &InputRegs) {
4631 // Compute whether this value requires an input register, an output register,
4632 // or both.
4633 bool isOutReg = false;
4634 bool isInReg = false;
4635 switch (OpInfo.Type) {
4636 case InlineAsm::isOutput:
4637 isOutReg = true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004638
4639 // If there is an input constraint that matches this, we need to reserve
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004640 // the input register so no other inputs allocate to it.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004641 isInReg = OpInfo.hasMatchingInput();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004642 break;
4643 case InlineAsm::isInput:
4644 isInReg = true;
4645 isOutReg = false;
4646 break;
4647 case InlineAsm::isClobber:
4648 isOutReg = true;
4649 isInReg = true;
4650 break;
4651 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004652
4653
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004654 MachineFunction &MF = DAG.getMachineFunction();
4655 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004656
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004657 // If this is a constraint for a single physreg, or a constraint for a
4658 // register class, find it.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004659 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004660 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4661 OpInfo.ConstraintVT);
4662
4663 unsigned NumRegs = 1;
Chris Lattner01426e12008-10-21 00:45:36 +00004664 if (OpInfo.ConstraintVT != MVT::Other) {
4665 // If this is a FP input in an integer register (or visa versa) insert a bit
4666 // cast of the input value. More generally, handle any case where the input
4667 // value disagrees with the register class we plan to stick this in.
4668 if (OpInfo.Type == InlineAsm::isInput &&
4669 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4670 // Try to convert to the first MVT that the reg class contains. If the
4671 // types are identical size, use a bitcast to convert (e.g. two differing
4672 // vector types).
4673 MVT RegVT = *PhysReg.second->vt_begin();
4674 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
4675 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4676 OpInfo.CallOperand);
4677 OpInfo.ConstraintVT = RegVT;
4678 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4679 // If the input is a FP value and we want it in FP registers, do a
4680 // bitcast to the corresponding integer type. This turns an f64 value
4681 // into i64, which can be passed with two i32 values on a 32-bit
4682 // machine.
4683 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
4684 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4685 OpInfo.CallOperand);
4686 OpInfo.ConstraintVT = RegVT;
4687 }
4688 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004689
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004690 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00004691 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004692
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004693 MVT RegVT;
4694 MVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004695
4696 // If this is a constraint for a specific physical register, like {r17},
4697 // assign it now.
4698 if (PhysReg.first) {
4699 if (OpInfo.ConstraintVT == MVT::Other)
4700 ValueVT = *PhysReg.second->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004701
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004702 // Get the actual register value type. This is important, because the user
4703 // may have asked for (e.g.) the AX register in i32 type. We need to
4704 // remember that AX is actually i16 to get the right extension.
4705 RegVT = *PhysReg.second->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004706
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004707 // This is a explicit reference to a physical register.
4708 Regs.push_back(PhysReg.first);
4709
4710 // If this is an expanded reference, add the rest of the regs to Regs.
4711 if (NumRegs != 1) {
4712 TargetRegisterClass::iterator I = PhysReg.second->begin();
4713 for (; *I != PhysReg.first; ++I)
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004714 assert(I != PhysReg.second->end() && "Didn't find reg!");
4715
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004716 // Already added the first reg.
4717 --NumRegs; ++I;
4718 for (; NumRegs; --NumRegs, ++I) {
4719 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
4720 Regs.push_back(*I);
4721 }
4722 }
4723 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4724 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4725 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4726 return;
4727 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004728
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004729 // Otherwise, if this was a reference to an LLVM register class, create vregs
4730 // for this reference.
4731 std::vector<unsigned> RegClassRegs;
4732 const TargetRegisterClass *RC = PhysReg.second;
4733 if (RC) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004734 // If this is a tied register, our regalloc doesn't know how to maintain
Chris Lattner58f15c42008-10-17 16:21:11 +00004735 // the constraint, so we have to pick a register to pin the input/output to.
4736 // If it isn't a matched constraint, go ahead and create vreg and let the
4737 // regalloc do its thing.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004738 if (!OpInfo.hasMatchingInput()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004739 RegVT = *PhysReg.second->vt_begin();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004740 if (OpInfo.ConstraintVT == MVT::Other)
4741 ValueVT = RegVT;
4742
4743 // Create the appropriate number of virtual registers.
4744 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4745 for (; NumRegs; --NumRegs)
4746 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004747
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004748 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4749 return;
4750 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004751
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004752 // Otherwise, we can't allocate it. Let the code below figure out how to
4753 // maintain these constraints.
4754 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004755
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004756 } else {
4757 // This is a reference to a register class that doesn't directly correspond
4758 // to an LLVM register class. Allocate NumRegs consecutive, available,
4759 // registers from the class.
4760 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4761 OpInfo.ConstraintVT);
4762 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004763
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004764 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4765 unsigned NumAllocated = 0;
4766 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4767 unsigned Reg = RegClassRegs[i];
4768 // See if this register is available.
4769 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4770 (isInReg && InputRegs.count(Reg))) { // Already used.
4771 // Make sure we find consecutive registers.
4772 NumAllocated = 0;
4773 continue;
4774 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004775
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004776 // Check to see if this register is allocatable (i.e. don't give out the
4777 // stack pointer).
4778 if (RC == 0) {
4779 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4780 if (!RC) { // Couldn't allocate this register.
4781 // Reset NumAllocated to make sure we return consecutive registers.
4782 NumAllocated = 0;
4783 continue;
4784 }
4785 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004786
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004787 // Okay, this register is good, we can use it.
4788 ++NumAllocated;
4789
4790 // If we allocated enough consecutive registers, succeed.
4791 if (NumAllocated == NumRegs) {
4792 unsigned RegStart = (i-NumAllocated)+1;
4793 unsigned RegEnd = i+1;
4794 // Mark all of the allocated registers used.
4795 for (unsigned i = RegStart; i != RegEnd; ++i)
4796 Regs.push_back(RegClassRegs[i]);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004797
4798 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004799 OpInfo.ConstraintVT);
4800 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4801 return;
4802 }
4803 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004804
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004805 // Otherwise, we couldn't allocate enough registers for this.
4806}
4807
Evan Chengda43bcf2008-09-24 00:05:32 +00004808/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
4809/// processed uses a memory 'm' constraint.
4810static bool
4811hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
Dan Gohmane9530ec2009-01-15 16:58:17 +00004812 const TargetLowering &TLI) {
Evan Chengda43bcf2008-09-24 00:05:32 +00004813 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
4814 InlineAsm::ConstraintInfo &CI = CInfos[i];
4815 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
4816 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
4817 if (CType == TargetLowering::C_Memory)
4818 return true;
4819 }
4820 }
4821
4822 return false;
4823}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004824
4825/// visitInlineAsm - Handle a call to an InlineAsm object.
4826///
4827void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4828 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4829
4830 /// ConstraintOperands - Information about all of the constraints.
4831 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004832
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004833 SDValue Chain = getRoot();
4834 SDValue Flag;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004835
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004836 std::set<unsigned> OutputRegs, InputRegs;
4837
4838 // Do a prepass over the constraints, canonicalizing them, and building up the
4839 // ConstraintOperands list.
4840 std::vector<InlineAsm::ConstraintInfo>
4841 ConstraintInfos = IA->ParseConstraints();
4842
Evan Chengda43bcf2008-09-24 00:05:32 +00004843 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004844
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004845 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4846 unsigned ResNo = 0; // ResNo - The result number of the next output.
4847 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4848 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4849 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004850
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004851 MVT OpVT = MVT::Other;
4852
4853 // Compute the value type for each operand.
4854 switch (OpInfo.Type) {
4855 case InlineAsm::isOutput:
4856 // Indirect outputs just consume an argument.
4857 if (OpInfo.isIndirect) {
4858 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4859 break;
4860 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004861
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004862 // The return value of the call is this value. As such, there is no
4863 // corresponding argument.
4864 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4865 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4866 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4867 } else {
4868 assert(ResNo == 0 && "Asm only has one result!");
4869 OpVT = TLI.getValueType(CS.getType());
4870 }
4871 ++ResNo;
4872 break;
4873 case InlineAsm::isInput:
4874 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4875 break;
4876 case InlineAsm::isClobber:
4877 // Nothing to do.
4878 break;
4879 }
4880
4881 // If this is an input or an indirect output, process the call argument.
4882 // BasicBlocks are labels, currently appearing only in asm's.
4883 if (OpInfo.CallOperandVal) {
Chris Lattner81249c92008-10-17 17:05:25 +00004884 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004885 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00004886 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004887 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004888 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004889
Chris Lattner81249c92008-10-17 17:05:25 +00004890 OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004891 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004892
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004893 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004894 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004895
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004896 // Second pass over the constraints: compute which constraint option to use
4897 // and assign registers to constraints that want a specific physreg.
4898 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4899 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004900
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004901 // If this is an output operand with a matching input operand, look up the
Evan Cheng09dc9c02008-12-16 18:21:39 +00004902 // matching input. If their types mismatch, e.g. one is an integer, the
4903 // other is floating point, or their sizes are different, flag it as an
4904 // error.
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004905 if (OpInfo.hasMatchingInput()) {
4906 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4907 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Evan Cheng09dc9c02008-12-16 18:21:39 +00004908 if ((OpInfo.ConstraintVT.isInteger() !=
4909 Input.ConstraintVT.isInteger()) ||
4910 (OpInfo.ConstraintVT.getSizeInBits() !=
4911 Input.ConstraintVT.getSizeInBits())) {
4912 cerr << "Unsupported asm: input constraint with a matching output "
4913 << "constraint of incompatible type!\n";
4914 exit(1);
4915 }
4916 Input.ConstraintVT = OpInfo.ConstraintVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004917 }
4918 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004919
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004920 // Compute the constraint code and ConstraintType to use.
Evan Chengda43bcf2008-09-24 00:05:32 +00004921 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004922
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004923 // If this is a memory input, and if the operand is not indirect, do what we
4924 // need to to provide an address for the memory input.
4925 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4926 !OpInfo.isIndirect) {
4927 assert(OpInfo.Type == InlineAsm::isInput &&
4928 "Can only indirectify direct input operands!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004929
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004930 // Memory operands really want the address of the value. If we don't have
4931 // an indirect input, put it in the constpool if we can, otherwise spill
4932 // it to a stack slot.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004933
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004934 // If the operand is a float, integer, or vector constant, spill to a
4935 // constant pool entry to get its address.
4936 Value *OpVal = OpInfo.CallOperandVal;
4937 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4938 isa<ConstantVector>(OpVal)) {
4939 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4940 TLI.getPointerTy());
4941 } else {
4942 // Otherwise, create a stack slot and emit a store to it before the
4943 // asm.
4944 const Type *Ty = OpVal->getType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00004945 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004946 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4947 MachineFunction &MF = DAG.getMachineFunction();
4948 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4949 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4950 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4951 OpInfo.CallOperand = StackSlot;
4952 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004953
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004954 // There is no longer a Value* corresponding to this operand.
4955 OpInfo.CallOperandVal = 0;
4956 // It is now an indirect operand.
4957 OpInfo.isIndirect = true;
4958 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004959
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004960 // If this constraint is for a specific register, allocate it before
4961 // anything else.
4962 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004963 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004964 }
4965 ConstraintInfos.clear();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004966
4967
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004968 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00004969 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004970 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4971 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004972
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004973 // C_Register operands have already been allocated, Other/Memory don't need
4974 // to be.
4975 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004976 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004977 }
4978
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004979 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4980 std::vector<SDValue> AsmNodeOperands;
4981 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
4982 AsmNodeOperands.push_back(
Bill Wendling056292f2008-09-16 21:48:12 +00004983 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004984
4985
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004986 // Loop over all of the inputs, copying the operand values into the
4987 // appropriate registers and processing the output regs.
4988 RegsForValue RetValRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004989
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004990 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4991 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004992
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004993 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4994 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4995
4996 switch (OpInfo.Type) {
4997 case InlineAsm::isOutput: {
4998 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4999 OpInfo.ConstraintType != TargetLowering::C_Register) {
5000 // Memory output, or 'other' output (e.g. 'X' constraint).
5001 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5002
5003 // Add information to the INLINEASM node to know about this output.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005004 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5005 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005006 TLI.getPointerTy()));
5007 AsmNodeOperands.push_back(OpInfo.CallOperand);
5008 break;
5009 }
5010
5011 // Otherwise, this is a register or register class output.
5012
5013 // Copy the output from the appropriate register. Find a register that
5014 // we can use.
5015 if (OpInfo.AssignedRegs.Regs.empty()) {
5016 cerr << "Couldn't allocate output reg for constraint '"
5017 << OpInfo.ConstraintCode << "'!\n";
5018 exit(1);
5019 }
5020
5021 // If this is an indirect operand, store through the pointer after the
5022 // asm.
5023 if (OpInfo.isIndirect) {
5024 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5025 OpInfo.CallOperandVal));
5026 } else {
5027 // This is the result value of the call.
5028 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5029 // Concatenate this output onto the outputs list.
5030 RetValRegs.append(OpInfo.AssignedRegs);
5031 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005032
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005033 // Add information to the INLINEASM node to know that this register is
5034 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00005035 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5036 6 /* EARLYCLOBBER REGDEF */ :
5037 2 /* REGDEF */ ,
5038 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005039 break;
5040 }
5041 case InlineAsm::isInput: {
5042 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005043
Chris Lattner6bdcda32008-10-17 16:47:46 +00005044 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005045 // If this is required to match an output register we have already set,
5046 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00005047 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005048
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005049 // Scan until we find the definition we already emitted of this operand.
5050 // When we find it, create a RegsForValue operand.
5051 unsigned CurOp = 2; // The first operand.
5052 for (; OperandNo; --OperandNo) {
5053 // Advance to the next operand.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005054 unsigned NumOps =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005055 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005056 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
Dale Johannesen913d3df2008-09-12 17:49:03 +00005057 (NumOps & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
Dale Johannesen86b49f82008-09-24 01:07:17 +00005058 (NumOps & 7) == 4 /*MEM*/) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005059 "Skipped past definitions?");
5060 CurOp += (NumOps>>3)+1;
5061 }
5062
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005063 unsigned NumOps =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005064 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005065 if ((NumOps & 7) == 2 /*REGDEF*/
Dale Johannesen913d3df2008-09-12 17:49:03 +00005066 || (NumOps & 7) == 6 /* EARLYCLOBBER REGDEF */) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005067 // Add NumOps>>3 registers to MatchedRegs.
5068 RegsForValue MatchedRegs;
5069 MatchedRegs.TLI = &TLI;
5070 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5071 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
5072 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
5073 unsigned Reg =
5074 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
5075 MatchedRegs.Regs.push_back(Reg);
5076 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005077
5078 // Use the produced MatchedRegs object to
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005079 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Dale Johannesen86b49f82008-09-24 01:07:17 +00005080 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005081 break;
5082 } else {
Dale Johannesen86b49f82008-09-24 01:07:17 +00005083 assert(((NumOps & 7) == 4) && "Unknown matching constraint!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005084 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005085 // Add information to the INLINEASM node to know about this input.
Dale Johannesen91aac102008-09-17 21:13:11 +00005086 AsmNodeOperands.push_back(DAG.getTargetConstant(NumOps,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005087 TLI.getPointerTy()));
5088 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5089 break;
5090 }
5091 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005092
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005093 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005094 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005095 "Don't know how to handle indirect other inputs yet!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005096
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005097 std::vector<SDValue> Ops;
5098 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Chengda43bcf2008-09-24 00:05:32 +00005099 hasMemory, Ops, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005100 if (Ops.empty()) {
5101 cerr << "Invalid operand for inline asm constraint '"
5102 << OpInfo.ConstraintCode << "'!\n";
5103 exit(1);
5104 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005105
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005106 // Add information to the INLINEASM node to know about this input.
5107 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005108 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005109 TLI.getPointerTy()));
5110 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5111 break;
5112 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5113 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5114 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5115 "Memory operands expect pointer values");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005116
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005117 // Add information to the INLINEASM node to know about this input.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005118 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5119 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005120 TLI.getPointerTy()));
5121 AsmNodeOperands.push_back(InOperandVal);
5122 break;
5123 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005124
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005125 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5126 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5127 "Unknown constraint type!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005128 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005129 "Don't know how to handle indirect register inputs yet!");
5130
5131 // Copy the input into the appropriate registers.
Evan Chengaa765b82008-09-25 00:14:04 +00005132 if (OpInfo.AssignedRegs.Regs.empty()) {
5133 cerr << "Couldn't allocate output reg for constraint '"
5134 << OpInfo.ConstraintCode << "'!\n";
5135 exit(1);
5136 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005137
5138 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005139
Dale Johannesen86b49f82008-09-24 01:07:17 +00005140 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/,
5141 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005142 break;
5143 }
5144 case InlineAsm::isClobber: {
5145 // Add the clobbered value to the operand list, so that the register
5146 // allocator is aware that the physreg got clobbered.
5147 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesen91aac102008-09-17 21:13:11 +00005148 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
5149 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005150 break;
5151 }
5152 }
5153 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005154
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005155 // Finish up input operands.
5156 AsmNodeOperands[0] = Chain;
5157 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005158
5159 Chain = DAG.getNode(ISD::INLINEASM,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005160 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
5161 &AsmNodeOperands[0], AsmNodeOperands.size());
5162 Flag = Chain.getValue(1);
5163
5164 // If this asm returns a register value, copy the result from that register
5165 // and set it as the value of the call.
5166 if (!RetValRegs.Regs.empty()) {
5167 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005168
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005169 // FIXME: Why don't we do this for inline asms with MRVs?
5170 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5171 MVT ResultType = TLI.getValueType(CS.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005172
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005173 // If any of the results of the inline asm is a vector, it may have the
5174 // wrong width/num elts. This can happen for register classes that can
5175 // contain multiple different value types. The preg or vreg allocated may
5176 // not have the same VT as was expected. Convert it to the right type
5177 // with bit_convert.
5178 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5179 Val = DAG.getNode(ISD::BIT_CONVERT, ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005180
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005181 } else if (ResultType != Val.getValueType() &&
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005182 ResultType.isInteger() && Val.getValueType().isInteger()) {
5183 // If a result value was tied to an input value, the computed result may
5184 // have a wider width than the expected result. Extract the relevant
5185 // portion.
5186 Val = DAG.getNode(ISD::TRUNCATE, ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005187 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005188
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005189 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00005190 }
Dan Gohman95915732008-10-18 01:03:45 +00005191
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005192 setValue(CS.getInstruction(), Val);
5193 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005194
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005195 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005196
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005197 // Process indirect outputs, first output all of the flagged copies out of
5198 // physregs.
5199 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5200 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5201 Value *Ptr = IndirectStoresToEmit[i].second;
5202 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
5203 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5204 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005205
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005206 // Emit the non-flagged stores from the physregs.
5207 SmallVector<SDValue, 8> OutChains;
5208 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5209 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
5210 getValue(StoresToEmit[i].second),
5211 StoresToEmit[i].second, 0));
5212 if (!OutChains.empty())
5213 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5214 &OutChains[0], OutChains.size());
5215 DAG.setRoot(Chain);
5216}
5217
5218
5219void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5220 SDValue Src = getValue(I.getOperand(0));
5221
5222 MVT IntPtr = TLI.getPointerTy();
5223
5224 if (IntPtr.bitsLT(Src.getValueType()))
5225 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
5226 else if (IntPtr.bitsGT(Src.getValueType()))
5227 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
5228
5229 // Scale the source by the type size.
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005230 uint64_t ElementSize = TD->getTypePaddedSize(I.getType()->getElementType());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005231 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
5232 Src, DAG.getIntPtrConstant(ElementSize));
5233
5234 TargetLowering::ArgListTy Args;
5235 TargetLowering::ArgListEntry Entry;
5236 Entry.Node = Src;
5237 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5238 Args.push_back(Entry);
5239
5240 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005241 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005242 CallingConv::C, PerformTailCallOpt,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005243 DAG.getExternalSymbol("malloc", IntPtr),
Dan Gohman1937e2f2008-09-16 01:42:28 +00005244 Args, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005245 setValue(&I, Result.first); // Pointers always fit in registers
5246 DAG.setRoot(Result.second);
5247}
5248
5249void SelectionDAGLowering::visitFree(FreeInst &I) {
5250 TargetLowering::ArgListTy Args;
5251 TargetLowering::ArgListEntry Entry;
5252 Entry.Node = getValue(I.getOperand(0));
5253 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5254 Args.push_back(Entry);
5255 MVT IntPtr = TLI.getPointerTy();
5256 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005257 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
Dan Gohman1937e2f2008-09-16 01:42:28 +00005258 CallingConv::C, PerformTailCallOpt,
Bill Wendling056292f2008-09-16 21:48:12 +00005259 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005260 DAG.setRoot(Result.second);
5261}
5262
5263void SelectionDAGLowering::visitVAStart(CallInst &I) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005264 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
5265 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005266 DAG.getSrcValue(I.getOperand(1))));
5267}
5268
5269void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
5270 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
5271 getValue(I.getOperand(0)),
5272 DAG.getSrcValue(I.getOperand(0)));
5273 setValue(&I, V);
5274 DAG.setRoot(V.getValue(1));
5275}
5276
5277void SelectionDAGLowering::visitVAEnd(CallInst &I) {
5278 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005279 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005280 DAG.getSrcValue(I.getOperand(1))));
5281}
5282
5283void SelectionDAGLowering::visitVACopy(CallInst &I) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005284 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
5285 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005286 getValue(I.getOperand(2)),
5287 DAG.getSrcValue(I.getOperand(1)),
5288 DAG.getSrcValue(I.getOperand(2))));
5289}
5290
5291/// TargetLowering::LowerArguments - This is the default LowerArguments
5292/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005293/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005294/// integrated into SDISel.
5295void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
5296 SmallVectorImpl<SDValue> &ArgValues) {
5297 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5298 SmallVector<SDValue, 3+16> Ops;
5299 Ops.push_back(DAG.getRoot());
5300 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5301 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5302
5303 // Add one result value for each formal argument.
5304 SmallVector<MVT, 16> RetVals;
5305 unsigned j = 1;
5306 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5307 I != E; ++I, ++j) {
5308 SmallVector<MVT, 4> ValueVTs;
5309 ComputeValueVTs(*this, I->getType(), ValueVTs);
5310 for (unsigned Value = 0, NumValues = ValueVTs.size();
5311 Value != NumValues; ++Value) {
5312 MVT VT = ValueVTs[Value];
5313 const Type *ArgTy = VT.getTypeForMVT();
5314 ISD::ArgFlagsTy Flags;
5315 unsigned OriginalAlignment =
5316 getTargetData()->getABITypeAlignment(ArgTy);
5317
Devang Patel05988662008-09-25 21:00:45 +00005318 if (F.paramHasAttr(j, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005319 Flags.setZExt();
Devang Patel05988662008-09-25 21:00:45 +00005320 if (F.paramHasAttr(j, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005321 Flags.setSExt();
Devang Patel05988662008-09-25 21:00:45 +00005322 if (F.paramHasAttr(j, Attribute::InReg))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005323 Flags.setInReg();
Devang Patel05988662008-09-25 21:00:45 +00005324 if (F.paramHasAttr(j, Attribute::StructRet))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005325 Flags.setSRet();
Devang Patel05988662008-09-25 21:00:45 +00005326 if (F.paramHasAttr(j, Attribute::ByVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005327 Flags.setByVal();
5328 const PointerType *Ty = cast<PointerType>(I->getType());
5329 const Type *ElementTy = Ty->getElementType();
5330 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005331 unsigned FrameSize = getTargetData()->getTypePaddedSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005332 // For ByVal, alignment should be passed from FE. BE will guess if
5333 // this info is not there but there are cases it cannot get right.
5334 if (F.getParamAlignment(j))
5335 FrameAlign = F.getParamAlignment(j);
5336 Flags.setByValAlign(FrameAlign);
5337 Flags.setByValSize(FrameSize);
5338 }
Devang Patel05988662008-09-25 21:00:45 +00005339 if (F.paramHasAttr(j, Attribute::Nest))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005340 Flags.setNest();
5341 Flags.setOrigAlign(OriginalAlignment);
5342
5343 MVT RegisterVT = getRegisterType(VT);
5344 unsigned NumRegs = getNumRegisters(VT);
5345 for (unsigned i = 0; i != NumRegs; ++i) {
5346 RetVals.push_back(RegisterVT);
5347 ISD::ArgFlagsTy MyFlags = Flags;
5348 if (NumRegs > 1 && i == 0)
5349 MyFlags.setSplit();
5350 // if it isn't first piece, alignment must be 1
5351 else if (i > 0)
5352 MyFlags.setOrigAlign(1);
5353 Ops.push_back(DAG.getArgFlags(MyFlags));
5354 }
5355 }
5356 }
5357
5358 RetVals.push_back(MVT::Other);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005359
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005360 // Create the node.
5361 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
5362 DAG.getVTList(&RetVals[0], RetVals.size()),
5363 &Ops[0], Ops.size()).getNode();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005364
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005365 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5366 // allows exposing the loads that may be part of the argument access to the
5367 // first DAGCombiner pass.
5368 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005369
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005370 // The number of results should match up, except that the lowered one may have
5371 // an extra flag result.
5372 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5373 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5374 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5375 && "Lowering produced unexpected number of results!");
5376
5377 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5378 if (Result != TmpRes.getNode() && Result->use_empty()) {
5379 HandleSDNode Dummy(DAG.getRoot());
5380 DAG.RemoveDeadNode(Result);
5381 }
5382
5383 Result = TmpRes.getNode();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005384
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005385 unsigned NumArgRegs = Result->getNumValues() - 1;
5386 DAG.setRoot(SDValue(Result, NumArgRegs));
5387
5388 // Set up the return result vector.
5389 unsigned i = 0;
5390 unsigned Idx = 1;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005391 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005392 ++I, ++Idx) {
5393 SmallVector<MVT, 4> ValueVTs;
5394 ComputeValueVTs(*this, I->getType(), ValueVTs);
5395 for (unsigned Value = 0, NumValues = ValueVTs.size();
5396 Value != NumValues; ++Value) {
5397 MVT VT = ValueVTs[Value];
5398 MVT PartVT = getRegisterType(VT);
5399
5400 unsigned NumParts = getNumRegisters(VT);
5401 SmallVector<SDValue, 4> Parts(NumParts);
5402 for (unsigned j = 0; j != NumParts; ++j)
5403 Parts[j] = SDValue(Result, i++);
5404
5405 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Devang Patel05988662008-09-25 21:00:45 +00005406 if (F.paramHasAttr(Idx, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005407 AssertOp = ISD::AssertSext;
Devang Patel05988662008-09-25 21:00:45 +00005408 else if (F.paramHasAttr(Idx, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005409 AssertOp = ISD::AssertZext;
5410
5411 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
5412 AssertOp));
5413 }
5414 }
5415 assert(i == NumArgRegs && "Argument register count mismatch!");
5416}
5417
5418
5419/// TargetLowering::LowerCallTo - This is the default LowerCallTo
5420/// implementation, which just inserts an ISD::CALL node, which is later custom
5421/// lowered by the target to something concrete. FIXME: When all targets are
5422/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5423std::pair<SDValue, SDValue>
5424TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5425 bool RetSExt, bool RetZExt, bool isVarArg,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005426 bool isInreg,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005427 unsigned CallingConv, bool isTailCall,
5428 SDValue Callee,
5429 ArgListTy &Args, SelectionDAG &DAG) {
Dan Gohman1937e2f2008-09-16 01:42:28 +00005430 assert((!isTailCall || PerformTailCallOpt) &&
5431 "isTailCall set when tail-call optimizations are disabled!");
5432
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005433 SmallVector<SDValue, 32> Ops;
5434 Ops.push_back(Chain); // Op#0 - Chain
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005435 Ops.push_back(Callee);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005436
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005437 // Handle all of the outgoing arguments.
5438 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5439 SmallVector<MVT, 4> ValueVTs;
5440 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5441 for (unsigned Value = 0, NumValues = ValueVTs.size();
5442 Value != NumValues; ++Value) {
5443 MVT VT = ValueVTs[Value];
5444 const Type *ArgTy = VT.getTypeForMVT();
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005445 SDValue Op = SDValue(Args[i].Node.getNode(),
5446 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005447 ISD::ArgFlagsTy Flags;
5448 unsigned OriginalAlignment =
5449 getTargetData()->getABITypeAlignment(ArgTy);
5450
5451 if (Args[i].isZExt)
5452 Flags.setZExt();
5453 if (Args[i].isSExt)
5454 Flags.setSExt();
5455 if (Args[i].isInReg)
5456 Flags.setInReg();
5457 if (Args[i].isSRet)
5458 Flags.setSRet();
5459 if (Args[i].isByVal) {
5460 Flags.setByVal();
5461 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5462 const Type *ElementTy = Ty->getElementType();
5463 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005464 unsigned FrameSize = getTargetData()->getTypePaddedSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005465 // For ByVal, alignment should come from FE. BE will guess if this
5466 // info is not there but there are cases it cannot get right.
5467 if (Args[i].Alignment)
5468 FrameAlign = Args[i].Alignment;
5469 Flags.setByValAlign(FrameAlign);
5470 Flags.setByValSize(FrameSize);
5471 }
5472 if (Args[i].isNest)
5473 Flags.setNest();
5474 Flags.setOrigAlign(OriginalAlignment);
5475
5476 MVT PartVT = getRegisterType(VT);
5477 unsigned NumParts = getNumRegisters(VT);
5478 SmallVector<SDValue, 4> Parts(NumParts);
5479 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5480
5481 if (Args[i].isSExt)
5482 ExtendKind = ISD::SIGN_EXTEND;
5483 else if (Args[i].isZExt)
5484 ExtendKind = ISD::ZERO_EXTEND;
5485
5486 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5487
5488 for (unsigned i = 0; i != NumParts; ++i) {
5489 // if it isn't first piece, alignment must be 1
5490 ISD::ArgFlagsTy MyFlags = Flags;
5491 if (NumParts > 1 && i == 0)
5492 MyFlags.setSplit();
5493 else if (i != 0)
5494 MyFlags.setOrigAlign(1);
5495
5496 Ops.push_back(Parts[i]);
5497 Ops.push_back(DAG.getArgFlags(MyFlags));
5498 }
5499 }
5500 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005501
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005502 // Figure out the result value types. We start by making a list of
5503 // the potentially illegal return value types.
5504 SmallVector<MVT, 4> LoweredRetTys;
5505 SmallVector<MVT, 4> RetTys;
5506 ComputeValueVTs(*this, RetTy, RetTys);
5507
5508 // Then we translate that to a list of legal types.
5509 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5510 MVT VT = RetTys[I];
5511 MVT RegisterVT = getRegisterType(VT);
5512 unsigned NumRegs = getNumRegisters(VT);
5513 for (unsigned i = 0; i != NumRegs; ++i)
5514 LoweredRetTys.push_back(RegisterVT);
5515 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005516
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005517 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005518
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005519 // Create the CALL node.
Dale Johannesen86098bd2008-09-26 19:31:26 +00005520 SDValue Res = DAG.getCall(CallingConv, isVarArg, isTailCall, isInreg,
Dan Gohman095cc292008-09-13 01:54:27 +00005521 DAG.getVTList(&LoweredRetTys[0],
5522 LoweredRetTys.size()),
Dale Johannesen86098bd2008-09-26 19:31:26 +00005523 &Ops[0], Ops.size()
5524 );
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005525 Chain = Res.getValue(LoweredRetTys.size() - 1);
5526
5527 // Gather up the call result into a single value.
Dan Gohmanb5cc34d2008-10-07 00:12:37 +00005528 if (RetTy != Type::VoidTy && !RetTys.empty()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005529 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5530
5531 if (RetSExt)
5532 AssertOp = ISD::AssertSext;
5533 else if (RetZExt)
5534 AssertOp = ISD::AssertZext;
5535
5536 SmallVector<SDValue, 4> ReturnValues;
5537 unsigned RegNo = 0;
5538 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5539 MVT VT = RetTys[I];
5540 MVT RegisterVT = getRegisterType(VT);
5541 unsigned NumRegs = getNumRegisters(VT);
5542 unsigned RegNoEnd = NumRegs + RegNo;
5543 SmallVector<SDValue, 4> Results;
5544 for (; RegNo != RegNoEnd; ++RegNo)
5545 Results.push_back(Res.getValue(RegNo));
5546 SDValue ReturnValue =
5547 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
5548 AssertOp);
5549 ReturnValues.push_back(ReturnValue);
5550 }
Duncan Sandsaaffa052008-12-01 11:41:29 +00005551 Res = DAG.getNode(ISD::MERGE_VALUES,
5552 DAG.getVTList(&RetTys[0], RetTys.size()),
5553 &ReturnValues[0], ReturnValues.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005554 }
5555
5556 return std::make_pair(Res, Chain);
5557}
5558
Duncan Sands9fbc7e22009-01-21 09:00:29 +00005559void TargetLowering::LowerOperationWrapper(SDNode *N,
5560 SmallVectorImpl<SDValue> &Results,
5561 SelectionDAG &DAG) {
5562 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptabb326bb2009-01-21 04:48:39 +00005563 if (Res.getNode())
5564 Results.push_back(Res);
5565}
5566
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005567SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5568 assert(0 && "LowerOperation not implemented for this target!");
5569 abort();
5570 return SDValue();
5571}
5572
5573
5574void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5575 SDValue Op = getValue(V);
5576 assert((Op.getOpcode() != ISD::CopyFromReg ||
5577 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5578 "Copy from a reg to the same reg!");
5579 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5580
5581 RegsForValue RFV(TLI, Reg, V->getType());
5582 SDValue Chain = DAG.getEntryNode();
5583 RFV.getCopyToRegs(Op, DAG, Chain, 0);
5584 PendingExports.push_back(Chain);
5585}
5586
5587#include "llvm/CodeGen/SelectionDAGISel.h"
5588
5589void SelectionDAGISel::
5590LowerArguments(BasicBlock *LLVMBB) {
5591 // If this is the entry block, emit arguments.
5592 Function &F = *LLVMBB->getParent();
5593 SDValue OldRoot = SDL->DAG.getRoot();
5594 SmallVector<SDValue, 16> Args;
5595 TLI.LowerArguments(F, SDL->DAG, Args);
5596
5597 unsigned a = 0;
5598 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5599 AI != E; ++AI) {
5600 SmallVector<MVT, 4> ValueVTs;
5601 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5602 unsigned NumValues = ValueVTs.size();
5603 if (!AI->use_empty()) {
5604 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues));
5605 // If this argument is live outside of the entry block, insert a copy from
5606 // whereever we got it to the vreg that other BB's will reference it as.
5607 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5608 if (VMI != FuncInfo->ValueMap.end()) {
5609 SDL->CopyValueToVirtualRegister(AI, VMI->second);
5610 }
5611 }
5612 a += NumValues;
5613 }
5614
5615 // Finally, if the target has anything special to do, allow it to do so.
5616 // FIXME: this should insert code into the DAG!
5617 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5618}
5619
5620/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5621/// ensure constants are generated when needed. Remember the virtual registers
5622/// that need to be added to the Machine PHI nodes as input. We cannot just
5623/// directly add them, because expansion might result in multiple MBB's for one
5624/// BB. As such, the start of the BB might correspond to a different MBB than
5625/// the end.
5626///
5627void
5628SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5629 TerminatorInst *TI = LLVMBB->getTerminator();
5630
5631 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5632
5633 // Check successor nodes' PHI nodes that expect a constant to be available
5634 // from this block.
5635 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5636 BasicBlock *SuccBB = TI->getSuccessor(succ);
5637 if (!isa<PHINode>(SuccBB->begin())) continue;
5638 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005639
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005640 // If this terminator has multiple identical successors (common for
5641 // switches), only handle each succ once.
5642 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005643
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005644 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5645 PHINode *PN;
5646
5647 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5648 // nodes and Machine PHI nodes, but the incoming operands have not been
5649 // emitted yet.
5650 for (BasicBlock::iterator I = SuccBB->begin();
5651 (PN = dyn_cast<PHINode>(I)); ++I) {
5652 // Ignore dead phi's.
5653 if (PN->use_empty()) continue;
5654
5655 unsigned Reg;
5656 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5657
5658 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5659 unsigned &RegOut = SDL->ConstantsOut[C];
5660 if (RegOut == 0) {
5661 RegOut = FuncInfo->CreateRegForValue(C);
5662 SDL->CopyValueToVirtualRegister(C, RegOut);
5663 }
5664 Reg = RegOut;
5665 } else {
5666 Reg = FuncInfo->ValueMap[PHIOp];
5667 if (Reg == 0) {
5668 assert(isa<AllocaInst>(PHIOp) &&
5669 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5670 "Didn't codegen value into a register!??");
5671 Reg = FuncInfo->CreateRegForValue(PHIOp);
5672 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5673 }
5674 }
5675
5676 // Remember that this register needs to added to the machine PHI node as
5677 // the input for this MBB.
5678 SmallVector<MVT, 4> ValueVTs;
5679 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5680 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5681 MVT VT = ValueVTs[vti];
5682 unsigned NumRegisters = TLI.getNumRegisters(VT);
5683 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5684 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5685 Reg += NumRegisters;
5686 }
5687 }
5688 }
5689 SDL->ConstantsOut.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005690}
5691
Dan Gohman3df24e62008-09-03 23:12:08 +00005692/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5693/// supports legal types, and it emits MachineInstrs directly instead of
5694/// creating SelectionDAG nodes.
5695///
5696bool
5697SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5698 FastISel *F) {
5699 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005700
Dan Gohman3df24e62008-09-03 23:12:08 +00005701 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5702 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5703
5704 // Check successor nodes' PHI nodes that expect a constant to be available
5705 // from this block.
5706 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5707 BasicBlock *SuccBB = TI->getSuccessor(succ);
5708 if (!isa<PHINode>(SuccBB->begin())) continue;
5709 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005710
Dan Gohman3df24e62008-09-03 23:12:08 +00005711 // If this terminator has multiple identical successors (common for
5712 // switches), only handle each succ once.
5713 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005714
Dan Gohman3df24e62008-09-03 23:12:08 +00005715 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5716 PHINode *PN;
5717
5718 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5719 // nodes and Machine PHI nodes, but the incoming operands have not been
5720 // emitted yet.
5721 for (BasicBlock::iterator I = SuccBB->begin();
5722 (PN = dyn_cast<PHINode>(I)); ++I) {
5723 // Ignore dead phi's.
5724 if (PN->use_empty()) continue;
5725
5726 // Only handle legal types. Two interesting things to note here. First,
5727 // by bailing out early, we may leave behind some dead instructions,
5728 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5729 // own moves. Second, this check is necessary becuase FastISel doesn't
5730 // use CreateRegForValue to create registers, so it always creates
5731 // exactly one register for each non-void instruction.
5732 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5733 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
Dan Gohman74321ab2008-09-10 21:01:31 +00005734 // Promote MVT::i1.
5735 if (VT == MVT::i1)
5736 VT = TLI.getTypeToTransformTo(VT);
5737 else {
5738 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5739 return false;
5740 }
Dan Gohman3df24e62008-09-03 23:12:08 +00005741 }
5742
5743 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5744
5745 unsigned Reg = F->getRegForValue(PHIOp);
5746 if (Reg == 0) {
5747 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5748 return false;
5749 }
5750 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
5751 }
5752 }
5753
5754 return true;
5755}