blob: 4bf90508e9f84bae9dd30bbde372482a6e11771f [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"
Dale Johannesen49de9822009-02-05 01:49:45 +000046#include "llvm/Target/TargetIntrinsicInfo.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000047#include "llvm/Target/TargetLowering.h"
48#include "llvm/Target/TargetMachine.h"
49#include "llvm/Target/TargetOptions.h"
50#include "llvm/Support/Compiler.h"
Mikhail Glushenkov2388a582009-01-16 07:02:28 +000051#include "llvm/Support/CommandLine.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000052#include "llvm/Support/Debug.h"
53#include "llvm/Support/MathExtras.h"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +000054#include "llvm/Support/raw_ostream.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000055#include <algorithm>
56using namespace llvm;
57
Dale Johannesen601d3c02008-09-05 01:48:15 +000058/// LimitFloatPrecision - Generate low-precision inline sequences for
59/// some float libcalls (6, 8 or 12 bits).
60static unsigned LimitFloatPrecision;
61
62static cl::opt<unsigned, true>
63LimitFPPrecision("limit-float-precision",
64 cl::desc("Generate low-precision inline sequences "
65 "for some float libcalls"),
66 cl::location(LimitFloatPrecision),
67 cl::init(0));
68
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000069/// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
Dan Gohman2c91d102009-01-06 22:53:52 +000070/// of insertvalue or extractvalue indices that identify a member, return
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000071/// the linearized index of the start of the member.
72///
73static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
74 const unsigned *Indices,
75 const unsigned *IndicesEnd,
76 unsigned CurIndex = 0) {
77 // Base case: We're done.
78 if (Indices && Indices == IndicesEnd)
79 return CurIndex;
80
81 // Given a struct type, recursively traverse the elements.
82 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
83 for (StructType::element_iterator EB = STy->element_begin(),
84 EI = EB,
85 EE = STy->element_end();
86 EI != EE; ++EI) {
87 if (Indices && *Indices == unsigned(EI - EB))
88 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
89 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
90 }
Dan Gohman2c91d102009-01-06 22:53:52 +000091 return CurIndex;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000092 }
93 // Given an array type, recursively traverse the elements.
94 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
95 const Type *EltTy = ATy->getElementType();
96 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
97 if (Indices && *Indices == i)
98 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
99 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
100 }
Dan Gohman2c91d102009-01-06 22:53:52 +0000101 return CurIndex;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000102 }
103 // We haven't found the type we're looking for, so keep searching.
104 return CurIndex + 1;
105}
106
107/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
108/// MVTs that represent all the individual underlying
109/// non-aggregate types that comprise it.
110///
111/// If Offsets is non-null, it points to a vector to be filled in
112/// with the in-memory offsets of each of the individual values.
113///
114static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
115 SmallVectorImpl<MVT> &ValueVTs,
116 SmallVectorImpl<uint64_t> *Offsets = 0,
117 uint64_t StartingOffset = 0) {
118 // Given a struct type, recursively traverse the elements.
119 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
120 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
121 for (StructType::element_iterator EB = STy->element_begin(),
122 EI = EB,
123 EE = STy->element_end();
124 EI != EE; ++EI)
125 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
126 StartingOffset + SL->getElementOffset(EI - EB));
127 return;
128 }
129 // Given an array type, recursively traverse the elements.
130 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
131 const Type *EltTy = ATy->getElementType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000132 uint64_t EltSize = TLI.getTargetData()->getTypePaddedSize(EltTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000133 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
134 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
135 StartingOffset + i * EltSize);
136 return;
137 }
138 // Base case: we can get an MVT for this LLVM IR type.
139 ValueVTs.push_back(TLI.getValueType(Ty));
140 if (Offsets)
141 Offsets->push_back(StartingOffset);
142}
143
Dan Gohman2a7c6712008-09-03 23:18:39 +0000144namespace llvm {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000145 /// RegsForValue - This struct represents the registers (physical or virtual)
146 /// that a particular set of values is assigned, and the type information about
147 /// the value. The most common situation is to represent one value at a time,
148 /// but struct or array values are handled element-wise as multiple values.
149 /// The splitting of aggregates is performed recursively, so that we never
150 /// have aggregate-typed registers. The values at this point do not necessarily
151 /// have legal types, so each value may require one or more registers of some
152 /// legal type.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000153 ///
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000154 struct VISIBILITY_HIDDEN RegsForValue {
155 /// TLI - The TargetLowering object.
156 ///
157 const TargetLowering *TLI;
158
159 /// ValueVTs - The value types of the values, which may not be legal, and
160 /// may need be promoted or synthesized from one or more registers.
161 ///
162 SmallVector<MVT, 4> ValueVTs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000163
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000164 /// RegVTs - The value types of the registers. This is the same size as
165 /// ValueVTs and it records, for each value, what the type of the assigned
166 /// register or registers are. (Individual values are never synthesized
167 /// from more than one type of register.)
168 ///
169 /// With virtual registers, the contents of RegVTs is redundant with TLI's
170 /// getRegisterType member function, however when with physical registers
171 /// it is necessary to have a separate record of the types.
172 ///
173 SmallVector<MVT, 4> RegVTs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000174
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000175 /// Regs - This list holds the registers assigned to the values.
176 /// Each legal or promoted value requires one register, and each
177 /// expanded value requires multiple registers.
178 ///
179 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000180
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000181 RegsForValue() : TLI(0) {}
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000182
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000183 RegsForValue(const TargetLowering &tli,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000184 const SmallVector<unsigned, 4> &regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000185 MVT regvt, MVT valuevt)
186 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
187 RegsForValue(const TargetLowering &tli,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000188 const SmallVector<unsigned, 4> &regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000189 const SmallVector<MVT, 4> &regvts,
190 const SmallVector<MVT, 4> &valuevts)
191 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
192 RegsForValue(const TargetLowering &tli,
193 unsigned Reg, const Type *Ty) : TLI(&tli) {
194 ComputeValueVTs(tli, Ty, ValueVTs);
195
196 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
197 MVT ValueVT = ValueVTs[Value];
198 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
199 MVT RegisterVT = TLI->getRegisterType(ValueVT);
200 for (unsigned i = 0; i != NumRegs; ++i)
201 Regs.push_back(Reg + i);
202 RegVTs.push_back(RegisterVT);
203 Reg += NumRegs;
204 }
205 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000206
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000207 /// append - Add the specified values to this one.
208 void append(const RegsForValue &RHS) {
209 TLI = RHS.TLI;
210 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
211 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
212 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
213 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000214
215
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000216 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000217 /// this value and returns the result as a ValueVTs value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000218 /// Chain/Flag as the input and updates them for the output Chain/Flag.
219 /// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000220 SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000221 SDValue &Chain, SDValue *Flag) const;
222
223 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000224 /// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000225 /// Chain/Flag as the input and updates them for the output Chain/Flag.
226 /// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000227 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000228 SDValue &Chain, SDValue *Flag) const;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000229
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000230 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
Evan Cheng697cbbf2009-03-20 18:03:34 +0000231 /// operand list. This adds the code marker, matching input operand index
232 /// (if applicable), and includes the number of values added into it.
233 void AddInlineAsmOperands(unsigned Code,
234 bool HasMatching, unsigned MatchingIdx,
235 SelectionDAG &DAG, std::vector<SDValue> &Ops) const;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000236 };
237}
238
239/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000240/// PHI nodes or outside of the basic block that defines it, or used by a
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000241/// switch or atomic instruction, which may expand to multiple basic blocks.
242static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
243 if (isa<PHINode>(I)) return true;
244 BasicBlock *BB = I->getParent();
245 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
246 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
247 // FIXME: Remove switchinst special case.
248 isa<SwitchInst>(*UI))
249 return true;
250 return false;
251}
252
253/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
254/// entry block, return true. This includes arguments used by switches, since
255/// the switch may expand into multiple basic blocks.
256static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
257 // With FastISel active, we may be splitting blocks, so force creation
258 // of virtual registers for all non-dead arguments.
Dan Gohman33134c42008-09-25 17:05:24 +0000259 // Don't force virtual registers for byval arguments though, because
260 // fast-isel can't handle those in all cases.
261 if (EnableFastISel && !A->hasByValAttr())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000262 return A->use_empty();
263
264 BasicBlock *Entry = A->getParent()->begin();
265 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
266 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
267 return false; // Use not in entry block.
268 return true;
269}
270
271FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
272 : TLI(tli) {
273}
274
275void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000276 SelectionDAG &DAG,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000277 bool EnableFastISel) {
278 Fn = &fn;
279 MF = &mf;
280 RegInfo = &MF->getRegInfo();
281
282 // Create a vreg for each argument register that is not dead and is used
283 // outside of the entry block for the function.
284 for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
285 AI != E; ++AI)
286 if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
287 InitializeRegForValue(AI);
288
289 // Initialize the mapping of values to registers. This is only set up for
290 // instruction values that are used outside of the block that defines
291 // them.
292 Function::iterator BB = Fn->begin(), EB = Fn->end();
293 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
294 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
295 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
296 const Type *Ty = AI->getAllocatedType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +0000297 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000298 unsigned Align =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000299 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
300 AI->getAlignment());
301
302 TySize *= CUI->getZExtValue(); // Get total allocated size.
303 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
304 StaticAllocaMap[AI] =
305 MF->getFrameInfo()->CreateStackObject(TySize, Align);
306 }
307
308 for (; BB != EB; ++BB)
309 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
310 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
311 if (!isa<AllocaInst>(I) ||
312 !StaticAllocaMap.count(cast<AllocaInst>(I)))
313 InitializeRegForValue(I);
314
315 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
316 // also creates the initial PHI MachineInstrs, though none of the input
317 // operands are populated.
318 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
319 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
320 MBBMap[BB] = MBB;
321 MF->push_back(MBB);
322
323 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
324 // appropriate.
325 PHINode *PN;
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000326 DebugLoc DL;
327 for (BasicBlock::iterator
328 I = BB->begin(), E = BB->end(); I != E; ++I) {
329 if (CallInst *CI = dyn_cast<CallInst>(I)) {
330 if (Function *F = CI->getCalledFunction()) {
331 switch (F->getIntrinsicID()) {
332 default: break;
333 case Intrinsic::dbg_stoppoint: {
334 DwarfWriter *DW = DAG.getDwarfWriter();
335 DbgStopPointInst *SPI = cast<DbgStopPointInst>(I);
336
337 if (DW && DW->ValidDebugInfo(SPI->getContext())) {
338 DICompileUnit CU(cast<GlobalVariable>(SPI->getContext()));
Bill Wendling0582ae92009-03-13 04:39:26 +0000339 std::string Dir, FN;
340 unsigned SrcFile = DW->getOrCreateSourceID(CU.getDirectory(Dir),
341 CU.getFilename(FN));
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000342 unsigned idx = MF->getOrCreateDebugLocID(SrcFile,
Scott Michelfdc40a02009-02-17 22:15:04 +0000343 SPI->getLine(),
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000344 SPI->getColumn());
345 DL = DebugLoc::get(idx);
346 }
347
348 break;
349 }
350 case Intrinsic::dbg_func_start: {
351 DwarfWriter *DW = DAG.getDwarfWriter();
352 if (DW) {
353 DbgFuncStartInst *FSI = cast<DbgFuncStartInst>(I);
354 Value *SP = FSI->getSubprogram();
355
356 if (DW->ValidDebugInfo(SP)) {
357 DISubprogram Subprogram(cast<GlobalVariable>(SP));
358 DICompileUnit CU(Subprogram.getCompileUnit());
Bill Wendling0582ae92009-03-13 04:39:26 +0000359 std::string Dir, FN;
360 unsigned SrcFile = DW->getOrCreateSourceID(CU.getDirectory(Dir),
361 CU.getFilename(FN));
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000362 unsigned Line = Subprogram.getLineNumber();
363 DL = DebugLoc::get(MF->getOrCreateDebugLocID(SrcFile, Line, 0));
364 }
365 }
Scott Michelfdc40a02009-02-17 22:15:04 +0000366
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000367 break;
368 }
369 }
370 }
371 }
372
373 PN = dyn_cast<PHINode>(I);
374 if (!PN || PN->use_empty()) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000375
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000376 unsigned PHIReg = ValueMap[PN];
377 assert(PHIReg && "PHI node does not have an assigned virtual register!");
378
379 SmallVector<MVT, 4> ValueVTs;
380 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
381 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
382 MVT VT = ValueVTs[vti];
383 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohman6448d912008-09-04 15:39:15 +0000384 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000385 for (unsigned i = 0; i != NumRegisters; ++i)
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000386 BuildMI(MBB, DL, TII->get(TargetInstrInfo::PHI), PHIReg + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000387 PHIReg += NumRegisters;
388 }
389 }
390 }
391}
392
393unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
394 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
395}
396
397/// CreateRegForValue - Allocate the appropriate number of virtual registers of
398/// the correctly promoted or expanded types. Assign these registers
399/// consecutive vreg numbers and return the first assigned number.
400///
401/// In the case that the given value has struct or array type, this function
402/// will assign registers for each member or element.
403///
404unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
405 SmallVector<MVT, 4> ValueVTs;
406 ComputeValueVTs(TLI, V->getType(), ValueVTs);
407
408 unsigned FirstReg = 0;
409 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
410 MVT ValueVT = ValueVTs[Value];
411 MVT RegisterVT = TLI.getRegisterType(ValueVT);
412
413 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
414 for (unsigned i = 0; i != NumRegs; ++i) {
415 unsigned R = MakeReg(RegisterVT);
416 if (!FirstReg) FirstReg = R;
417 }
418 }
419 return FirstReg;
420}
421
422/// getCopyFromParts - Create a value that contains the specified legal parts
423/// combined into the value they represent. If the parts combine to a type
424/// larger then ValueVT then AssertOp can be used to specify whether the extra
425/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
426/// (ISD::AssertSext).
Dale Johannesen66978ee2009-01-31 02:22:37 +0000427static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
428 const SDValue *Parts,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000429 unsigned NumParts, MVT PartVT, MVT ValueVT,
430 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000431 assert(NumParts > 0 && "No parts to assemble!");
Dan Gohmane9530ec2009-01-15 16:58:17 +0000432 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000433 SDValue Val = Parts[0];
434
435 if (NumParts > 1) {
436 // Assemble the value from multiple parts.
437 if (!ValueVT.isVector()) {
438 unsigned PartBits = PartVT.getSizeInBits();
439 unsigned ValueBits = ValueVT.getSizeInBits();
440
441 // Assemble the power of 2 part.
442 unsigned RoundParts = NumParts & (NumParts - 1) ?
443 1 << Log2_32(NumParts) : NumParts;
444 unsigned RoundBits = PartBits * RoundParts;
445 MVT RoundVT = RoundBits == ValueBits ?
446 ValueVT : MVT::getIntegerVT(RoundBits);
447 SDValue Lo, Hi;
448
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000449 MVT HalfVT = ValueVT.isInteger() ?
450 MVT::getIntegerVT(RoundBits/2) :
451 MVT::getFloatingPointVT(RoundBits/2);
452
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000453 if (RoundParts > 2) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000454 Lo = getCopyFromParts(DAG, dl, Parts, RoundParts/2, PartVT, HalfVT);
455 Hi = getCopyFromParts(DAG, dl, Parts+RoundParts/2, RoundParts/2,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000456 PartVT, HalfVT);
457 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000458 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
459 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000460 }
461 if (TLI.isBigEndian())
462 std::swap(Lo, Hi);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000463 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000464
465 if (RoundParts < NumParts) {
466 // Assemble the trailing non-power-of-2 part.
467 unsigned OddParts = NumParts - RoundParts;
468 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
Scott Michelfdc40a02009-02-17 22:15:04 +0000469 Hi = getCopyFromParts(DAG, dl,
Dale Johannesen66978ee2009-01-31 02:22:37 +0000470 Parts+RoundParts, OddParts, PartVT, OddVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000471
472 // Combine the round and odd parts.
473 Lo = Val;
474 if (TLI.isBigEndian())
475 std::swap(Lo, Hi);
476 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000477 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
478 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000479 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands92abc622009-01-31 15:50:11 +0000480 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000481 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
482 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000483 }
484 } else {
485 // Handle a multi-element vector.
486 MVT IntermediateVT, RegisterVT;
487 unsigned NumIntermediates;
488 unsigned NumRegs =
489 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
490 RegisterVT);
491 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
492 NumParts = NumRegs; // Silence a compiler warning.
493 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
494 assert(RegisterVT == Parts[0].getValueType() &&
495 "Part type doesn't match part!");
496
497 // Assemble the parts into intermediate operands.
498 SmallVector<SDValue, 8> Ops(NumIntermediates);
499 if (NumIntermediates == NumParts) {
500 // If the register was not expanded, truncate or copy the value,
501 // as appropriate.
502 for (unsigned i = 0; i != NumParts; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000503 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000504 PartVT, IntermediateVT);
505 } else if (NumParts > 0) {
506 // If the intermediate type was expanded, build the intermediate operands
507 // from the parts.
508 assert(NumParts % NumIntermediates == 0 &&
509 "Must expand into a divisible number of parts!");
510 unsigned Factor = NumParts / NumIntermediates;
511 for (unsigned i = 0; i != NumIntermediates; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000512 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000513 PartVT, IntermediateVT);
514 }
515
516 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
517 // operands.
518 Val = DAG.getNode(IntermediateVT.isVector() ?
Dale Johannesen66978ee2009-01-31 02:22:37 +0000519 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000520 ValueVT, &Ops[0], NumIntermediates);
521 }
522 }
523
524 // There is now one part, held in Val. Correct it to match ValueVT.
525 PartVT = Val.getValueType();
526
527 if (PartVT == ValueVT)
528 return Val;
529
530 if (PartVT.isVector()) {
531 assert(ValueVT.isVector() && "Unknown vector conversion!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000532 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000533 }
534
535 if (ValueVT.isVector()) {
536 assert(ValueVT.getVectorElementType() == PartVT &&
537 ValueVT.getVectorNumElements() == 1 &&
538 "Only trivial scalar-to-vector conversions should get here!");
Evan Chenga87008d2009-02-25 22:49:59 +0000539 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000540 }
541
542 if (PartVT.isInteger() &&
543 ValueVT.isInteger()) {
544 if (ValueVT.bitsLT(PartVT)) {
545 // For a truncate, see if we have any information to
546 // indicate whether the truncated bits will always be
547 // zero or sign-extension.
548 if (AssertOp != ISD::DELETED_NODE)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000549 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000550 DAG.getValueType(ValueVT));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000551 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000552 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000553 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000554 }
555 }
556
557 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
558 if (ValueVT.bitsLT(Val.getValueType()))
559 // FP_ROUND's are always exact here.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000560 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000561 DAG.getIntPtrConstant(1));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000562 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000563 }
564
565 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
Dale Johannesen66978ee2009-01-31 02:22:37 +0000566 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000567
568 assert(0 && "Unknown mismatch!");
569 return SDValue();
570}
571
572/// getCopyToParts - Create a series of nodes that contain the specified value
573/// split into legal parts. If the parts contain more bits than Val, then, for
574/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000575static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, SDValue Val,
Chris Lattner01426e12008-10-21 00:45:36 +0000576 SDValue *Parts, unsigned NumParts, MVT PartVT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000577 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohmane9530ec2009-01-15 16:58:17 +0000578 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000579 MVT PtrVT = TLI.getPointerTy();
580 MVT ValueVT = Val.getValueType();
581 unsigned PartBits = PartVT.getSizeInBits();
Dale Johannesen8a36f502009-02-25 22:39:13 +0000582 unsigned OrigNumParts = NumParts;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000583 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
584
585 if (!NumParts)
586 return;
587
588 if (!ValueVT.isVector()) {
589 if (PartVT == ValueVT) {
590 assert(NumParts == 1 && "No-op copy with multiple parts!");
591 Parts[0] = Val;
592 return;
593 }
594
595 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
596 // If the parts cover more bits than the value has, promote the value.
597 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
598 assert(NumParts == 1 && "Do not know what to promote to!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000599 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000600 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
601 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000602 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000603 } else {
604 assert(0 && "Unknown mismatch!");
605 }
606 } else if (PartBits == ValueVT.getSizeInBits()) {
607 // Different types of the same size.
608 assert(NumParts == 1 && PartVT != ValueVT);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000609 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000610 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
611 // If the parts cover less bits than value has, truncate the value.
612 if (PartVT.isInteger() && ValueVT.isInteger()) {
613 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000614 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000615 } else {
616 assert(0 && "Unknown mismatch!");
617 }
618 }
619
620 // The value may have changed - recompute ValueVT.
621 ValueVT = Val.getValueType();
622 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
623 "Failed to tile the value with PartVT!");
624
625 if (NumParts == 1) {
626 assert(PartVT == ValueVT && "Type conversion failed!");
627 Parts[0] = Val;
628 return;
629 }
630
631 // Expand the value into multiple parts.
632 if (NumParts & (NumParts - 1)) {
633 // The number of parts is not a power of 2. Split off and copy the tail.
634 assert(PartVT.isInteger() && ValueVT.isInteger() &&
635 "Do not know what to expand to!");
636 unsigned RoundParts = 1 << Log2_32(NumParts);
637 unsigned RoundBits = RoundParts * PartBits;
638 unsigned OddParts = NumParts - RoundParts;
Dale Johannesen66978ee2009-01-31 02:22:37 +0000639 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000640 DAG.getConstant(RoundBits,
Duncan Sands92abc622009-01-31 15:50:11 +0000641 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000642 getCopyToParts(DAG, dl, OddVal, Parts + RoundParts, OddParts, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000643 if (TLI.isBigEndian())
644 // The odd parts were reversed by getCopyToParts - unreverse them.
645 std::reverse(Parts + RoundParts, Parts + NumParts);
646 NumParts = RoundParts;
647 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000648 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000649 }
650
651 // The number of parts is a power of 2. Repeatedly bisect the value using
652 // EXTRACT_ELEMENT.
Scott Michelfdc40a02009-02-17 22:15:04 +0000653 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000654 MVT::getIntegerVT(ValueVT.getSizeInBits()),
655 Val);
656 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
657 for (unsigned i = 0; i < NumParts; i += StepSize) {
658 unsigned ThisBits = StepSize * PartBits / 2;
659 MVT ThisVT = MVT::getIntegerVT (ThisBits);
660 SDValue &Part0 = Parts[i];
661 SDValue &Part1 = Parts[i+StepSize/2];
662
Scott Michelfdc40a02009-02-17 22:15:04 +0000663 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000664 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000665 DAG.getConstant(1, PtrVT));
Scott Michelfdc40a02009-02-17 22:15:04 +0000666 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000667 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000668 DAG.getConstant(0, PtrVT));
669
670 if (ThisBits == PartBits && ThisVT != PartVT) {
Scott Michelfdc40a02009-02-17 22:15:04 +0000671 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000672 PartVT, Part0);
Scott Michelfdc40a02009-02-17 22:15:04 +0000673 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000674 PartVT, Part1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000675 }
676 }
677 }
678
679 if (TLI.isBigEndian())
Dale Johannesen8a36f502009-02-25 22:39:13 +0000680 std::reverse(Parts, Parts + OrigNumParts);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000681
682 return;
683 }
684
685 // Vector ValueVT.
686 if (NumParts == 1) {
687 if (PartVT != ValueVT) {
688 if (PartVT.isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000689 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000690 } else {
691 assert(ValueVT.getVectorElementType() == PartVT &&
692 ValueVT.getVectorNumElements() == 1 &&
693 "Only trivial vector-to-scalar conversions should get here!");
Scott Michelfdc40a02009-02-17 22:15:04 +0000694 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000695 PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000696 DAG.getConstant(0, PtrVT));
697 }
698 }
699
700 Parts[0] = Val;
701 return;
702 }
703
704 // Handle a multi-element vector.
705 MVT IntermediateVT, RegisterVT;
706 unsigned NumIntermediates;
Dan Gohmane9530ec2009-01-15 16:58:17 +0000707 unsigned NumRegs = TLI
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000708 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
709 RegisterVT);
710 unsigned NumElements = ValueVT.getVectorNumElements();
711
712 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
713 NumParts = NumRegs; // Silence a compiler warning.
714 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
715
716 // Split the vector into intermediate operands.
717 SmallVector<SDValue, 8> Ops(NumIntermediates);
718 for (unsigned i = 0; i != NumIntermediates; ++i)
719 if (IntermediateVT.isVector())
Scott Michelfdc40a02009-02-17 22:15:04 +0000720 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000721 IntermediateVT, Val,
722 DAG.getConstant(i * (NumElements / NumIntermediates),
723 PtrVT));
724 else
Scott Michelfdc40a02009-02-17 22:15:04 +0000725 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000726 IntermediateVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000727 DAG.getConstant(i, PtrVT));
728
729 // Split the intermediate operands into legal parts.
730 if (NumParts == NumIntermediates) {
731 // If the register was not expanded, promote or copy the value,
732 // as appropriate.
733 for (unsigned i = 0; i != NumParts; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000734 getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000735 } else if (NumParts > 0) {
736 // If the intermediate type was expanded, split each the value into
737 // legal parts.
738 assert(NumParts % NumIntermediates == 0 &&
739 "Must expand into a divisible number of parts!");
740 unsigned Factor = NumParts / NumIntermediates;
741 for (unsigned i = 0; i != NumIntermediates; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000742 getCopyToParts(DAG, dl, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000743 }
744}
745
746
747void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
748 AA = &aa;
749 GFI = gfi;
750 TD = DAG.getTarget().getTargetData();
751}
752
753/// clear - Clear out the curret SelectionDAG and the associated
754/// state and prepare this SelectionDAGLowering object to be used
755/// for a new block. This doesn't clear out information about
756/// additional blocks that are needed to complete switch lowering
757/// or PHI node updating; that information is cleared out as it is
758/// consumed.
759void SelectionDAGLowering::clear() {
760 NodeMap.clear();
761 PendingLoads.clear();
762 PendingExports.clear();
763 DAG.clear();
Bill Wendling8fcf1702009-02-06 21:36:23 +0000764 CurDebugLoc = DebugLoc::getUnknownLoc();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000765}
766
767/// getRoot - Return the current virtual root of the Selection DAG,
768/// flushing any PendingLoad items. This must be done before emitting
769/// a store or any other node that may need to be ordered after any
770/// prior load instructions.
771///
772SDValue SelectionDAGLowering::getRoot() {
773 if (PendingLoads.empty())
774 return DAG.getRoot();
775
776 if (PendingLoads.size() == 1) {
777 SDValue Root = PendingLoads[0];
778 DAG.setRoot(Root);
779 PendingLoads.clear();
780 return Root;
781 }
782
783 // Otherwise, we have to make a token factor node.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000784 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000785 &PendingLoads[0], PendingLoads.size());
786 PendingLoads.clear();
787 DAG.setRoot(Root);
788 return Root;
789}
790
791/// getControlRoot - Similar to getRoot, but instead of flushing all the
792/// PendingLoad items, flush all the PendingExports items. It is necessary
793/// to do this before emitting a terminator instruction.
794///
795SDValue SelectionDAGLowering::getControlRoot() {
796 SDValue Root = DAG.getRoot();
797
798 if (PendingExports.empty())
799 return Root;
800
801 // Turn all of the CopyToReg chains into one factored node.
802 if (Root.getOpcode() != ISD::EntryToken) {
803 unsigned i = 0, e = PendingExports.size();
804 for (; i != e; ++i) {
805 assert(PendingExports[i].getNode()->getNumOperands() > 1);
806 if (PendingExports[i].getNode()->getOperand(0) == Root)
807 break; // Don't add the root if we already indirectly depend on it.
808 }
809
810 if (i == e)
811 PendingExports.push_back(Root);
812 }
813
Dale Johannesen66978ee2009-01-31 02:22:37 +0000814 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000815 &PendingExports[0],
816 PendingExports.size());
817 PendingExports.clear();
818 DAG.setRoot(Root);
819 return Root;
820}
821
822void SelectionDAGLowering::visit(Instruction &I) {
823 visit(I.getOpcode(), I);
824}
825
826void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
827 // Note: this doesn't use InstVisitor, because it has to work with
828 // ConstantExpr's in addition to instructions.
829 switch (Opcode) {
830 default: assert(0 && "Unknown instruction type encountered!");
831 abort();
832 // Build the switch statement using the Instruction.def file.
833#define HANDLE_INST(NUM, OPCODE, CLASS) \
834 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
835#include "llvm/Instruction.def"
836 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000837}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000838
839void SelectionDAGLowering::visitAdd(User &I) {
840 if (I.getType()->isFPOrFPVector())
841 visitBinary(I, ISD::FADD);
842 else
843 visitBinary(I, ISD::ADD);
844}
845
846void SelectionDAGLowering::visitMul(User &I) {
847 if (I.getType()->isFPOrFPVector())
848 visitBinary(I, ISD::FMUL);
849 else
850 visitBinary(I, ISD::MUL);
851}
852
853SDValue SelectionDAGLowering::getValue(const Value *V) {
854 SDValue &N = NodeMap[V];
855 if (N.getNode()) return N;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000856
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000857 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
858 MVT VT = TLI.getValueType(V->getType(), true);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000859
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000860 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000861 return N = DAG.getConstant(*CI, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000862
863 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
864 return N = DAG.getGlobalAddress(GV, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000865
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000866 if (isa<ConstantPointerNull>(C))
867 return N = DAG.getConstant(0, TLI.getPointerTy());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000868
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000869 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000870 return N = DAG.getConstantFP(*CFP, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000871
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000872 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
873 !V->getType()->isAggregateType())
Dale Johannesene8d72302009-02-06 23:05:02 +0000874 return N = DAG.getUNDEF(VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000875
876 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
877 visit(CE->getOpcode(), *CE);
878 SDValue N1 = NodeMap[V];
879 assert(N1.getNode() && "visit didn't populate the ValueMap!");
880 return N1;
881 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000882
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000883 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
884 SmallVector<SDValue, 4> Constants;
885 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
886 OI != OE; ++OI) {
887 SDNode *Val = getValue(*OI).getNode();
888 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
889 Constants.push_back(SDValue(Val, i));
890 }
Dale Johannesen4be0bdf2009-02-05 00:20:09 +0000891 return DAG.getMergeValues(&Constants[0], Constants.size(),
892 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000893 }
894
895 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
896 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
897 "Unknown struct or array constant!");
898
899 SmallVector<MVT, 4> ValueVTs;
900 ComputeValueVTs(TLI, C->getType(), ValueVTs);
901 unsigned NumElts = ValueVTs.size();
902 if (NumElts == 0)
903 return SDValue(); // empty struct
904 SmallVector<SDValue, 4> Constants(NumElts);
905 for (unsigned i = 0; i != NumElts; ++i) {
906 MVT EltVT = ValueVTs[i];
907 if (isa<UndefValue>(C))
Dale Johannesene8d72302009-02-06 23:05:02 +0000908 Constants[i] = DAG.getUNDEF(EltVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000909 else if (EltVT.isFloatingPoint())
910 Constants[i] = DAG.getConstantFP(0, EltVT);
911 else
912 Constants[i] = DAG.getConstant(0, EltVT);
913 }
Dale Johannesen4be0bdf2009-02-05 00:20:09 +0000914 return DAG.getMergeValues(&Constants[0], NumElts, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000915 }
916
917 const VectorType *VecTy = cast<VectorType>(V->getType());
918 unsigned NumElements = VecTy->getNumElements();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000919
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000920 // Now that we know the number and type of the elements, get that number of
921 // elements into the Ops array based on what kind of constant it is.
922 SmallVector<SDValue, 16> Ops;
923 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
924 for (unsigned i = 0; i != NumElements; ++i)
925 Ops.push_back(getValue(CP->getOperand(i)));
926 } else {
927 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
928 "Unknown vector constant!");
929 MVT EltVT = TLI.getValueType(VecTy->getElementType());
930
931 SDValue Op;
932 if (isa<UndefValue>(C))
Dale Johannesene8d72302009-02-06 23:05:02 +0000933 Op = DAG.getUNDEF(EltVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000934 else if (EltVT.isFloatingPoint())
935 Op = DAG.getConstantFP(0, EltVT);
936 else
937 Op = DAG.getConstant(0, EltVT);
938 Ops.assign(NumElements, Op);
939 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000940
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000941 // Create a BUILD_VECTOR node.
Evan Chenga87008d2009-02-25 22:49:59 +0000942 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
943 VT, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000944 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000945
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000946 // If this is a static alloca, generate it as the frameindex instead of
947 // computation.
948 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
949 DenseMap<const AllocaInst*, int>::iterator SI =
950 FuncInfo.StaticAllocaMap.find(AI);
951 if (SI != FuncInfo.StaticAllocaMap.end())
952 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
953 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000954
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000955 unsigned InReg = FuncInfo.ValueMap[V];
956 assert(InReg && "Value not in map!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000957
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000958 RegsForValue RFV(TLI, InReg, V->getType());
959 SDValue Chain = DAG.getEntryNode();
Dale Johannesen66978ee2009-01-31 02:22:37 +0000960 return RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000961}
962
963
964void SelectionDAGLowering::visitRet(ReturnInst &I) {
965 if (I.getNumOperands() == 0) {
Scott Michelfdc40a02009-02-17 22:15:04 +0000966 DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000967 MVT::Other, getControlRoot()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000968 return;
969 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000970
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000971 SmallVector<SDValue, 8> NewValues;
972 NewValues.push_back(getControlRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000973 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000974 SmallVector<MVT, 4> ValueVTs;
975 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
Dan Gohman7ea1ca62008-10-21 20:00:42 +0000976 unsigned NumValues = ValueVTs.size();
977 if (NumValues == 0) continue;
978
979 SDValue RetOp = getValue(I.getOperand(i));
980 for (unsigned j = 0, f = NumValues; j != f; ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000981 MVT VT = ValueVTs[j];
982
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000983 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000984
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000985 const Function *F = I.getParent()->getParent();
Devang Patel05988662008-09-25 21:00:45 +0000986 if (F->paramHasAttr(0, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000987 ExtendKind = ISD::SIGN_EXTEND;
Devang Patel05988662008-09-25 21:00:45 +0000988 else if (F->paramHasAttr(0, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000989 ExtendKind = ISD::ZERO_EXTEND;
990
Evan Cheng3927f432009-03-25 20:20:11 +0000991 // FIXME: C calling convention requires the return type to be promoted to
992 // at least 32-bit. But this is not necessary for non-C calling
993 // conventions. The frontend should mark functions whose return values
994 // require promoting with signext or zeroext attributes.
995 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
996 MVT MinVT = TLI.getRegisterType(MVT::i32);
997 if (VT.bitsLT(MinVT))
998 VT = MinVT;
999 }
1000
1001 unsigned NumParts = TLI.getNumRegisters(VT);
1002 MVT PartVT = TLI.getRegisterType(VT);
1003 SmallVector<SDValue, 4> Parts(NumParts);
Dale Johannesen66978ee2009-01-31 02:22:37 +00001004 getCopyToParts(DAG, getCurDebugLoc(),
1005 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001006 &Parts[0], NumParts, PartVT, ExtendKind);
1007
Dale Johannesenc9c6da62008-09-25 20:47:45 +00001008 // 'inreg' on function refers to return value
1009 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Devang Patel05988662008-09-25 21:00:45 +00001010 if (F->paramHasAttr(0, Attribute::InReg))
Dale Johannesenc9c6da62008-09-25 20:47:45 +00001011 Flags.setInReg();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001012 for (unsigned i = 0; i < NumParts; ++i) {
1013 NewValues.push_back(Parts[i]);
Dale Johannesenc9c6da62008-09-25 20:47:45 +00001014 NewValues.push_back(DAG.getArgFlags(Flags));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001015 }
1016 }
1017 }
Dale Johannesen66978ee2009-01-31 02:22:37 +00001018 DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001019 &NewValues[0], NewValues.size()));
1020}
1021
1022/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1023/// the current basic block, add it to ValueMap now so that we'll get a
1024/// CopyTo/FromReg.
1025void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1026 // No need to export constants.
1027 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001028
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001029 // Already exported?
1030 if (FuncInfo.isExportedInst(V)) return;
1031
1032 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1033 CopyValueToVirtualRegister(V, Reg);
1034}
1035
1036bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1037 const BasicBlock *FromBB) {
1038 // The operands of the setcc have to be in this block. We don't know
1039 // how to export them from some other block.
1040 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1041 // Can export from current BB.
1042 if (VI->getParent() == FromBB)
1043 return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001044
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001045 // Is already exported, noop.
1046 return FuncInfo.isExportedInst(V);
1047 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001048
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001049 // If this is an argument, we can export it if the BB is the entry block or
1050 // if it is already exported.
1051 if (isa<Argument>(V)) {
1052 if (FromBB == &FromBB->getParent()->getEntryBlock())
1053 return true;
1054
1055 // Otherwise, can only export this if it is already exported.
1056 return FuncInfo.isExportedInst(V);
1057 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001058
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001059 // Otherwise, constants can always be exported.
1060 return true;
1061}
1062
1063static bool InBlock(const Value *V, const BasicBlock *BB) {
1064 if (const Instruction *I = dyn_cast<Instruction>(V))
1065 return I->getParent() == BB;
1066 return true;
1067}
1068
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001069/// getFCmpCondCode - Return the ISD condition code corresponding to
1070/// the given LLVM IR floating-point condition code. This includes
1071/// consideration of global floating-point math flags.
1072///
1073static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1074 ISD::CondCode FPC, FOC;
1075 switch (Pred) {
1076 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1077 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1078 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1079 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1080 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1081 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1082 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1083 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1084 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1085 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1086 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1087 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1088 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1089 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1090 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1091 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1092 default:
1093 assert(0 && "Invalid FCmp predicate opcode!");
1094 FOC = FPC = ISD::SETFALSE;
1095 break;
1096 }
1097 if (FiniteOnlyFPMath())
1098 return FOC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001099 else
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001100 return FPC;
1101}
1102
1103/// getICmpCondCode - Return the ISD condition code corresponding to
1104/// the given LLVM IR integer condition code.
1105///
1106static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1107 switch (Pred) {
1108 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1109 case ICmpInst::ICMP_NE: return ISD::SETNE;
1110 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1111 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1112 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1113 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1114 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1115 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1116 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1117 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1118 default:
1119 assert(0 && "Invalid ICmp predicate opcode!");
1120 return ISD::SETNE;
1121 }
1122}
1123
Dan Gohmanc2277342008-10-17 21:16:08 +00001124/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1125/// This function emits a branch and is used at the leaves of an OR or an
1126/// AND operator tree.
1127///
1128void
1129SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1130 MachineBasicBlock *TBB,
1131 MachineBasicBlock *FBB,
1132 MachineBasicBlock *CurBB) {
1133 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001134
Dan Gohmanc2277342008-10-17 21:16:08 +00001135 // If the leaf of the tree is a comparison, merge the condition into
1136 // the caseblock.
1137 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1138 // The operands of the cmp have to be in this block. We don't know
1139 // how to export them from some other block. If this is the first block
1140 // of the sequence, no exporting is needed.
1141 if (CurBB == CurMBB ||
1142 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1143 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001144 ISD::CondCode Condition;
1145 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001146 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001147 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001148 Condition = getFCmpCondCode(FC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001149 } else {
1150 Condition = ISD::SETEQ; // silence warning.
1151 assert(0 && "Unknown compare instruction");
1152 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001153
1154 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001155 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1156 SwitchCases.push_back(CB);
1157 return;
1158 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001159 }
1160
1161 // Create a CaseBlock record representing this branch.
1162 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1163 NULL, TBB, FBB, CurBB);
1164 SwitchCases.push_back(CB);
1165}
1166
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001167/// FindMergedConditions - If Cond is an expression like
Dan Gohmanc2277342008-10-17 21:16:08 +00001168void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1169 MachineBasicBlock *TBB,
1170 MachineBasicBlock *FBB,
1171 MachineBasicBlock *CurBB,
1172 unsigned Opc) {
1173 // If this node is not part of the or/and tree, emit it as a branch.
1174 Instruction *BOp = dyn_cast<Instruction>(Cond);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001175 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohmanc2277342008-10-17 21:16:08 +00001176 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1177 BOp->getParent() != CurBB->getBasicBlock() ||
1178 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1179 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1180 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001181 return;
1182 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001183
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001184 // Create TmpBB after CurBB.
1185 MachineFunction::iterator BBI = CurBB;
1186 MachineFunction &MF = DAG.getMachineFunction();
1187 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1188 CurBB->getParent()->insert(++BBI, TmpBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001189
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001190 if (Opc == Instruction::Or) {
1191 // Codegen X | Y as:
1192 // jmp_if_X TBB
1193 // jmp TmpBB
1194 // TmpBB:
1195 // jmp_if_Y TBB
1196 // jmp FBB
1197 //
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001198
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001199 // Emit the LHS condition.
1200 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001201
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001202 // Emit the RHS condition into TmpBB.
1203 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1204 } else {
1205 assert(Opc == Instruction::And && "Unknown merge op!");
1206 // Codegen X & Y as:
1207 // jmp_if_X TmpBB
1208 // jmp FBB
1209 // TmpBB:
1210 // jmp_if_Y TBB
1211 // jmp FBB
1212 //
1213 // This requires creation of TmpBB after CurBB.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001214
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001215 // Emit the LHS condition.
1216 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001217
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001218 // Emit the RHS condition into TmpBB.
1219 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1220 }
1221}
1222
1223/// If the set of cases should be emitted as a series of branches, return true.
1224/// If we should emit this as a bunch of and/or'd together conditions, return
1225/// false.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001226bool
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001227SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1228 if (Cases.size() != 2) return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001229
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001230 // If this is two comparisons of the same values or'd or and'd together, they
1231 // will get folded into a single comparison, so don't emit two blocks.
1232 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1233 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1234 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1235 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1236 return false;
1237 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001238
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001239 return true;
1240}
1241
1242void SelectionDAGLowering::visitBr(BranchInst &I) {
1243 // Update machine-CFG edges.
1244 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1245
1246 // Figure out which block is immediately after the current one.
1247 MachineBasicBlock *NextBlock = 0;
1248 MachineFunction::iterator BBI = CurMBB;
1249 if (++BBI != CurMBB->getParent()->end())
1250 NextBlock = BBI;
1251
1252 if (I.isUnconditional()) {
1253 // Update machine-CFG edges.
1254 CurMBB->addSuccessor(Succ0MBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001255
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001256 // If this is not a fall-through branch, emit the branch.
1257 if (Succ0MBB != NextBlock)
Scott Michelfdc40a02009-02-17 22:15:04 +00001258 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001259 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001260 DAG.getBasicBlock(Succ0MBB)));
1261 return;
1262 }
1263
1264 // If this condition is one of the special cases we handle, do special stuff
1265 // now.
1266 Value *CondVal = I.getCondition();
1267 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1268
1269 // If this is a series of conditions that are or'd or and'd together, emit
1270 // this as a sequence of branches instead of setcc's with and/or operations.
1271 // For example, instead of something like:
1272 // cmp A, B
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001273 // C = seteq
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001274 // cmp D, E
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001275 // F = setle
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001276 // or C, F
1277 // jnz foo
1278 // Emit:
1279 // cmp A, B
1280 // je foo
1281 // cmp D, E
1282 // jle foo
1283 //
1284 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001285 if (BOp->hasOneUse() &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001286 (BOp->getOpcode() == Instruction::And ||
1287 BOp->getOpcode() == Instruction::Or)) {
1288 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1289 // If the compares in later blocks need to use values not currently
1290 // exported from this block, export them now. This block should always
1291 // be the first entry.
1292 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001293
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001294 // Allow some cases to be rejected.
1295 if (ShouldEmitAsBranches(SwitchCases)) {
1296 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1297 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1298 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1299 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001300
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001301 // Emit the branch for this block.
1302 visitSwitchCase(SwitchCases[0]);
1303 SwitchCases.erase(SwitchCases.begin());
1304 return;
1305 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001306
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001307 // Okay, we decided not to do this, remove any inserted MBB's and clear
1308 // SwitchCases.
1309 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1310 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001311
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001312 SwitchCases.clear();
1313 }
1314 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001315
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001316 // Create a CaseBlock record representing this branch.
1317 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1318 NULL, Succ0MBB, Succ1MBB, CurMBB);
1319 // Use visitSwitchCase to actually insert the fast branch sequence for this
1320 // cond branch.
1321 visitSwitchCase(CB);
1322}
1323
1324/// visitSwitchCase - Emits the necessary code to represent a single node in
1325/// the binary search tree resulting from lowering a switch instruction.
1326void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1327 SDValue Cond;
1328 SDValue CondLHS = getValue(CB.CmpLHS);
Dale Johannesenf5d97892009-02-04 01:48:28 +00001329 DebugLoc dl = getCurDebugLoc();
Anton Korobeynikov23218582008-12-23 22:25:27 +00001330
1331 // Build the setcc now.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001332 if (CB.CmpMHS == NULL) {
1333 // Fold "(X == true)" to X and "(X == false)" to !X to
1334 // handle common cases produced by branch lowering.
1335 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1336 Cond = CondLHS;
1337 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1338 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001339 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001340 } else
Dale Johannesenf5d97892009-02-04 01:48:28 +00001341 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001342 } else {
1343 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1344
Anton Korobeynikov23218582008-12-23 22:25:27 +00001345 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1346 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001347
1348 SDValue CmpOp = getValue(CB.CmpMHS);
1349 MVT VT = CmpOp.getValueType();
1350
1351 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
Scott Michelfdc40a02009-02-17 22:15:04 +00001352 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
Dale Johannesenf5d97892009-02-04 01:48:28 +00001353 ISD::SETLE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001354 } else {
Dale Johannesenf5d97892009-02-04 01:48:28 +00001355 SDValue SUB = DAG.getNode(ISD::SUB, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001356 VT, CmpOp, DAG.getConstant(Low, VT));
Dale Johannesenf5d97892009-02-04 01:48:28 +00001357 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001358 DAG.getConstant(High-Low, VT), ISD::SETULE);
1359 }
1360 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001361
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001362 // Update successor info
1363 CurMBB->addSuccessor(CB.TrueBB);
1364 CurMBB->addSuccessor(CB.FalseBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001365
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001366 // Set NextBlock to be the MBB immediately after the current one, if any.
1367 // This is used to avoid emitting unnecessary branches to the next block.
1368 MachineBasicBlock *NextBlock = 0;
1369 MachineFunction::iterator BBI = CurMBB;
1370 if (++BBI != CurMBB->getParent()->end())
1371 NextBlock = BBI;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001372
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001373 // If the lhs block is the next block, invert the condition so that we can
1374 // fall through to the lhs instead of the rhs block.
1375 if (CB.TrueBB == NextBlock) {
1376 std::swap(CB.TrueBB, CB.FalseBB);
1377 SDValue True = DAG.getConstant(1, Cond.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001378 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001379 }
Dale Johannesenf5d97892009-02-04 01:48:28 +00001380 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001381 MVT::Other, getControlRoot(), Cond,
1382 DAG.getBasicBlock(CB.TrueBB));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001383
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001384 // If the branch was constant folded, fix up the CFG.
1385 if (BrCond.getOpcode() == ISD::BR) {
1386 CurMBB->removeSuccessor(CB.FalseBB);
1387 DAG.setRoot(BrCond);
1388 } else {
1389 // Otherwise, go ahead and insert the false branch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001390 if (BrCond == getControlRoot())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001391 CurMBB->removeSuccessor(CB.TrueBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001392
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001393 if (CB.FalseBB == NextBlock)
1394 DAG.setRoot(BrCond);
1395 else
Dale Johannesenf5d97892009-02-04 01:48:28 +00001396 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001397 DAG.getBasicBlock(CB.FalseBB)));
1398 }
1399}
1400
1401/// visitJumpTable - Emit JumpTable node in the current MBB
1402void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1403 // Emit the code for the jump table
1404 assert(JT.Reg != -1U && "Should lower JT Header first!");
1405 MVT PTy = TLI.getPointerTy();
Dale Johannesena04b7572009-02-03 23:04:43 +00001406 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1407 JT.Reg, PTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001408 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Scott Michelfdc40a02009-02-17 22:15:04 +00001409 DAG.setRoot(DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001410 MVT::Other, Index.getValue(1),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001411 Table, Index));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001412}
1413
1414/// visitJumpTableHeader - This function emits necessary code to produce index
1415/// in the JumpTable from switch case.
1416void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1417 JumpTableHeader &JTH) {
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001418 // Subtract the lowest switch case value from the value being switched on and
1419 // conditional branch to default mbb if the result is greater than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001420 // difference between smallest and largest cases.
1421 SDValue SwitchOp = getValue(JTH.SValue);
1422 MVT VT = SwitchOp.getValueType();
Dale Johannesen66978ee2009-01-31 02:22:37 +00001423 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001424 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001425
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001426 // The SDNode we just created, which holds the value being switched on minus
1427 // the the smallest case value, needs to be copied to a virtual register so it
1428 // can be used as an index into the jump table in a subsequent basic block.
1429 // This value may be smaller or larger than the target's pointer type, and
1430 // therefore require extension or truncating.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001431 if (VT.bitsGT(TLI.getPointerTy()))
Scott Michelfdc40a02009-02-17 22:15:04 +00001432 SwitchOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001433 TLI.getPointerTy(), SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001434 else
Scott Michelfdc40a02009-02-17 22:15:04 +00001435 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001436 TLI.getPointerTy(), SUB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001437
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001438 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001439 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1440 JumpTableReg, SwitchOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001441 JT.Reg = JumpTableReg;
1442
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001443 // Emit the range check for the jump table, and branch to the default block
1444 // for the switch statement if the value being switched on exceeds the largest
1445 // case in the switch.
Dale Johannesenf5d97892009-02-04 01:48:28 +00001446 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1447 TLI.getSetCCResultType(SUB.getValueType()), SUB,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001448 DAG.getConstant(JTH.Last-JTH.First,VT),
1449 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001450
1451 // Set NextBlock to be the MBB immediately after the current one, if any.
1452 // This is used to avoid emitting unnecessary branches to the next block.
1453 MachineBasicBlock *NextBlock = 0;
1454 MachineFunction::iterator BBI = CurMBB;
1455 if (++BBI != CurMBB->getParent()->end())
1456 NextBlock = BBI;
1457
Dale Johannesen66978ee2009-01-31 02:22:37 +00001458 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001459 MVT::Other, CopyTo, CMP,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001460 DAG.getBasicBlock(JT.Default));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001461
1462 if (JT.MBB == NextBlock)
1463 DAG.setRoot(BrCond);
1464 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001465 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001466 DAG.getBasicBlock(JT.MBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001467}
1468
1469/// visitBitTestHeader - This function emits necessary code to produce value
1470/// suitable for "bit tests"
1471void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1472 // Subtract the minimum value
1473 SDValue SwitchOp = getValue(B.SValue);
1474 MVT VT = SwitchOp.getValueType();
Dale Johannesen66978ee2009-01-31 02:22:37 +00001475 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001476 DAG.getConstant(B.First, VT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001477
1478 // Check range
Dale Johannesenf5d97892009-02-04 01:48:28 +00001479 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1480 TLI.getSetCCResultType(SUB.getValueType()),
1481 SUB, DAG.getConstant(B.Range, VT),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001482 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001483
1484 SDValue ShiftOp;
Duncan Sands92abc622009-01-31 15:50:11 +00001485 if (VT.bitsGT(TLI.getPointerTy()))
Scott Michelfdc40a02009-02-17 22:15:04 +00001486 ShiftOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00001487 TLI.getPointerTy(), SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001488 else
Scott Michelfdc40a02009-02-17 22:15:04 +00001489 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00001490 TLI.getPointerTy(), SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001491
Duncan Sands92abc622009-01-31 15:50:11 +00001492 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001493 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1494 B.Reg, ShiftOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001495
1496 // Set NextBlock to be the MBB immediately after the current one, if any.
1497 // This is used to avoid emitting unnecessary branches to the next block.
1498 MachineBasicBlock *NextBlock = 0;
1499 MachineFunction::iterator BBI = CurMBB;
1500 if (++BBI != CurMBB->getParent()->end())
1501 NextBlock = BBI;
1502
1503 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1504
1505 CurMBB->addSuccessor(B.Default);
1506 CurMBB->addSuccessor(MBB);
1507
Dale Johannesen66978ee2009-01-31 02:22:37 +00001508 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001509 MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001510 DAG.getBasicBlock(B.Default));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001511
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001512 if (MBB == NextBlock)
1513 DAG.setRoot(BrRange);
1514 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001515 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001516 DAG.getBasicBlock(MBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001517}
1518
1519/// visitBitTestCase - this function produces one "bit test"
1520void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1521 unsigned Reg,
1522 BitTestCase &B) {
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001523 // Make desired shift
Dale Johannesena04b7572009-02-03 23:04:43 +00001524 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
Duncan Sands92abc622009-01-31 15:50:11 +00001525 TLI.getPointerTy());
Scott Michelfdc40a02009-02-17 22:15:04 +00001526 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001527 TLI.getPointerTy(),
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001528 DAG.getConstant(1, TLI.getPointerTy()),
1529 ShiftOp);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001530
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001531 // Emit bit tests and jumps
Scott Michelfdc40a02009-02-17 22:15:04 +00001532 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001533 TLI.getPointerTy(), SwitchVal,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001534 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Dale Johannesenf5d97892009-02-04 01:48:28 +00001535 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1536 TLI.getSetCCResultType(AndOp.getValueType()),
Duncan Sands5480c042009-01-01 15:52:00 +00001537 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001538 ISD::SETNE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001539
1540 CurMBB->addSuccessor(B.TargetBB);
1541 CurMBB->addSuccessor(NextMBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001542
Dale Johannesen66978ee2009-01-31 02:22:37 +00001543 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001544 MVT::Other, getControlRoot(),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001545 AndCmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001546
1547 // Set NextBlock to be the MBB immediately after the current one, if any.
1548 // This is used to avoid emitting unnecessary branches to the next block.
1549 MachineBasicBlock *NextBlock = 0;
1550 MachineFunction::iterator BBI = CurMBB;
1551 if (++BBI != CurMBB->getParent()->end())
1552 NextBlock = BBI;
1553
1554 if (NextMBB == NextBlock)
1555 DAG.setRoot(BrAnd);
1556 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001557 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001558 DAG.getBasicBlock(NextMBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001559}
1560
1561void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1562 // Retrieve successors.
1563 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1564 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1565
Gabor Greifb67e6b32009-01-15 11:10:44 +00001566 const Value *Callee(I.getCalledValue());
1567 if (isa<InlineAsm>(Callee))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001568 visitInlineAsm(&I);
1569 else
Gabor Greifb67e6b32009-01-15 11:10:44 +00001570 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001571
1572 // If the value of the invoke is used outside of its defining block, make it
1573 // available as a virtual register.
1574 if (!I.use_empty()) {
1575 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1576 if (VMI != FuncInfo.ValueMap.end())
1577 CopyValueToVirtualRegister(&I, VMI->second);
1578 }
1579
1580 // Update successor info
1581 CurMBB->addSuccessor(Return);
1582 CurMBB->addSuccessor(LandingPad);
1583
1584 // Drop into normal successor.
Scott Michelfdc40a02009-02-17 22:15:04 +00001585 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001586 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001587 DAG.getBasicBlock(Return)));
1588}
1589
1590void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1591}
1592
1593/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1594/// small case ranges).
1595bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1596 CaseRecVector& WorkList,
1597 Value* SV,
1598 MachineBasicBlock* Default) {
1599 Case& BackCase = *(CR.Range.second-1);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001600
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001601 // Size is the number of Cases represented by this range.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001602 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001603 if (Size > 3)
Anton Korobeynikov23218582008-12-23 22:25:27 +00001604 return false;
1605
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001606 // Get the MachineFunction which holds the current MBB. This is used when
1607 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001608 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001609
1610 // Figure out which block is immediately after the current one.
1611 MachineBasicBlock *NextBlock = 0;
1612 MachineFunction::iterator BBI = CR.CaseBB;
1613
1614 if (++BBI != CurMBB->getParent()->end())
1615 NextBlock = BBI;
1616
1617 // TODO: If any two of the cases has the same destination, and if one value
1618 // is the same as the other, but has one bit unset that the other has set,
1619 // use bit manipulation to do two compares at once. For example:
1620 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Anton Korobeynikov23218582008-12-23 22:25:27 +00001621
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001622 // Rearrange the case blocks so that the last one falls through if possible.
1623 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1624 // The last case block won't fall through into 'NextBlock' if we emit the
1625 // branches in this order. See if rearranging a case value would help.
1626 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1627 if (I->BB == NextBlock) {
1628 std::swap(*I, BackCase);
1629 break;
1630 }
1631 }
1632 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001633
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001634 // Create a CaseBlock record representing a conditional branch to
1635 // the Case's target mbb if the value being switched on SV is equal
1636 // to C.
1637 MachineBasicBlock *CurBlock = CR.CaseBB;
1638 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1639 MachineBasicBlock *FallThrough;
1640 if (I != E-1) {
1641 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1642 CurMF->insert(BBI, FallThrough);
1643 } else {
1644 // If the last case doesn't match, go to the default block.
1645 FallThrough = Default;
1646 }
1647
1648 Value *RHS, *LHS, *MHS;
1649 ISD::CondCode CC;
1650 if (I->High == I->Low) {
1651 // This is just small small case range :) containing exactly 1 case
1652 CC = ISD::SETEQ;
1653 LHS = SV; RHS = I->High; MHS = NULL;
1654 } else {
1655 CC = ISD::SETLE;
1656 LHS = I->Low; MHS = SV; RHS = I->High;
1657 }
1658 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001659
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001660 // If emitting the first comparison, just call visitSwitchCase to emit the
1661 // code into the current block. Otherwise, push the CaseBlock onto the
1662 // vector to be later processed by SDISel, and insert the node's MBB
1663 // before the next MBB.
1664 if (CurBlock == CurMBB)
1665 visitSwitchCase(CB);
1666 else
1667 SwitchCases.push_back(CB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001668
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001669 CurBlock = FallThrough;
1670 }
1671
1672 return true;
1673}
1674
1675static inline bool areJTsAllowed(const TargetLowering &TLI) {
1676 return !DisableJumpTables &&
Dan Gohmanf560ffa2009-01-28 17:46:25 +00001677 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1678 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001679}
Anton Korobeynikov23218582008-12-23 22:25:27 +00001680
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001681static APInt ComputeRange(const APInt &First, const APInt &Last) {
1682 APInt LastExt(Last), FirstExt(First);
1683 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1684 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1685 return (LastExt - FirstExt + 1ULL);
1686}
1687
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001688/// handleJTSwitchCase - Emit jumptable for current switch case range
1689bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1690 CaseRecVector& WorkList,
1691 Value* SV,
1692 MachineBasicBlock* Default) {
1693 Case& FrontCase = *CR.Range.first;
1694 Case& BackCase = *(CR.Range.second-1);
1695
Anton Korobeynikov23218582008-12-23 22:25:27 +00001696 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1697 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001698
Anton Korobeynikov23218582008-12-23 22:25:27 +00001699 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001700 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1701 I!=E; ++I)
1702 TSize += I->size();
1703
1704 if (!areJTsAllowed(TLI) || TSize <= 3)
1705 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001706
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001707 APInt Range = ComputeRange(First, Last);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001708 double Density = (double)TSize / Range.roundToDouble();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001709 if (Density < 0.4)
1710 return false;
1711
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001712 DEBUG(errs() << "Lowering jump table\n"
1713 << "First entry: " << First << ". Last entry: " << Last << '\n'
1714 << "Range: " << Range
1715 << "Size: " << TSize << ". Density: " << Density << "\n\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001716
1717 // Get the MachineFunction which holds the current MBB. This is used when
1718 // inserting any additional MBBs necessary to represent the switch.
1719 MachineFunction *CurMF = CurMBB->getParent();
1720
1721 // Figure out which block is immediately after the current one.
1722 MachineBasicBlock *NextBlock = 0;
1723 MachineFunction::iterator BBI = CR.CaseBB;
1724
1725 if (++BBI != CurMBB->getParent()->end())
1726 NextBlock = BBI;
1727
1728 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1729
1730 // Create a new basic block to hold the code for loading the address
1731 // of the jump table, and jumping to it. Update successor information;
1732 // we will either branch to the default case for the switch, or the jump
1733 // table.
1734 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1735 CurMF->insert(BBI, JumpTableBB);
1736 CR.CaseBB->addSuccessor(Default);
1737 CR.CaseBB->addSuccessor(JumpTableBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001738
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001739 // Build a vector of destination BBs, corresponding to each target
1740 // of the jump table. If the value of the jump table slot corresponds to
1741 // a case statement, push the case's BB onto the vector, otherwise, push
1742 // the default BB.
1743 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001744 APInt TEI = First;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001745 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001746 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1747 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1748
1749 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001750 DestBBs.push_back(I->BB);
1751 if (TEI==High)
1752 ++I;
1753 } else {
1754 DestBBs.push_back(Default);
1755 }
1756 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001757
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001758 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001759 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1760 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001761 E = DestBBs.end(); I != E; ++I) {
1762 if (!SuccsHandled[(*I)->getNumber()]) {
1763 SuccsHandled[(*I)->getNumber()] = true;
1764 JumpTableBB->addSuccessor(*I);
1765 }
1766 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001767
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001768 // Create a jump table index for this jump table, or return an existing
1769 // one.
1770 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001771
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001772 // Set the jump table information so that we can codegen it as a second
1773 // MachineBasicBlock
1774 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1775 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1776 if (CR.CaseBB == CurMBB)
1777 visitJumpTableHeader(JT, JTH);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001778
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001779 JTCases.push_back(JumpTableBlock(JTH, JT));
1780
1781 return true;
1782}
1783
1784/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1785/// 2 subtrees.
1786bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1787 CaseRecVector& WorkList,
1788 Value* SV,
1789 MachineBasicBlock* Default) {
1790 // Get the MachineFunction which holds the current MBB. This is used when
1791 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001792 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001793
1794 // Figure out which block is immediately after the current one.
1795 MachineBasicBlock *NextBlock = 0;
1796 MachineFunction::iterator BBI = CR.CaseBB;
1797
1798 if (++BBI != CurMBB->getParent()->end())
1799 NextBlock = BBI;
1800
1801 Case& FrontCase = *CR.Range.first;
1802 Case& BackCase = *(CR.Range.second-1);
1803 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1804
1805 // Size is the number of Cases represented by this range.
1806 unsigned Size = CR.Range.second - CR.Range.first;
1807
Anton Korobeynikov23218582008-12-23 22:25:27 +00001808 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1809 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001810 double FMetric = 0;
1811 CaseItr Pivot = CR.Range.first + Size/2;
1812
1813 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1814 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001815 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001816 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1817 I!=E; ++I)
1818 TSize += I->size();
1819
Anton Korobeynikov23218582008-12-23 22:25:27 +00001820 size_t LSize = FrontCase.size();
1821 size_t RSize = TSize-LSize;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001822 DEBUG(errs() << "Selecting best pivot: \n"
1823 << "First: " << First << ", Last: " << Last <<'\n'
1824 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001825 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1826 J!=E; ++I, ++J) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001827 const APInt& LEnd = cast<ConstantInt>(I->High)->getValue();
1828 const APInt& RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001829 APInt Range = ComputeRange(LEnd, RBegin);
1830 assert((Range - 2ULL).isNonNegative() &&
1831 "Invalid case distance");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001832 double LDensity = (double)LSize / (LEnd - First + 1ULL).roundToDouble();
1833 double RDensity = (double)RSize / (Last - RBegin + 1ULL).roundToDouble();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001834 double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001835 // Should always split in some non-trivial place
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001836 DEBUG(errs() <<"=>Step\n"
1837 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1838 << "LDensity: " << LDensity
1839 << ", RDensity: " << RDensity << '\n'
1840 << "Metric: " << Metric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001841 if (FMetric < Metric) {
1842 Pivot = J;
1843 FMetric = Metric;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001844 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001845 }
1846
1847 LSize += J->size();
1848 RSize -= J->size();
1849 }
1850 if (areJTsAllowed(TLI)) {
1851 // If our case is dense we *really* should handle it earlier!
1852 assert((FMetric > 0) && "Should handle dense range earlier!");
1853 } else {
1854 Pivot = CR.Range.first + Size/2;
1855 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001856
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001857 CaseRange LHSR(CR.Range.first, Pivot);
1858 CaseRange RHSR(Pivot, CR.Range.second);
1859 Constant *C = Pivot->Low;
1860 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001861
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001862 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001863 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001864 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001865 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001866 // Pivot's Value, then we can branch directly to the LHS's Target,
1867 // rather than creating a leaf node for it.
1868 if ((LHSR.second - LHSR.first) == 1 &&
1869 LHSR.first->High == CR.GE &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001870 cast<ConstantInt>(C)->getValue() ==
1871 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001872 TrueBB = LHSR.first->BB;
1873 } else {
1874 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1875 CurMF->insert(BBI, TrueBB);
1876 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1877 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001878
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001879 // Similar to the optimization above, if the Value being switched on is
1880 // known to be less than the Constant CR.LT, and the current Case Value
1881 // is CR.LT - 1, then we can branch directly to the target block for
1882 // the current Case Value, rather than emitting a RHS leaf node for it.
1883 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001884 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1885 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001886 FalseBB = RHSR.first->BB;
1887 } else {
1888 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1889 CurMF->insert(BBI, FalseBB);
1890 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1891 }
1892
1893 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001894 // the LHS node if the value being switched on SV is less than C.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001895 // Otherwise, branch to LHS.
1896 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1897
1898 if (CR.CaseBB == CurMBB)
1899 visitSwitchCase(CB);
1900 else
1901 SwitchCases.push_back(CB);
1902
1903 return true;
1904}
1905
1906/// handleBitTestsSwitchCase - if current case range has few destination and
1907/// range span less, than machine word bitwidth, encode case range into series
1908/// of masks and emit bit tests with these masks.
1909bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1910 CaseRecVector& WorkList,
1911 Value* SV,
1912 MachineBasicBlock* Default){
1913 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1914
1915 Case& FrontCase = *CR.Range.first;
1916 Case& BackCase = *(CR.Range.second-1);
1917
1918 // Get the MachineFunction which holds the current MBB. This is used when
1919 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001920 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001921
Anton Korobeynikov23218582008-12-23 22:25:27 +00001922 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001923 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1924 I!=E; ++I) {
1925 // Single case counts one, case range - two.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001926 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001927 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001928
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001929 // Count unique destinations
1930 SmallSet<MachineBasicBlock*, 4> Dests;
1931 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1932 Dests.insert(I->BB);
1933 if (Dests.size() > 3)
1934 // Don't bother the code below, if there are too much unique destinations
1935 return false;
1936 }
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001937 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1938 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001939
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001940 // Compute span of values.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001941 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1942 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001943 APInt cmpRange = maxValue - minValue;
1944
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001945 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1946 << "Low bound: " << minValue << '\n'
1947 << "High bound: " << maxValue << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001948
1949 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001950 (!(Dests.size() == 1 && numCmps >= 3) &&
1951 !(Dests.size() == 2 && numCmps >= 5) &&
1952 !(Dests.size() >= 3 && numCmps >= 6)))
1953 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001954
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001955 DEBUG(errs() << "Emitting bit tests\n");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001956 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1957
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001958 // Optimize the case where all the case values fit in a
1959 // word without having to subtract minValue. In this case,
1960 // we can optimize away the subtraction.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001961 if (minValue.isNonNegative() &&
1962 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1963 cmpRange = maxValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001964 } else {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001965 lowBound = minValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001966 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001967
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001968 CaseBitsVector CasesBits;
1969 unsigned i, count = 0;
1970
1971 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1972 MachineBasicBlock* Dest = I->BB;
1973 for (i = 0; i < count; ++i)
1974 if (Dest == CasesBits[i].BB)
1975 break;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001976
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001977 if (i == count) {
1978 assert((count < 3) && "Too much destinations to test!");
1979 CasesBits.push_back(CaseBits(0, Dest, 0));
1980 count++;
1981 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001982
1983 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1984 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1985
1986 uint64_t lo = (lowValue - lowBound).getZExtValue();
1987 uint64_t hi = (highValue - lowBound).getZExtValue();
1988
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001989 for (uint64_t j = lo; j <= hi; j++) {
1990 CasesBits[i].Mask |= 1ULL << j;
1991 CasesBits[i].Bits++;
1992 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001993
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001994 }
1995 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001996
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001997 BitTestInfo BTC;
1998
1999 // Figure out which block is immediately after the current one.
2000 MachineFunction::iterator BBI = CR.CaseBB;
2001 ++BBI;
2002
2003 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2004
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002005 DEBUG(errs() << "Cases:\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002006 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002007 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
2008 << ", Bits: " << CasesBits[i].Bits
2009 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002010
2011 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2012 CurMF->insert(BBI, CaseBB);
2013 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2014 CaseBB,
2015 CasesBits[i].BB));
2016 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002017
2018 BitTestBlock BTB(lowBound, cmpRange, SV,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002019 -1U, (CR.CaseBB == CurMBB),
2020 CR.CaseBB, Default, BTC);
2021
2022 if (CR.CaseBB == CurMBB)
2023 visitBitTestHeader(BTB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002024
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002025 BitTestCases.push_back(BTB);
2026
2027 return true;
2028}
2029
2030
2031/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov23218582008-12-23 22:25:27 +00002032size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002033 const SwitchInst& SI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00002034 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002035
2036 // Start with "simple" cases
Anton Korobeynikov23218582008-12-23 22:25:27 +00002037 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002038 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2039 Cases.push_back(Case(SI.getSuccessorValue(i),
2040 SI.getSuccessorValue(i),
2041 SMBB));
2042 }
2043 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2044
2045 // Merge case into clusters
Anton Korobeynikov23218582008-12-23 22:25:27 +00002046 if (Cases.size() >= 2)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002047 // Must recompute end() each iteration because it may be
2048 // invalidated by erase if we hold on to it
Anton Korobeynikov23218582008-12-23 22:25:27 +00002049 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
2050 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2051 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002052 MachineBasicBlock* nextBB = J->BB;
2053 MachineBasicBlock* currentBB = I->BB;
2054
2055 // If the two neighboring cases go to the same destination, merge them
2056 // into a single case.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002057 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002058 I->High = J->High;
2059 J = Cases.erase(J);
2060 } else {
2061 I = J++;
2062 }
2063 }
2064
2065 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2066 if (I->Low != I->High)
2067 // A range counts double, since it requires two compares.
2068 ++numCmps;
2069 }
2070
2071 return numCmps;
2072}
2073
Anton Korobeynikov23218582008-12-23 22:25:27 +00002074void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002075 // Figure out which block is immediately after the current one.
2076 MachineBasicBlock *NextBlock = 0;
2077 MachineFunction::iterator BBI = CurMBB;
2078
2079 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2080
2081 // If there is only the default destination, branch to it if it is not the
2082 // next basic block. Otherwise, just fall through.
2083 if (SI.getNumOperands() == 2) {
2084 // Update machine-CFG edges.
2085
2086 // If this is not a fall-through branch, emit the branch.
2087 CurMBB->addSuccessor(Default);
2088 if (Default != NextBlock)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002089 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002090 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002091 DAG.getBasicBlock(Default)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002092 return;
2093 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002094
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002095 // If there are any non-default case statements, create a vector of Cases
2096 // representing each one, and sort the vector so that we can efficiently
2097 // create a binary search tree from them.
2098 CaseVector Cases;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002099 size_t numCmps = Clusterify(Cases, SI);
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002100 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2101 << ". Total compares: " << numCmps << '\n');
Devang Patel8a84e442009-01-05 17:31:22 +00002102 numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002103
2104 // Get the Value to be switched on and default basic blocks, which will be
2105 // inserted into CaseBlock records, representing basic blocks in the binary
2106 // search tree.
2107 Value *SV = SI.getOperand(0);
2108
2109 // Push the initial CaseRec onto the worklist
2110 CaseRecVector WorkList;
2111 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2112
2113 while (!WorkList.empty()) {
2114 // Grab a record representing a case range to process off the worklist
2115 CaseRec CR = WorkList.back();
2116 WorkList.pop_back();
2117
2118 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2119 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002120
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002121 // If the range has few cases (two or less) emit a series of specific
2122 // tests.
2123 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2124 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002125
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002126 // If the switch has more than 5 blocks, and at least 40% dense, and the
2127 // target supports indirect branches, then emit a jump table rather than
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002128 // lowering the switch to a binary tree of conditional branches.
2129 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2130 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002131
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002132 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2133 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2134 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2135 }
2136}
2137
2138
2139void SelectionDAGLowering::visitSub(User &I) {
2140 // -0.0 - X --> fneg
2141 const Type *Ty = I.getType();
2142 if (isa<VectorType>(Ty)) {
2143 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2144 const VectorType *DestTy = cast<VectorType>(I.getType());
2145 const Type *ElTy = DestTy->getElementType();
2146 if (ElTy->isFloatingPoint()) {
2147 unsigned VL = DestTy->getNumElements();
2148 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2149 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2150 if (CV == CNZ) {
2151 SDValue Op2 = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002152 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002153 Op2.getValueType(), Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002154 return;
2155 }
2156 }
2157 }
2158 }
2159 if (Ty->isFloatingPoint()) {
2160 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2161 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2162 SDValue Op2 = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002163 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002164 Op2.getValueType(), Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002165 return;
2166 }
2167 }
2168
2169 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2170}
2171
2172void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2173 SDValue Op1 = getValue(I.getOperand(0));
2174 SDValue Op2 = getValue(I.getOperand(1));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002175
Scott Michelfdc40a02009-02-17 22:15:04 +00002176 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002177 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002178}
2179
2180void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2181 SDValue Op1 = getValue(I.getOperand(0));
2182 SDValue Op2 = getValue(I.getOperand(1));
2183 if (!isa<VectorType>(I.getType())) {
Duncan Sands92abc622009-01-31 15:50:11 +00002184 if (TLI.getPointerTy().bitsLT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002185 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002186 TLI.getPointerTy(), Op2);
2187 else if (TLI.getPointerTy().bitsGT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002188 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002189 TLI.getPointerTy(), Op2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002190 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002191
Scott Michelfdc40a02009-02-17 22:15:04 +00002192 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002193 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002194}
2195
2196void SelectionDAGLowering::visitICmp(User &I) {
2197 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2198 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2199 predicate = IC->getPredicate();
2200 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2201 predicate = ICmpInst::Predicate(IC->getPredicate());
2202 SDValue Op1 = getValue(I.getOperand(0));
2203 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002204 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dale Johannesenf5d97892009-02-04 01:48:28 +00002205 setValue(&I, DAG.getSetCC(getCurDebugLoc(),MVT::i1, Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002206}
2207
2208void SelectionDAGLowering::visitFCmp(User &I) {
2209 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2210 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2211 predicate = FC->getPredicate();
2212 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2213 predicate = FCmpInst::Predicate(FC->getPredicate());
2214 SDValue Op1 = getValue(I.getOperand(0));
2215 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002216 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dale Johannesenf5d97892009-02-04 01:48:28 +00002217 setValue(&I, DAG.getSetCC(getCurDebugLoc(), MVT::i1, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002218}
2219
2220void SelectionDAGLowering::visitVICmp(User &I) {
2221 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2222 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2223 predicate = IC->getPredicate();
2224 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2225 predicate = ICmpInst::Predicate(IC->getPredicate());
2226 SDValue Op1 = getValue(I.getOperand(0));
2227 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002228 ISD::CondCode Opcode = getICmpCondCode(predicate);
Scott Michelfdc40a02009-02-17 22:15:04 +00002229 setValue(&I, DAG.getVSetCC(getCurDebugLoc(), Op1.getValueType(),
Dale Johannesenf5d97892009-02-04 01:48:28 +00002230 Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002231}
2232
2233void SelectionDAGLowering::visitVFCmp(User &I) {
2234 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2235 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2236 predicate = FC->getPredicate();
2237 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2238 predicate = FCmpInst::Predicate(FC->getPredicate());
2239 SDValue Op1 = getValue(I.getOperand(0));
2240 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002241 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002242 MVT DestVT = TLI.getValueType(I.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002243
Dale Johannesenf5d97892009-02-04 01:48:28 +00002244 setValue(&I, DAG.getVSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002245}
2246
2247void SelectionDAGLowering::visitSelect(User &I) {
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002248 SmallVector<MVT, 4> ValueVTs;
2249 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2250 unsigned NumValues = ValueVTs.size();
2251 if (NumValues != 0) {
2252 SmallVector<SDValue, 4> Values(NumValues);
2253 SDValue Cond = getValue(I.getOperand(0));
2254 SDValue TrueVal = getValue(I.getOperand(1));
2255 SDValue FalseVal = getValue(I.getOperand(2));
2256
2257 for (unsigned i = 0; i != NumValues; ++i)
Scott Michelfdc40a02009-02-17 22:15:04 +00002258 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002259 TrueVal.getValueType(), Cond,
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002260 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2261 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2262
Scott Michelfdc40a02009-02-17 22:15:04 +00002263 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002264 DAG.getVTList(&ValueVTs[0], NumValues),
2265 &Values[0], NumValues));
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002266 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002267}
2268
2269
2270void SelectionDAGLowering::visitTrunc(User &I) {
2271 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2272 SDValue N = getValue(I.getOperand(0));
2273 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002274 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002275}
2276
2277void SelectionDAGLowering::visitZExt(User &I) {
2278 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2279 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2280 SDValue N = getValue(I.getOperand(0));
2281 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002282 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002283}
2284
2285void SelectionDAGLowering::visitSExt(User &I) {
2286 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2287 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2288 SDValue N = getValue(I.getOperand(0));
2289 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002290 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002291}
2292
2293void SelectionDAGLowering::visitFPTrunc(User &I) {
2294 // FPTrunc is never a no-op cast, no need to check
2295 SDValue N = getValue(I.getOperand(0));
2296 MVT DestVT = TLI.getValueType(I.getType());
Scott Michelfdc40a02009-02-17 22:15:04 +00002297 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002298 DestVT, N, DAG.getIntPtrConstant(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002299}
2300
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002301void SelectionDAGLowering::visitFPExt(User &I){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002302 // FPTrunc is never a no-op cast, no need to check
2303 SDValue N = getValue(I.getOperand(0));
2304 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002305 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002306}
2307
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002308void SelectionDAGLowering::visitFPToUI(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002309 // FPToUI is never a no-op cast, no need to check
2310 SDValue N = getValue(I.getOperand(0));
2311 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002312 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002313}
2314
2315void SelectionDAGLowering::visitFPToSI(User &I) {
2316 // FPToSI is never a no-op cast, no need to check
2317 SDValue N = getValue(I.getOperand(0));
2318 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002319 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002320}
2321
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002322void SelectionDAGLowering::visitUIToFP(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002323 // UIToFP is never a no-op cast, no need to check
2324 SDValue N = getValue(I.getOperand(0));
2325 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002326 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002327}
2328
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002329void SelectionDAGLowering::visitSIToFP(User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002330 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002331 SDValue N = getValue(I.getOperand(0));
2332 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002333 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002334}
2335
2336void SelectionDAGLowering::visitPtrToInt(User &I) {
2337 // What to do depends on the size of the integer and the size of the pointer.
2338 // We can either truncate, zero extend, or no-op, accordingly.
2339 SDValue N = getValue(I.getOperand(0));
2340 MVT SrcVT = N.getValueType();
2341 MVT DestVT = TLI.getValueType(I.getType());
2342 SDValue Result;
2343 if (DestVT.bitsLT(SrcVT))
Dale Johannesen66978ee2009-01-31 02:22:37 +00002344 Result = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002345 else
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002346 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
Dale Johannesen66978ee2009-01-31 02:22:37 +00002347 Result = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002348 setValue(&I, Result);
2349}
2350
2351void SelectionDAGLowering::visitIntToPtr(User &I) {
2352 // What to do depends on the size of the integer and the size of the pointer.
2353 // We can either truncate, zero extend, or no-op, accordingly.
2354 SDValue N = getValue(I.getOperand(0));
2355 MVT SrcVT = N.getValueType();
2356 MVT DestVT = TLI.getValueType(I.getType());
2357 if (DestVT.bitsLT(SrcVT))
Dale Johannesen66978ee2009-01-31 02:22:37 +00002358 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002359 else
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002360 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
Scott Michelfdc40a02009-02-17 22:15:04 +00002361 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002362 DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002363}
2364
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002365void SelectionDAGLowering::visitBitCast(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002366 SDValue N = getValue(I.getOperand(0));
2367 MVT DestVT = TLI.getValueType(I.getType());
2368
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002369 // BitCast assures us that source and destination are the same size so this
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002370 // is either a BIT_CONVERT or a no-op.
2371 if (DestVT != N.getValueType())
Scott Michelfdc40a02009-02-17 22:15:04 +00002372 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002373 DestVT, N)); // convert types
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002374 else
2375 setValue(&I, N); // noop cast.
2376}
2377
2378void SelectionDAGLowering::visitInsertElement(User &I) {
2379 SDValue InVec = getValue(I.getOperand(0));
2380 SDValue InVal = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002381 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002382 TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002383 getValue(I.getOperand(2)));
2384
Scott Michelfdc40a02009-02-17 22:15:04 +00002385 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002386 TLI.getValueType(I.getType()),
2387 InVec, InVal, InIdx));
2388}
2389
2390void SelectionDAGLowering::visitExtractElement(User &I) {
2391 SDValue InVec = getValue(I.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00002392 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002393 TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002394 getValue(I.getOperand(1)));
Dale Johannesen66978ee2009-01-31 02:22:37 +00002395 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002396 TLI.getValueType(I.getType()), InVec, InIdx));
2397}
2398
Mon P Wangaeb06d22008-11-10 04:46:22 +00002399
2400// Utility for visitShuffleVector - Returns true if the mask is mask starting
2401// from SIndx and increasing to the element length (undefs are allowed).
2402static bool SequentialMask(SDValue Mask, unsigned SIndx) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002403 unsigned MaskNumElts = Mask.getNumOperands();
2404 for (unsigned i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002405 if (Mask.getOperand(i).getOpcode() != ISD::UNDEF) {
2406 unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2407 if (Idx != i + SIndx)
2408 return false;
2409 }
2410 }
2411 return true;
2412}
2413
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002414void SelectionDAGLowering::visitShuffleVector(User &I) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002415 SDValue Src1 = getValue(I.getOperand(0));
2416 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002417 SDValue Mask = getValue(I.getOperand(2));
2418
Mon P Wangaeb06d22008-11-10 04:46:22 +00002419 MVT VT = TLI.getValueType(I.getType());
Mon P Wang230e4fa2008-11-21 04:25:21 +00002420 MVT SrcVT = Src1.getValueType();
Mon P Wangc7849c22008-11-16 05:06:27 +00002421 int MaskNumElts = Mask.getNumOperands();
2422 int SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002423
Mon P Wangc7849c22008-11-16 05:06:27 +00002424 if (SrcNumElts == MaskNumElts) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002425 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002426 VT, Src1, Src2, Mask));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002427 return;
2428 }
2429
2430 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002431 MVT MaskEltVT = Mask.getValueType().getVectorElementType();
2432
2433 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2434 // Mask is longer than the source vectors and is a multiple of the source
2435 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang230e4fa2008-11-21 04:25:21 +00002436 // lengths match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002437 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2438 // The shuffle is concatenating two vectors together.
Scott Michelfdc40a02009-02-17 22:15:04 +00002439 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002440 VT, Src1, Src2));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002441 return;
2442 }
2443
Mon P Wangc7849c22008-11-16 05:06:27 +00002444 // Pad both vectors with undefs to make them the same length as the mask.
2445 unsigned NumConcat = MaskNumElts / SrcNumElts;
Dale Johannesene8d72302009-02-06 23:05:02 +00002446 SDValue UndefVal = DAG.getUNDEF(SrcVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002447
Mon P Wang230e4fa2008-11-21 04:25:21 +00002448 SDValue* MOps1 = new SDValue[NumConcat];
2449 SDValue* MOps2 = new SDValue[NumConcat];
2450 MOps1[0] = Src1;
2451 MOps2[0] = Src2;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002452 for (unsigned i = 1; i != NumConcat; ++i) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002453 MOps1[i] = UndefVal;
2454 MOps2[i] = UndefVal;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002455 }
Scott Michelfdc40a02009-02-17 22:15:04 +00002456 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002457 VT, MOps1, NumConcat);
Scott Michelfdc40a02009-02-17 22:15:04 +00002458 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002459 VT, MOps2, NumConcat);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002460
2461 delete [] MOps1;
2462 delete [] MOps2;
2463
Mon P Wangaeb06d22008-11-10 04:46:22 +00002464 // Readjust mask for new input vector length.
2465 SmallVector<SDValue, 8> MappedOps;
Mon P Wangc7849c22008-11-16 05:06:27 +00002466 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002467 if (Mask.getOperand(i).getOpcode() == ISD::UNDEF) {
2468 MappedOps.push_back(Mask.getOperand(i));
2469 } else {
Mon P Wangc7849c22008-11-16 05:06:27 +00002470 int Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2471 if (Idx < SrcNumElts)
2472 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2473 else
2474 MappedOps.push_back(DAG.getConstant(Idx + MaskNumElts - SrcNumElts,
2475 MaskEltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002476 }
2477 }
Evan Chenga87008d2009-02-25 22:49:59 +00002478 Mask = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2479 Mask.getValueType(),
2480 &MappedOps[0], MappedOps.size());
Mon P Wangaeb06d22008-11-10 04:46:22 +00002481
Scott Michelfdc40a02009-02-17 22:15:04 +00002482 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002483 VT, Src1, Src2, Mask));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002484 return;
2485 }
2486
Mon P Wangc7849c22008-11-16 05:06:27 +00002487 if (SrcNumElts > MaskNumElts) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002488 // Resulting vector is shorter than the incoming vector.
Mon P Wangc7849c22008-11-16 05:06:27 +00002489 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,0)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002490 // Shuffle extracts 1st vector.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002491 setValue(&I, Src1);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002492 return;
2493 }
2494
Mon P Wangc7849c22008-11-16 05:06:27 +00002495 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,MaskNumElts)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002496 // Shuffle extracts 2nd vector.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002497 setValue(&I, Src2);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002498 return;
2499 }
2500
Mon P Wangc7849c22008-11-16 05:06:27 +00002501 // Analyze the access pattern of the vector to see if we can extract
2502 // two subvectors and do the shuffle. The analysis is done by calculating
2503 // the range of elements the mask access on both vectors.
2504 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2505 int MaxRange[2] = {-1, -1};
2506
2507 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002508 SDValue Arg = Mask.getOperand(i);
2509 if (Arg.getOpcode() != ISD::UNDEF) {
2510 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Mon P Wangc7849c22008-11-16 05:06:27 +00002511 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2512 int Input = 0;
2513 if (Idx >= SrcNumElts) {
2514 Input = 1;
2515 Idx -= SrcNumElts;
2516 }
2517 if (Idx > MaxRange[Input])
2518 MaxRange[Input] = Idx;
2519 if (Idx < MinRange[Input])
2520 MinRange[Input] = Idx;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002521 }
2522 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002523
Mon P Wangc7849c22008-11-16 05:06:27 +00002524 // Check if the access is smaller than the vector size and can we find
2525 // a reasonable extract index.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002526 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
Mon P Wangc7849c22008-11-16 05:06:27 +00002527 int StartIdx[2]; // StartIdx to extract from
2528 for (int Input=0; Input < 2; ++Input) {
2529 if (MinRange[Input] == SrcNumElts+1 && MaxRange[Input] == -1) {
2530 RangeUse[Input] = 0; // Unused
2531 StartIdx[Input] = 0;
2532 } else if (MaxRange[Input] - MinRange[Input] < MaskNumElts) {
2533 // Fits within range but we should see if we can find a good
Mon P Wang230e4fa2008-11-21 04:25:21 +00002534 // start index that is a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002535 if (MaxRange[Input] < MaskNumElts) {
2536 RangeUse[Input] = 1; // Extract from beginning of the vector
2537 StartIdx[Input] = 0;
2538 } else {
2539 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
Mon P Wang6cce3da2008-11-23 04:35:05 +00002540 if (MaxRange[Input] - StartIdx[Input] < MaskNumElts &&
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002541 StartIdx[Input] + MaskNumElts < SrcNumElts)
Mon P Wangc7849c22008-11-16 05:06:27 +00002542 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002543 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002544 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002545 }
2546
2547 if (RangeUse[0] == 0 && RangeUse[0] == 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002548 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
Mon P Wangc7849c22008-11-16 05:06:27 +00002549 return;
2550 }
2551 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2552 // Extract appropriate subvector and generate a vector shuffle
2553 for (int Input=0; Input < 2; ++Input) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002554 SDValue& Src = Input == 0 ? Src1 : Src2;
Mon P Wangc7849c22008-11-16 05:06:27 +00002555 if (RangeUse[Input] == 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002556 Src = DAG.getUNDEF(VT);
Mon P Wangc7849c22008-11-16 05:06:27 +00002557 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002558 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002559 Src, DAG.getIntPtrConstant(StartIdx[Input]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002560 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002561 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002562 // Calculate new mask.
2563 SmallVector<SDValue, 8> MappedOps;
2564 for (int i = 0; i != MaskNumElts; ++i) {
2565 SDValue Arg = Mask.getOperand(i);
2566 if (Arg.getOpcode() == ISD::UNDEF) {
2567 MappedOps.push_back(Arg);
2568 } else {
2569 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2570 if (Idx < SrcNumElts)
2571 MappedOps.push_back(DAG.getConstant(Idx - StartIdx[0], MaskEltVT));
2572 else {
2573 Idx = Idx - SrcNumElts - StartIdx[1] + MaskNumElts;
2574 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002575 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002576 }
2577 }
Evan Chenga87008d2009-02-25 22:49:59 +00002578 Mask = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2579 Mask.getValueType(),
2580 &MappedOps[0], MappedOps.size());
Scott Michelfdc40a02009-02-17 22:15:04 +00002581 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002582 VT, Src1, Src2, Mask));
Mon P Wangc7849c22008-11-16 05:06:27 +00002583 return;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002584 }
2585 }
2586
Mon P Wangc7849c22008-11-16 05:06:27 +00002587 // We can't use either concat vectors or extract subvectors so fall back to
2588 // replacing the shuffle with extract and build vector.
2589 // to insert and build vector.
Mon P Wangaeb06d22008-11-10 04:46:22 +00002590 MVT EltVT = VT.getVectorElementType();
2591 MVT PtrVT = TLI.getPointerTy();
2592 SmallVector<SDValue,8> Ops;
Mon P Wangc7849c22008-11-16 05:06:27 +00002593 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002594 SDValue Arg = Mask.getOperand(i);
2595 if (Arg.getOpcode() == ISD::UNDEF) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002596 Ops.push_back(DAG.getUNDEF(EltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002597 } else {
2598 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Mon P Wangc7849c22008-11-16 05:06:27 +00002599 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2600 if (Idx < SrcNumElts)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002601 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002602 EltVT, Src1, DAG.getConstant(Idx, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002603 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00002604 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Scott Michelfdc40a02009-02-17 22:15:04 +00002605 EltVT, Src2,
Mon P Wangc7849c22008-11-16 05:06:27 +00002606 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002607 }
2608 }
Evan Chenga87008d2009-02-25 22:49:59 +00002609 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2610 VT, &Ops[0], Ops.size()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002611}
2612
2613void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2614 const Value *Op0 = I.getOperand(0);
2615 const Value *Op1 = I.getOperand(1);
2616 const Type *AggTy = I.getType();
2617 const Type *ValTy = Op1->getType();
2618 bool IntoUndef = isa<UndefValue>(Op0);
2619 bool FromUndef = isa<UndefValue>(Op1);
2620
2621 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2622 I.idx_begin(), I.idx_end());
2623
2624 SmallVector<MVT, 4> AggValueVTs;
2625 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2626 SmallVector<MVT, 4> ValValueVTs;
2627 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2628
2629 unsigned NumAggValues = AggValueVTs.size();
2630 unsigned NumValValues = ValValueVTs.size();
2631 SmallVector<SDValue, 4> Values(NumAggValues);
2632
2633 SDValue Agg = getValue(Op0);
2634 SDValue Val = getValue(Op1);
2635 unsigned i = 0;
2636 // Copy the beginning value(s) from the original aggregate.
2637 for (; i != LinearIndex; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002638 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002639 SDValue(Agg.getNode(), Agg.getResNo() + i);
2640 // Copy values from the inserted value(s).
2641 for (; i != LinearIndex + NumValValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002642 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002643 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2644 // Copy remaining value(s) from the original aggregate.
2645 for (; i != NumAggValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002646 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002647 SDValue(Agg.getNode(), Agg.getResNo() + i);
2648
Scott Michelfdc40a02009-02-17 22:15:04 +00002649 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002650 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2651 &Values[0], NumAggValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002652}
2653
2654void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2655 const Value *Op0 = I.getOperand(0);
2656 const Type *AggTy = Op0->getType();
2657 const Type *ValTy = I.getType();
2658 bool OutOfUndef = isa<UndefValue>(Op0);
2659
2660 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2661 I.idx_begin(), I.idx_end());
2662
2663 SmallVector<MVT, 4> ValValueVTs;
2664 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2665
2666 unsigned NumValValues = ValValueVTs.size();
2667 SmallVector<SDValue, 4> Values(NumValValues);
2668
2669 SDValue Agg = getValue(Op0);
2670 // Copy out the selected value(s).
2671 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2672 Values[i - LinearIndex] =
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002673 OutOfUndef ?
Dale Johannesene8d72302009-02-06 23:05:02 +00002674 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002675 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002676
Scott Michelfdc40a02009-02-17 22:15:04 +00002677 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002678 DAG.getVTList(&ValValueVTs[0], NumValValues),
2679 &Values[0], NumValValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002680}
2681
2682
2683void SelectionDAGLowering::visitGetElementPtr(User &I) {
2684 SDValue N = getValue(I.getOperand(0));
2685 const Type *Ty = I.getOperand(0)->getType();
2686
2687 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2688 OI != E; ++OI) {
2689 Value *Idx = *OI;
2690 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2691 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2692 if (Field) {
2693 // N = N + Offset
2694 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002695 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002696 DAG.getIntPtrConstant(Offset));
2697 }
2698 Ty = StTy->getElementType(Field);
2699 } else {
2700 Ty = cast<SequentialType>(Ty)->getElementType();
2701
2702 // If this is a constant subscript, handle it quickly.
2703 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2704 if (CI->getZExtValue() == 0) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002705 uint64_t Offs =
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00002706 TD->getTypePaddedSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Evan Cheng65b52df2009-02-09 21:01:06 +00002707 SDValue OffsVal;
Evan Chengb1032a82009-02-09 20:54:38 +00002708 unsigned PtrBits = TLI.getPointerTy().getSizeInBits();
Evan Cheng65b52df2009-02-09 21:01:06 +00002709 if (PtrBits < 64) {
2710 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2711 TLI.getPointerTy(),
2712 DAG.getConstant(Offs, MVT::i64));
2713 } else
Evan Chengb1032a82009-02-09 20:54:38 +00002714 OffsVal = DAG.getIntPtrConstant(Offs);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002715 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Evan Chengb1032a82009-02-09 20:54:38 +00002716 OffsVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002717 continue;
2718 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002719
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002720 // N = N + Idx * ElementSize;
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00002721 uint64_t ElementSize = TD->getTypePaddedSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002722 SDValue IdxN = getValue(Idx);
2723
2724 // If the index is smaller or larger than intptr_t, truncate or extend
2725 // it.
2726 if (IdxN.getValueType().bitsLT(N.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002727 IdxN = DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002728 N.getValueType(), IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002729 else if (IdxN.getValueType().bitsGT(N.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002730 IdxN = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002731 N.getValueType(), IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002732
2733 // If this is a multiply by a power of two, turn it into a shl
2734 // immediately. This is a very common case.
2735 if (ElementSize != 1) {
2736 if (isPowerOf2_64(ElementSize)) {
2737 unsigned Amt = Log2_64(ElementSize);
Scott Michelfdc40a02009-02-17 22:15:04 +00002738 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002739 N.getValueType(), IdxN,
Duncan Sands92abc622009-01-31 15:50:11 +00002740 DAG.getConstant(Amt, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002741 } else {
2742 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
Scott Michelfdc40a02009-02-17 22:15:04 +00002743 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002744 N.getValueType(), IdxN, Scale);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002745 }
2746 }
2747
Scott Michelfdc40a02009-02-17 22:15:04 +00002748 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002749 N.getValueType(), N, IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002750 }
2751 }
2752 setValue(&I, N);
2753}
2754
2755void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2756 // If this is a fixed sized alloca in the entry block of the function,
2757 // allocate it statically on the stack.
2758 if (FuncInfo.StaticAllocaMap.count(&I))
2759 return; // getValue will auto-populate this.
2760
2761 const Type *Ty = I.getAllocatedType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00002762 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002763 unsigned Align =
2764 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2765 I.getAlignment());
2766
2767 SDValue AllocSize = getValue(I.getArraySize());
Chris Lattner0b18e592009-03-17 19:36:00 +00002768
2769 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2770 AllocSize,
2771 DAG.getConstant(TySize, AllocSize.getValueType()));
2772
2773
2774
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002775 MVT IntPtr = TLI.getPointerTy();
2776 if (IntPtr.bitsLT(AllocSize.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002777 AllocSize = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002778 IntPtr, AllocSize);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002779 else if (IntPtr.bitsGT(AllocSize.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002780 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002781 IntPtr, AllocSize);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002782
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002783 // Handle alignment. If the requested alignment is less than or equal to
2784 // the stack alignment, ignore it. If the size is greater than or equal to
2785 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2786 unsigned StackAlign =
2787 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2788 if (Align <= StackAlign)
2789 Align = 0;
2790
2791 // Round the size of the allocation up to the stack alignment size
2792 // by add SA-1 to the size.
Scott Michelfdc40a02009-02-17 22:15:04 +00002793 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002794 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002795 DAG.getIntPtrConstant(StackAlign-1));
2796 // Mask out the low bits for alignment purposes.
Scott Michelfdc40a02009-02-17 22:15:04 +00002797 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002798 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002799 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2800
2801 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2802 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2803 MVT::Other);
Scott Michelfdc40a02009-02-17 22:15:04 +00002804 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002805 VTs, 2, Ops, 3);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002806 setValue(&I, DSA);
2807 DAG.setRoot(DSA.getValue(1));
2808
2809 // Inform the Frame Information that we have just allocated a variable-sized
2810 // object.
2811 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2812}
2813
2814void SelectionDAGLowering::visitLoad(LoadInst &I) {
2815 const Value *SV = I.getOperand(0);
2816 SDValue Ptr = getValue(SV);
2817
2818 const Type *Ty = I.getType();
2819 bool isVolatile = I.isVolatile();
2820 unsigned Alignment = I.getAlignment();
2821
2822 SmallVector<MVT, 4> ValueVTs;
2823 SmallVector<uint64_t, 4> Offsets;
2824 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2825 unsigned NumValues = ValueVTs.size();
2826 if (NumValues == 0)
2827 return;
2828
2829 SDValue Root;
2830 bool ConstantMemory = false;
2831 if (I.isVolatile())
2832 // Serialize volatile loads with other side effects.
2833 Root = getRoot();
2834 else if (AA->pointsToConstantMemory(SV)) {
2835 // Do not serialize (non-volatile) loads of constant memory with anything.
2836 Root = DAG.getEntryNode();
2837 ConstantMemory = true;
2838 } else {
2839 // Do not serialize non-volatile loads against each other.
2840 Root = DAG.getRoot();
2841 }
2842
2843 SmallVector<SDValue, 4> Values(NumValues);
2844 SmallVector<SDValue, 4> Chains(NumValues);
2845 MVT PtrVT = Ptr.getValueType();
2846 for (unsigned i = 0; i != NumValues; ++i) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002847 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
Scott Michelfdc40a02009-02-17 22:15:04 +00002848 DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002849 PtrVT, Ptr,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002850 DAG.getConstant(Offsets[i], PtrVT)),
2851 SV, Offsets[i],
2852 isVolatile, Alignment);
2853 Values[i] = L;
2854 Chains[i] = L.getValue(1);
2855 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002856
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002857 if (!ConstantMemory) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002858 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002859 MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002860 &Chains[0], NumValues);
2861 if (isVolatile)
2862 DAG.setRoot(Chain);
2863 else
2864 PendingLoads.push_back(Chain);
2865 }
2866
Scott Michelfdc40a02009-02-17 22:15:04 +00002867 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002868 DAG.getVTList(&ValueVTs[0], NumValues),
2869 &Values[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002870}
2871
2872
2873void SelectionDAGLowering::visitStore(StoreInst &I) {
2874 Value *SrcV = I.getOperand(0);
2875 Value *PtrV = I.getOperand(1);
2876
2877 SmallVector<MVT, 4> ValueVTs;
2878 SmallVector<uint64_t, 4> Offsets;
2879 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2880 unsigned NumValues = ValueVTs.size();
2881 if (NumValues == 0)
2882 return;
2883
2884 // Get the lowered operands. Note that we do this after
2885 // checking if NumResults is zero, because with zero results
2886 // the operands won't have values in the map.
2887 SDValue Src = getValue(SrcV);
2888 SDValue Ptr = getValue(PtrV);
2889
2890 SDValue Root = getRoot();
2891 SmallVector<SDValue, 4> Chains(NumValues);
2892 MVT PtrVT = Ptr.getValueType();
2893 bool isVolatile = I.isVolatile();
2894 unsigned Alignment = I.getAlignment();
2895 for (unsigned i = 0; i != NumValues; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002896 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002897 SDValue(Src.getNode(), Src.getResNo() + i),
Scott Michelfdc40a02009-02-17 22:15:04 +00002898 DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002899 PtrVT, Ptr,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002900 DAG.getConstant(Offsets[i], PtrVT)),
2901 PtrV, Offsets[i],
2902 isVolatile, Alignment);
2903
Scott Michelfdc40a02009-02-17 22:15:04 +00002904 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002905 MVT::Other, &Chains[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002906}
2907
2908/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2909/// node.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002910void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002911 unsigned Intrinsic) {
2912 bool HasChain = !I.doesNotAccessMemory();
2913 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2914
2915 // Build the operand list.
2916 SmallVector<SDValue, 8> Ops;
2917 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2918 if (OnlyLoad) {
2919 // We don't need to serialize loads against other loads.
2920 Ops.push_back(DAG.getRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002921 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002922 Ops.push_back(getRoot());
2923 }
2924 }
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002925
2926 // Info is set by getTgtMemInstrinsic
2927 TargetLowering::IntrinsicInfo Info;
2928 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2929
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002930 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002931 if (!IsTgtIntrinsic)
2932 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002933
2934 // Add all operands of the call to the operand list.
2935 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2936 SDValue Op = getValue(I.getOperand(i));
2937 assert(TLI.isTypeLegal(Op.getValueType()) &&
2938 "Intrinsic uses a non-legal type?");
2939 Ops.push_back(Op);
2940 }
2941
2942 std::vector<MVT> VTs;
2943 if (I.getType() != Type::VoidTy) {
2944 MVT VT = TLI.getValueType(I.getType());
2945 if (VT.isVector()) {
2946 const VectorType *DestTy = cast<VectorType>(I.getType());
2947 MVT EltVT = TLI.getValueType(DestTy->getElementType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002948
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002949 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2950 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2951 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002952
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002953 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2954 VTs.push_back(VT);
2955 }
2956 if (HasChain)
2957 VTs.push_back(MVT::Other);
2958
2959 const MVT *VTList = DAG.getNodeValueTypes(VTs);
2960
2961 // Create the node.
2962 SDValue Result;
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002963 if (IsTgtIntrinsic) {
2964 // This is target intrinsic that touches memory
Dale Johannesen66978ee2009-01-31 02:22:37 +00002965 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002966 VTList, VTs.size(),
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002967 &Ops[0], Ops.size(),
2968 Info.memVT, Info.ptrVal, Info.offset,
2969 Info.align, Info.vol,
2970 Info.readMem, Info.writeMem);
2971 }
2972 else if (!HasChain)
Scott Michelfdc40a02009-02-17 22:15:04 +00002973 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002974 VTList, VTs.size(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002975 &Ops[0], Ops.size());
2976 else if (I.getType() != Type::VoidTy)
Scott Michelfdc40a02009-02-17 22:15:04 +00002977 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002978 VTList, VTs.size(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002979 &Ops[0], Ops.size());
2980 else
Scott Michelfdc40a02009-02-17 22:15:04 +00002981 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002982 VTList, VTs.size(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002983 &Ops[0], Ops.size());
2984
2985 if (HasChain) {
2986 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2987 if (OnlyLoad)
2988 PendingLoads.push_back(Chain);
2989 else
2990 DAG.setRoot(Chain);
2991 }
2992 if (I.getType() != Type::VoidTy) {
2993 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2994 MVT VT = TLI.getValueType(PTy);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002995 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002996 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002997 setValue(&I, Result);
2998 }
2999}
3000
3001/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
3002static GlobalVariable *ExtractTypeInfo(Value *V) {
3003 V = V->stripPointerCasts();
3004 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
3005 assert ((GV || isa<ConstantPointerNull>(V)) &&
3006 "TypeInfo must be a global variable or NULL");
3007 return GV;
3008}
3009
3010namespace llvm {
3011
3012/// AddCatchInfo - Extract the personality and type infos from an eh.selector
3013/// call, and add them to the specified machine basic block.
3014void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3015 MachineBasicBlock *MBB) {
3016 // Inform the MachineModuleInfo of the personality for this landing pad.
3017 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3018 assert(CE->getOpcode() == Instruction::BitCast &&
3019 isa<Function>(CE->getOperand(0)) &&
3020 "Personality should be a function");
3021 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3022
3023 // Gather all the type infos for this landing pad and pass them along to
3024 // MachineModuleInfo.
3025 std::vector<GlobalVariable *> TyInfo;
3026 unsigned N = I.getNumOperands();
3027
3028 for (unsigned i = N - 1; i > 2; --i) {
3029 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3030 unsigned FilterLength = CI->getZExtValue();
3031 unsigned FirstCatch = i + FilterLength + !FilterLength;
3032 assert (FirstCatch <= N && "Invalid filter length");
3033
3034 if (FirstCatch < N) {
3035 TyInfo.reserve(N - FirstCatch);
3036 for (unsigned j = FirstCatch; j < N; ++j)
3037 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3038 MMI->addCatchTypeInfo(MBB, TyInfo);
3039 TyInfo.clear();
3040 }
3041
3042 if (!FilterLength) {
3043 // Cleanup.
3044 MMI->addCleanup(MBB);
3045 } else {
3046 // Filter.
3047 TyInfo.reserve(FilterLength - 1);
3048 for (unsigned j = i + 1; j < FirstCatch; ++j)
3049 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3050 MMI->addFilterTypeInfo(MBB, TyInfo);
3051 TyInfo.clear();
3052 }
3053
3054 N = i;
3055 }
3056 }
3057
3058 if (N > 3) {
3059 TyInfo.reserve(N - 3);
3060 for (unsigned j = 3; j < N; ++j)
3061 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3062 MMI->addCatchTypeInfo(MBB, TyInfo);
3063 }
3064}
3065
3066}
3067
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003068/// GetSignificand - Get the significand and build it into a floating-point
3069/// number with exponent of 1:
3070///
3071/// Op = (Op & 0x007fffff) | 0x3f800000;
3072///
3073/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003074static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003075GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
3076 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003077 DAG.getConstant(0x007fffff, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003078 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003079 DAG.getConstant(0x3f800000, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003080 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003081}
3082
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003083/// GetExponent - Get the exponent:
3084///
Bill Wendlinge9a72862009-01-20 21:17:57 +00003085/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003086///
3087/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003088static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003089GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3090 DebugLoc dl) {
3091 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003092 DAG.getConstant(0x7f800000, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003093 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
Duncan Sands92abc622009-01-31 15:50:11 +00003094 DAG.getConstant(23, TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003095 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003096 DAG.getConstant(127, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003097 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003098}
3099
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003100/// getF32Constant - Get 32-bit floating point constant.
3101static SDValue
3102getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3103 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3104}
3105
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003106/// Inlined utility function to implement binary input atomic intrinsics for
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003107/// visitIntrinsicCall: I is a call instruction
3108/// Op is the associated NodeType for I
3109const char *
3110SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003111 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003112 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00003113 DAG.getAtomic(Op, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003114 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003115 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003116 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003117 getValue(I.getOperand(2)),
3118 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003119 setValue(&I, L);
3120 DAG.setRoot(L.getValue(1));
3121 return 0;
3122}
3123
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003124// implVisitAluOverflow - Lower arithmetic overflow instrinsics.
Bill Wendling74c37652008-12-09 22:08:41 +00003125const char *
3126SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003127 SDValue Op1 = getValue(I.getOperand(1));
3128 SDValue Op2 = getValue(I.getOperand(2));
Bill Wendling74c37652008-12-09 22:08:41 +00003129
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003130 MVT ValueVTs[] = { Op1.getValueType(), MVT::i1 };
3131 SDValue Ops[] = { Op1, Op2 };
Bill Wendling74c37652008-12-09 22:08:41 +00003132
Scott Michelfdc40a02009-02-17 22:15:04 +00003133 SDValue Result = DAG.getNode(Op, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003134 DAG.getVTList(&ValueVTs[0], 2), &Ops[0], 2);
Bill Wendling74c37652008-12-09 22:08:41 +00003135
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003136 setValue(&I, Result);
3137 return 0;
3138}
Bill Wendling74c37652008-12-09 22:08:41 +00003139
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003140/// visitExp - Lower an exp intrinsic. Handles the special sequences for
3141/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003142void
3143SelectionDAGLowering::visitExp(CallInst &I) {
3144 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003145 DebugLoc dl = getCurDebugLoc();
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003146
3147 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3148 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3149 SDValue Op = getValue(I.getOperand(1));
3150
3151 // Put the exponent in the right bit position for later addition to the
3152 // final result:
3153 //
3154 // #define LOG2OFe 1.4426950f
3155 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003156 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003157 getF32Constant(DAG, 0x3fb8aa3b));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003158 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003159
3160 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003161 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3162 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003163
3164 // IntegerPartOfX <<= 23;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003165 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003166 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003167
3168 if (LimitFloatPrecision <= 6) {
3169 // For floating-point precision of 6:
3170 //
3171 // TwoToFractionalPartOfX =
3172 // 0.997535578f +
3173 // (0.735607626f + 0.252464424f * x) * x;
3174 //
3175 // error 0.0144103317, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003176 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003177 getF32Constant(DAG, 0x3e814304));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003178 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003179 getF32Constant(DAG, 0x3f3c50c8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003180 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3181 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003182 getF32Constant(DAG, 0x3f7f5e7e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003183 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003184
3185 // Add the exponent into the result in integer domain.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003186 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003187 TwoToFracPartOfX, IntegerPartOfX);
3188
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003189 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003190 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3191 // For floating-point precision of 12:
3192 //
3193 // TwoToFractionalPartOfX =
3194 // 0.999892986f +
3195 // (0.696457318f +
3196 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3197 //
3198 // 0.000107046256 error, which is 13 to 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003199 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003200 getF32Constant(DAG, 0x3da235e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003201 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003202 getF32Constant(DAG, 0x3e65b8f3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003203 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3204 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003205 getF32Constant(DAG, 0x3f324b07));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003206 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3207 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003208 getF32Constant(DAG, 0x3f7ff8fd));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003209 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003210
3211 // Add the exponent into the result in integer domain.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003212 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003213 TwoToFracPartOfX, IntegerPartOfX);
3214
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003215 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003216 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3217 // For floating-point precision of 18:
3218 //
3219 // TwoToFractionalPartOfX =
3220 // 0.999999982f +
3221 // (0.693148872f +
3222 // (0.240227044f +
3223 // (0.554906021e-1f +
3224 // (0.961591928e-2f +
3225 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3226 //
3227 // error 2.47208000*10^(-7), which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003228 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003229 getF32Constant(DAG, 0x3924b03e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003230 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003231 getF32Constant(DAG, 0x3ab24b87));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003232 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3233 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003234 getF32Constant(DAG, 0x3c1d8c17));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003235 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3236 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003237 getF32Constant(DAG, 0x3d634a1d));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003238 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3239 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003240 getF32Constant(DAG, 0x3e75fe14));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003241 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3242 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003243 getF32Constant(DAG, 0x3f317234));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003244 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3245 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003246 getF32Constant(DAG, 0x3f800000));
Scott Michelfdc40a02009-02-17 22:15:04 +00003247 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003248 MVT::i32, t13);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003249
3250 // Add the exponent into the result in integer domain.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003251 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003252 TwoToFracPartOfX, IntegerPartOfX);
3253
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003254 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003255 }
3256 } else {
3257 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003258 result = DAG.getNode(ISD::FEXP, dl,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003259 getValue(I.getOperand(1)).getValueType(),
3260 getValue(I.getOperand(1)));
3261 }
3262
Dale Johannesen59e577f2008-09-05 18:38:42 +00003263 setValue(&I, result);
3264}
3265
Bill Wendling39150252008-09-09 20:39:27 +00003266/// visitLog - Lower a log intrinsic. Handles the special sequences for
3267/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003268void
3269SelectionDAGLowering::visitLog(CallInst &I) {
3270 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003271 DebugLoc dl = getCurDebugLoc();
Bill Wendling39150252008-09-09 20:39:27 +00003272
3273 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3274 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3275 SDValue Op = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003276 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling39150252008-09-09 20:39:27 +00003277
3278 // Scale the exponent by log(2) [0.69314718f].
Dale Johannesen66978ee2009-01-31 02:22:37 +00003279 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003280 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003281 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003282
3283 // Get the significand and build it into a floating-point number with
3284 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003285 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling39150252008-09-09 20:39:27 +00003286
3287 if (LimitFloatPrecision <= 6) {
3288 // For floating-point precision of 6:
3289 //
3290 // LogofMantissa =
3291 // -1.1609546f +
3292 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003293 //
Bill Wendling39150252008-09-09 20:39:27 +00003294 // error 0.0034276066, which is better than 8 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003295 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003296 getF32Constant(DAG, 0xbe74c456));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003297 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003298 getF32Constant(DAG, 0x3fb3a2b1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003299 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3300 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003301 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00003302
Scott Michelfdc40a02009-02-17 22:15:04 +00003303 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003304 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003305 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3306 // For floating-point precision of 12:
3307 //
3308 // LogOfMantissa =
3309 // -1.7417939f +
3310 // (2.8212026f +
3311 // (-1.4699568f +
3312 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3313 //
3314 // error 0.000061011436, which is 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003315 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003316 getF32Constant(DAG, 0xbd67b6d6));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003317 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003318 getF32Constant(DAG, 0x3ee4f4b8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003319 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3320 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003321 getF32Constant(DAG, 0x3fbc278b));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003322 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3323 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003324 getF32Constant(DAG, 0x40348e95));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003325 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3326 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003327 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00003328
Scott Michelfdc40a02009-02-17 22:15:04 +00003329 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003330 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003331 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3332 // For floating-point precision of 18:
3333 //
3334 // LogOfMantissa =
3335 // -2.1072184f +
3336 // (4.2372794f +
3337 // (-3.7029485f +
3338 // (2.2781945f +
3339 // (-0.87823314f +
3340 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3341 //
3342 // error 0.0000023660568, which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003343 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003344 getF32Constant(DAG, 0xbc91e5ac));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003345 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003346 getF32Constant(DAG, 0x3e4350aa));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003347 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3348 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003349 getF32Constant(DAG, 0x3f60d3e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003350 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3351 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003352 getF32Constant(DAG, 0x4011cdf0));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003353 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3354 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003355 getF32Constant(DAG, 0x406cfd1c));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003356 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3357 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003358 getF32Constant(DAG, 0x408797cb));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003359 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3360 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003361 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003362
Scott Michelfdc40a02009-02-17 22:15:04 +00003363 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003364 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003365 }
3366 } else {
3367 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003368 result = DAG.getNode(ISD::FLOG, dl,
Bill Wendling39150252008-09-09 20:39:27 +00003369 getValue(I.getOperand(1)).getValueType(),
3370 getValue(I.getOperand(1)));
3371 }
3372
Dale Johannesen59e577f2008-09-05 18:38:42 +00003373 setValue(&I, result);
3374}
3375
Bill Wendling3eb59402008-09-09 00:28:24 +00003376/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3377/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003378void
3379SelectionDAGLowering::visitLog2(CallInst &I) {
3380 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003381 DebugLoc dl = getCurDebugLoc();
Bill Wendling3eb59402008-09-09 00:28:24 +00003382
Dale Johannesen853244f2008-09-05 23:49:37 +00003383 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003384 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3385 SDValue Op = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003386 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003387
Bill Wendling39150252008-09-09 20:39:27 +00003388 // Get the exponent.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003389 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00003390
3391 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003392 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003393 SDValue X = GetSignificand(DAG, Op1, dl);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003394
Bill Wendling3eb59402008-09-09 00:28:24 +00003395 // Different possible minimax approximations of significand in
3396 // floating-point for various degrees of accuracy over [1,2].
3397 if (LimitFloatPrecision <= 6) {
3398 // For floating-point precision of 6:
3399 //
3400 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3401 //
3402 // error 0.0049451742, which is more than 7 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003403 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003404 getF32Constant(DAG, 0xbeb08fe0));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003405 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003406 getF32Constant(DAG, 0x40019463));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003407 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3408 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003409 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003410
Scott Michelfdc40a02009-02-17 22:15:04 +00003411 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003412 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003413 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3414 // For floating-point precision of 12:
3415 //
3416 // Log2ofMantissa =
3417 // -2.51285454f +
3418 // (4.07009056f +
3419 // (-2.12067489f +
3420 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003421 //
Bill Wendling3eb59402008-09-09 00:28:24 +00003422 // error 0.0000876136000, which is better than 13 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003423 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003424 getF32Constant(DAG, 0xbda7262e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003425 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003426 getF32Constant(DAG, 0x3f25280b));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003427 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3428 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003429 getF32Constant(DAG, 0x4007b923));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003430 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3431 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003432 getF32Constant(DAG, 0x40823e2f));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003433 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3434 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003435 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003436
Scott Michelfdc40a02009-02-17 22:15:04 +00003437 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003438 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003439 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3440 // For floating-point precision of 18:
3441 //
3442 // Log2ofMantissa =
3443 // -3.0400495f +
3444 // (6.1129976f +
3445 // (-5.3420409f +
3446 // (3.2865683f +
3447 // (-1.2669343f +
3448 // (0.27515199f -
3449 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3450 //
3451 // error 0.0000018516, which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003452 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003453 getF32Constant(DAG, 0xbcd2769e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003454 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003455 getF32Constant(DAG, 0x3e8ce0b9));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003456 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3457 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003458 getF32Constant(DAG, 0x3fa22ae7));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003459 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3460 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003461 getF32Constant(DAG, 0x40525723));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003462 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3463 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003464 getF32Constant(DAG, 0x40aaf200));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003465 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3466 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003467 getF32Constant(DAG, 0x40c39dad));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003468 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3469 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003470 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003471
Scott Michelfdc40a02009-02-17 22:15:04 +00003472 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003473 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003474 }
Dale Johannesen853244f2008-09-05 23:49:37 +00003475 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003476 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003477 result = DAG.getNode(ISD::FLOG2, dl,
Dale Johannesen853244f2008-09-05 23:49:37 +00003478 getValue(I.getOperand(1)).getValueType(),
3479 getValue(I.getOperand(1)));
3480 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003481
Dale Johannesen59e577f2008-09-05 18:38:42 +00003482 setValue(&I, result);
3483}
3484
Bill Wendling3eb59402008-09-09 00:28:24 +00003485/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3486/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003487void
3488SelectionDAGLowering::visitLog10(CallInst &I) {
3489 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003490 DebugLoc dl = getCurDebugLoc();
Bill Wendling181b6272008-10-19 20:34:04 +00003491
Dale Johannesen852680a2008-09-05 21:27:19 +00003492 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003493 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3494 SDValue Op = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003495 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003496
Bill Wendling39150252008-09-09 20:39:27 +00003497 // Scale the exponent by log10(2) [0.30102999f].
Dale Johannesen66978ee2009-01-31 02:22:37 +00003498 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003499 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003500 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003501
3502 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003503 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003504 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00003505
3506 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003507 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003508 //
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003509 // Log10ofMantissa =
3510 // -0.50419619f +
3511 // (0.60948995f - 0.10380950f * x) * x;
3512 //
3513 // error 0.0014886165, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003514 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003515 getF32Constant(DAG, 0xbdd49a13));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003516 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003517 getF32Constant(DAG, 0x3f1c0789));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003518 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3519 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003520 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003521
Scott Michelfdc40a02009-02-17 22:15:04 +00003522 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003523 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003524 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3525 // For floating-point precision of 12:
3526 //
3527 // Log10ofMantissa =
3528 // -0.64831180f +
3529 // (0.91751397f +
3530 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3531 //
3532 // error 0.00019228036, which is better than 12 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003533 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003534 getF32Constant(DAG, 0x3d431f31));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003535 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003536 getF32Constant(DAG, 0x3ea21fb2));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003537 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3538 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003539 getF32Constant(DAG, 0x3f6ae232));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003540 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3541 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003542 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00003543
Scott Michelfdc40a02009-02-17 22:15:04 +00003544 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003545 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003546 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003547 // For floating-point precision of 18:
3548 //
3549 // Log10ofMantissa =
3550 // -0.84299375f +
3551 // (1.5327582f +
3552 // (-1.0688956f +
3553 // (0.49102474f +
3554 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3555 //
3556 // error 0.0000037995730, which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003557 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003558 getF32Constant(DAG, 0x3c5d51ce));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003559 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003560 getF32Constant(DAG, 0x3e00685a));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003561 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3562 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003563 getF32Constant(DAG, 0x3efb6798));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003564 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3565 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003566 getF32Constant(DAG, 0x3f88d192));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003567 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3568 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003569 getF32Constant(DAG, 0x3fc4316c));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003570 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3571 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003572 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003573
Scott Michelfdc40a02009-02-17 22:15:04 +00003574 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003575 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003576 }
Dale Johannesen852680a2008-09-05 21:27:19 +00003577 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003578 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003579 result = DAG.getNode(ISD::FLOG10, dl,
Dale Johannesen852680a2008-09-05 21:27:19 +00003580 getValue(I.getOperand(1)).getValueType(),
3581 getValue(I.getOperand(1)));
3582 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003583
Dale Johannesen59e577f2008-09-05 18:38:42 +00003584 setValue(&I, result);
3585}
3586
Bill Wendlinge10c8142008-09-09 22:39:21 +00003587/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3588/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003589void
3590SelectionDAGLowering::visitExp2(CallInst &I) {
3591 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003592 DebugLoc dl = getCurDebugLoc();
Bill Wendlinge10c8142008-09-09 22:39:21 +00003593
Dale Johannesen601d3c02008-09-05 01:48:15 +00003594 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00003595 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3596 SDValue Op = getValue(I.getOperand(1));
3597
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003598 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003599
3600 // FractionalPartOfX = x - (float)IntegerPartOfX;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003601 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3602 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003603
3604 // IntegerPartOfX <<= 23;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003605 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003606 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003607
3608 if (LimitFloatPrecision <= 6) {
3609 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003610 //
Bill Wendlinge10c8142008-09-09 22:39:21 +00003611 // TwoToFractionalPartOfX =
3612 // 0.997535578f +
3613 // (0.735607626f + 0.252464424f * x) * x;
3614 //
3615 // error 0.0144103317, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003616 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003617 getF32Constant(DAG, 0x3e814304));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003618 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003619 getF32Constant(DAG, 0x3f3c50c8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003620 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3621 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003622 getF32Constant(DAG, 0x3f7f5e7e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003623 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003624 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003625 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003626
Scott Michelfdc40a02009-02-17 22:15:04 +00003627 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003628 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003629 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3630 // For floating-point precision of 12:
3631 //
3632 // TwoToFractionalPartOfX =
3633 // 0.999892986f +
3634 // (0.696457318f +
3635 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3636 //
3637 // error 0.000107046256, which is 13 to 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003638 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003639 getF32Constant(DAG, 0x3da235e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003640 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003641 getF32Constant(DAG, 0x3e65b8f3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003642 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3643 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003644 getF32Constant(DAG, 0x3f324b07));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003645 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3646 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003647 getF32Constant(DAG, 0x3f7ff8fd));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003648 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003649 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003650 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003651
Scott Michelfdc40a02009-02-17 22:15:04 +00003652 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003653 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003654 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3655 // For floating-point precision of 18:
3656 //
3657 // TwoToFractionalPartOfX =
3658 // 0.999999982f +
3659 // (0.693148872f +
3660 // (0.240227044f +
3661 // (0.554906021e-1f +
3662 // (0.961591928e-2f +
3663 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3664 // error 2.47208000*10^(-7), which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003665 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003666 getF32Constant(DAG, 0x3924b03e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003667 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003668 getF32Constant(DAG, 0x3ab24b87));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003669 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3670 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003671 getF32Constant(DAG, 0x3c1d8c17));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003672 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3673 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003674 getF32Constant(DAG, 0x3d634a1d));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003675 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3676 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003677 getF32Constant(DAG, 0x3e75fe14));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003678 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3679 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003680 getF32Constant(DAG, 0x3f317234));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003681 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3682 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003683 getF32Constant(DAG, 0x3f800000));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003684 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003685 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003686 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003687
Scott Michelfdc40a02009-02-17 22:15:04 +00003688 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003689 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003690 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00003691 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003692 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003693 result = DAG.getNode(ISD::FEXP2, dl,
Dale Johannesen601d3c02008-09-05 01:48:15 +00003694 getValue(I.getOperand(1)).getValueType(),
3695 getValue(I.getOperand(1)));
3696 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00003697
Dale Johannesen601d3c02008-09-05 01:48:15 +00003698 setValue(&I, result);
3699}
3700
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003701/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3702/// limited-precision mode with x == 10.0f.
3703void
3704SelectionDAGLowering::visitPow(CallInst &I) {
3705 SDValue result;
3706 Value *Val = I.getOperand(1);
Dale Johannesen66978ee2009-01-31 02:22:37 +00003707 DebugLoc dl = getCurDebugLoc();
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003708 bool IsExp10 = false;
3709
3710 if (getValue(Val).getValueType() == MVT::f32 &&
Bill Wendling277fc242008-09-10 00:24:59 +00003711 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003712 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3713 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3714 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3715 APFloat Ten(10.0f);
3716 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3717 }
3718 }
3719 }
3720
3721 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3722 SDValue Op = getValue(I.getOperand(2));
3723
3724 // Put the exponent in the right bit position for later addition to the
3725 // final result:
3726 //
3727 // #define LOG2OF10 3.3219281f
3728 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003729 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003730 getF32Constant(DAG, 0x40549a78));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003731 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003732
3733 // FractionalPartOfX = x - (float)IntegerPartOfX;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003734 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3735 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003736
3737 // IntegerPartOfX <<= 23;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003738 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003739 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003740
3741 if (LimitFloatPrecision <= 6) {
3742 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003743 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003744 // twoToFractionalPartOfX =
3745 // 0.997535578f +
3746 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003747 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003748 // error 0.0144103317, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003749 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003750 getF32Constant(DAG, 0x3e814304));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003751 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003752 getF32Constant(DAG, 0x3f3c50c8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003753 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3754 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003755 getF32Constant(DAG, 0x3f7f5e7e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003756 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003757 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003758 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003759
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003760 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3761 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003762 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3763 // For floating-point precision of 12:
3764 //
3765 // TwoToFractionalPartOfX =
3766 // 0.999892986f +
3767 // (0.696457318f +
3768 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3769 //
3770 // error 0.000107046256, which is 13 to 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003771 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003772 getF32Constant(DAG, 0x3da235e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003773 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003774 getF32Constant(DAG, 0x3e65b8f3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003775 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3776 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003777 getF32Constant(DAG, 0x3f324b07));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003778 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3779 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003780 getF32Constant(DAG, 0x3f7ff8fd));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003781 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003782 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003783 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003784
Scott Michelfdc40a02009-02-17 22:15:04 +00003785 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003786 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003787 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3788 // For floating-point precision of 18:
3789 //
3790 // TwoToFractionalPartOfX =
3791 // 0.999999982f +
3792 // (0.693148872f +
3793 // (0.240227044f +
3794 // (0.554906021e-1f +
3795 // (0.961591928e-2f +
3796 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3797 // error 2.47208000*10^(-7), which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003798 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003799 getF32Constant(DAG, 0x3924b03e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003800 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003801 getF32Constant(DAG, 0x3ab24b87));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003802 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3803 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003804 getF32Constant(DAG, 0x3c1d8c17));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003805 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3806 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003807 getF32Constant(DAG, 0x3d634a1d));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003808 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3809 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003810 getF32Constant(DAG, 0x3e75fe14));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003811 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3812 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003813 getF32Constant(DAG, 0x3f317234));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003814 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3815 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003816 getF32Constant(DAG, 0x3f800000));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003817 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003818 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003819 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003820
Scott Michelfdc40a02009-02-17 22:15:04 +00003821 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003822 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003823 }
3824 } else {
3825 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003826 result = DAG.getNode(ISD::FPOW, dl,
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003827 getValue(I.getOperand(1)).getValueType(),
3828 getValue(I.getOperand(1)),
3829 getValue(I.getOperand(2)));
3830 }
3831
3832 setValue(&I, result);
3833}
3834
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003835/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3836/// we want to emit this as a call to a named external function, return the name
3837/// otherwise lower it and return null.
3838const char *
3839SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00003840 DebugLoc dl = getCurDebugLoc();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003841 switch (Intrinsic) {
3842 default:
3843 // By default, turn this into a target intrinsic node.
3844 visitTargetIntrinsic(I, Intrinsic);
3845 return 0;
3846 case Intrinsic::vastart: visitVAStart(I); return 0;
3847 case Intrinsic::vaend: visitVAEnd(I); return 0;
3848 case Intrinsic::vacopy: visitVACopy(I); return 0;
3849 case Intrinsic::returnaddress:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003850 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003851 getValue(I.getOperand(1))));
3852 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00003853 case Intrinsic::frameaddress:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003854 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003855 getValue(I.getOperand(1))));
3856 return 0;
3857 case Intrinsic::setjmp:
3858 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3859 break;
3860 case Intrinsic::longjmp:
3861 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3862 break;
Chris Lattner824b9582008-11-21 16:42:48 +00003863 case Intrinsic::memcpy: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003864 SDValue Op1 = getValue(I.getOperand(1));
3865 SDValue Op2 = getValue(I.getOperand(2));
3866 SDValue Op3 = getValue(I.getOperand(3));
3867 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Dale Johannesena04b7572009-02-03 23:04:43 +00003868 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003869 I.getOperand(1), 0, I.getOperand(2), 0));
3870 return 0;
3871 }
Chris Lattner824b9582008-11-21 16:42:48 +00003872 case Intrinsic::memset: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003873 SDValue Op1 = getValue(I.getOperand(1));
3874 SDValue Op2 = getValue(I.getOperand(2));
3875 SDValue Op3 = getValue(I.getOperand(3));
3876 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Dale Johannesena04b7572009-02-03 23:04:43 +00003877 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003878 I.getOperand(1), 0));
3879 return 0;
3880 }
Chris Lattner824b9582008-11-21 16:42:48 +00003881 case Intrinsic::memmove: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003882 SDValue Op1 = getValue(I.getOperand(1));
3883 SDValue Op2 = getValue(I.getOperand(2));
3884 SDValue Op3 = getValue(I.getOperand(3));
3885 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3886
3887 // If the source and destination are known to not be aliases, we can
3888 // lower memmove as memcpy.
3889 uint64_t Size = -1ULL;
3890 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003891 Size = C->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003892 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3893 AliasAnalysis::NoAlias) {
Dale Johannesena04b7572009-02-03 23:04:43 +00003894 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003895 I.getOperand(1), 0, I.getOperand(2), 0));
3896 return 0;
3897 }
3898
Dale Johannesena04b7572009-02-03 23:04:43 +00003899 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003900 I.getOperand(1), 0, I.getOperand(2), 0));
3901 return 0;
3902 }
3903 case Intrinsic::dbg_stoppoint: {
Devang Patel83489bb2009-01-13 00:35:13 +00003904 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003905 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003906 if (DW && DW->ValidDebugInfo(SPI.getContext())) {
Evan Chenge3d42322009-02-25 07:04:34 +00003907 MachineFunction &MF = DAG.getMachineFunction();
Dale Johannesenbeaec4c2009-03-25 17:36:08 +00003908 if (Fast)
3909 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3910 SPI.getLine(),
3911 SPI.getColumn(),
3912 SPI.getContext()));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003913 DICompileUnit CU(cast<GlobalVariable>(SPI.getContext()));
Bill Wendling0582ae92009-03-13 04:39:26 +00003914 std::string Dir, FN;
3915 unsigned SrcFile = DW->getOrCreateSourceID(CU.getDirectory(Dir),
3916 CU.getFilename(FN));
Evan Chenge3d42322009-02-25 07:04:34 +00003917 unsigned idx = MF.getOrCreateDebugLocID(SrcFile,
3918 SPI.getLine(), SPI.getColumn());
Dale Johannesen66978ee2009-01-31 02:22:37 +00003919 setCurDebugLoc(DebugLoc::get(idx));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003920 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003921 return 0;
3922 }
3923 case Intrinsic::dbg_region_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003924 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003925 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Bill Wendling92c1e122009-02-13 02:16:35 +00003926 if (DW && DW->ValidDebugInfo(RSI.getContext())) {
3927 unsigned LabelID =
3928 DW->RecordRegionStart(cast<GlobalVariable>(RSI.getContext()));
Bill Wendlingdfdacee2009-02-19 21:12:54 +00003929 if (Fast)
Bill Wendling86e6cb92009-02-17 01:04:54 +00003930 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3931 getRoot(), LabelID));
Bill Wendling92c1e122009-02-13 02:16:35 +00003932 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003933
3934 return 0;
3935 }
3936 case Intrinsic::dbg_region_end: {
Devang Patel83489bb2009-01-13 00:35:13 +00003937 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003938 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Bill Wendling92c1e122009-02-13 02:16:35 +00003939 if (DW && DW->ValidDebugInfo(REI.getContext())) {
3940 unsigned LabelID =
3941 DW->RecordRegionEnd(cast<GlobalVariable>(REI.getContext()));
Bill Wendlingdfdacee2009-02-19 21:12:54 +00003942 if (Fast)
Bill Wendling86e6cb92009-02-17 01:04:54 +00003943 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3944 getRoot(), LabelID));
Bill Wendling92c1e122009-02-13 02:16:35 +00003945 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003946
3947 return 0;
3948 }
3949 case Intrinsic::dbg_func_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003950 DwarfWriter *DW = DAG.getDwarfWriter();
3951 if (!DW) return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003952 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3953 Value *SP = FSI.getSubprogram();
Devang Patelcf3a4482009-01-15 23:41:32 +00003954 if (SP && DW->ValidDebugInfo(SP)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003955 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3956 // what (most?) gdb expects.
Evan Chenge3d42322009-02-25 07:04:34 +00003957 MachineFunction &MF = DAG.getMachineFunction();
Devang Patel83489bb2009-01-13 00:35:13 +00003958 DISubprogram Subprogram(cast<GlobalVariable>(SP));
3959 DICompileUnit CompileUnit = Subprogram.getCompileUnit();
Bill Wendling0582ae92009-03-13 04:39:26 +00003960 std::string Dir, FN;
3961 unsigned SrcFile = DW->getOrCreateSourceID(CompileUnit.getDirectory(Dir),
3962 CompileUnit.getFilename(FN));
Bill Wendling9bc96a52009-02-03 00:55:04 +00003963
Devang Patel20dd0462008-11-06 00:30:09 +00003964 // Record the source line but does not create a label for the normal
3965 // function start. It will be emitted at asm emission time. However,
3966 // create a label if this is a beginning of inlined function.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003967 unsigned Line = Subprogram.getLineNumber();
Bill Wendling92c1e122009-02-13 02:16:35 +00003968
Bill Wendling5aa49772009-02-24 02:35:30 +00003969 if (Fast) {
Bill Wendling86e6cb92009-02-17 01:04:54 +00003970 unsigned LabelID = DW->RecordSourceLine(Line, 0, SrcFile);
3971 if (DW->getRecordSourceLineCount() != 1)
3972 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3973 getRoot(), LabelID));
3974 }
Bill Wendling92c1e122009-02-13 02:16:35 +00003975
Evan Chenge3d42322009-02-25 07:04:34 +00003976 setCurDebugLoc(DebugLoc::get(MF.getOrCreateDebugLocID(SrcFile, Line, 0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003977 }
3978
3979 return 0;
3980 }
Bill Wendling92c1e122009-02-13 02:16:35 +00003981 case Intrinsic::dbg_declare: {
Bill Wendling5aa49772009-02-24 02:35:30 +00003982 if (Fast) {
Bill Wendling86e6cb92009-02-17 01:04:54 +00003983 DwarfWriter *DW = DAG.getDwarfWriter();
3984 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3985 Value *Variable = DI.getVariable();
3986 if (DW && DW->ValidDebugInfo(Variable))
3987 DAG.setRoot(DAG.getNode(ISD::DECLARE, dl, MVT::Other, getRoot(),
3988 getValue(DI.getAddress()), getValue(Variable)));
3989 } else {
3990 // FIXME: Do something sensible here when we support debug declare.
3991 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003992 return 0;
Bill Wendling92c1e122009-02-13 02:16:35 +00003993 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003994 case Intrinsic::eh_exception: {
3995 if (!CurMBB->isLandingPad()) {
3996 // FIXME: Mark exception register as live in. Hack for PR1508.
3997 unsigned Reg = TLI.getExceptionAddressRegister();
3998 if (Reg) CurMBB->addLiveIn(Reg);
3999 }
4000 // Insert the EXCEPTIONADDR instruction.
4001 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4002 SDValue Ops[1];
4003 Ops[0] = DAG.getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004004 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004005 setValue(&I, Op);
4006 DAG.setRoot(Op.getValue(1));
4007 return 0;
4008 }
4009
4010 case Intrinsic::eh_selector_i32:
4011 case Intrinsic::eh_selector_i64: {
4012 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4013 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
4014 MVT::i32 : MVT::i64);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004015
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004016 if (MMI) {
4017 if (CurMBB->isLandingPad())
4018 AddCatchInfo(I, MMI, CurMBB);
4019 else {
4020#ifndef NDEBUG
4021 FuncInfo.CatchInfoLost.insert(&I);
4022#endif
4023 // FIXME: Mark exception selector register as live in. Hack for PR1508.
4024 unsigned Reg = TLI.getExceptionSelectorRegister();
4025 if (Reg) CurMBB->addLiveIn(Reg);
4026 }
4027
4028 // Insert the EHSELECTION instruction.
4029 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
4030 SDValue Ops[2];
4031 Ops[0] = getValue(I.getOperand(1));
4032 Ops[1] = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004033 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004034 setValue(&I, Op);
4035 DAG.setRoot(Op.getValue(1));
4036 } else {
4037 setValue(&I, DAG.getConstant(0, VT));
4038 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004039
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004040 return 0;
4041 }
4042
4043 case Intrinsic::eh_typeid_for_i32:
4044 case Intrinsic::eh_typeid_for_i64: {
4045 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4046 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
4047 MVT::i32 : MVT::i64);
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004048
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004049 if (MMI) {
4050 // Find the type id for the given typeinfo.
4051 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
4052
4053 unsigned TypeID = MMI->getTypeIDFor(GV);
4054 setValue(&I, DAG.getConstant(TypeID, VT));
4055 } else {
4056 // Return something different to eh_selector.
4057 setValue(&I, DAG.getConstant(1, VT));
4058 }
4059
4060 return 0;
4061 }
4062
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004063 case Intrinsic::eh_return_i32:
4064 case Intrinsic::eh_return_i64:
4065 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004066 MMI->setCallsEHReturn(true);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004067 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004068 MVT::Other,
4069 getControlRoot(),
4070 getValue(I.getOperand(1)),
4071 getValue(I.getOperand(2))));
4072 } else {
4073 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
4074 }
4075
4076 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004077 case Intrinsic::eh_unwind_init:
4078 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4079 MMI->setCallsUnwindInit(true);
4080 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004081
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004082 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004083
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004084 case Intrinsic::eh_dwarf_cfa: {
4085 MVT VT = getValue(I.getOperand(1)).getValueType();
4086 SDValue CfaArg;
4087 if (VT.bitsGT(TLI.getPointerTy()))
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004088 CfaArg = DAG.getNode(ISD::TRUNCATE, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004089 TLI.getPointerTy(), getValue(I.getOperand(1)));
4090 else
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004091 CfaArg = DAG.getNode(ISD::SIGN_EXTEND, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004092 TLI.getPointerTy(), getValue(I.getOperand(1)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004093
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004094 SDValue Offset = DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004095 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004096 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004097 TLI.getPointerTy()),
4098 CfaArg);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004099 setValue(&I, DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004100 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004101 DAG.getNode(ISD::FRAMEADDR, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004102 TLI.getPointerTy(),
4103 DAG.getConstant(0,
4104 TLI.getPointerTy())),
4105 Offset));
4106 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004107 }
4108
Mon P Wang77cdf302008-11-10 20:54:11 +00004109 case Intrinsic::convertff:
4110 case Intrinsic::convertfsi:
4111 case Intrinsic::convertfui:
4112 case Intrinsic::convertsif:
4113 case Intrinsic::convertuif:
4114 case Intrinsic::convertss:
4115 case Intrinsic::convertsu:
4116 case Intrinsic::convertus:
4117 case Intrinsic::convertuu: {
4118 ISD::CvtCode Code = ISD::CVT_INVALID;
4119 switch (Intrinsic) {
4120 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4121 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4122 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4123 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4124 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4125 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4126 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4127 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4128 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4129 }
4130 MVT DestVT = TLI.getValueType(I.getType());
4131 Value* Op1 = I.getOperand(1);
Dale Johannesena04b7572009-02-03 23:04:43 +00004132 setValue(&I, DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
Mon P Wang77cdf302008-11-10 20:54:11 +00004133 DAG.getValueType(DestVT),
4134 DAG.getValueType(getValue(Op1).getValueType()),
4135 getValue(I.getOperand(2)),
4136 getValue(I.getOperand(3)),
4137 Code));
4138 return 0;
4139 }
4140
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004141 case Intrinsic::sqrt:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004142 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004143 getValue(I.getOperand(1)).getValueType(),
4144 getValue(I.getOperand(1))));
4145 return 0;
4146 case Intrinsic::powi:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004147 setValue(&I, DAG.getNode(ISD::FPOWI, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004148 getValue(I.getOperand(1)).getValueType(),
4149 getValue(I.getOperand(1)),
4150 getValue(I.getOperand(2))));
4151 return 0;
4152 case Intrinsic::sin:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004153 setValue(&I, DAG.getNode(ISD::FSIN, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004154 getValue(I.getOperand(1)).getValueType(),
4155 getValue(I.getOperand(1))));
4156 return 0;
4157 case Intrinsic::cos:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004158 setValue(&I, DAG.getNode(ISD::FCOS, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004159 getValue(I.getOperand(1)).getValueType(),
4160 getValue(I.getOperand(1))));
4161 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004162 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004163 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004164 return 0;
4165 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004166 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004167 return 0;
4168 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004169 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004170 return 0;
4171 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004172 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004173 return 0;
4174 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00004175 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004176 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004177 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004178 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004179 return 0;
4180 case Intrinsic::pcmarker: {
4181 SDValue Tmp = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004182 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004183 return 0;
4184 }
4185 case Intrinsic::readcyclecounter: {
4186 SDValue Op = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004187 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004188 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
4189 &Op, 1);
4190 setValue(&I, Tmp);
4191 DAG.setRoot(Tmp.getValue(1));
4192 return 0;
4193 }
4194 case Intrinsic::part_select: {
4195 // Currently not implemented: just abort
4196 assert(0 && "part_select intrinsic not implemented");
4197 abort();
4198 }
4199 case Intrinsic::part_set: {
4200 // Currently not implemented: just abort
4201 assert(0 && "part_set intrinsic not implemented");
4202 abort();
4203 }
4204 case Intrinsic::bswap:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004205 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004206 getValue(I.getOperand(1)).getValueType(),
4207 getValue(I.getOperand(1))));
4208 return 0;
4209 case Intrinsic::cttz: {
4210 SDValue Arg = getValue(I.getOperand(1));
4211 MVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004212 SDValue result = DAG.getNode(ISD::CTTZ, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004213 setValue(&I, result);
4214 return 0;
4215 }
4216 case Intrinsic::ctlz: {
4217 SDValue Arg = getValue(I.getOperand(1));
4218 MVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004219 SDValue result = DAG.getNode(ISD::CTLZ, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004220 setValue(&I, result);
4221 return 0;
4222 }
4223 case Intrinsic::ctpop: {
4224 SDValue Arg = getValue(I.getOperand(1));
4225 MVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004226 SDValue result = DAG.getNode(ISD::CTPOP, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004227 setValue(&I, result);
4228 return 0;
4229 }
4230 case Intrinsic::stacksave: {
4231 SDValue Op = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004232 SDValue Tmp = DAG.getNode(ISD::STACKSAVE, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004233 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
4234 setValue(&I, Tmp);
4235 DAG.setRoot(Tmp.getValue(1));
4236 return 0;
4237 }
4238 case Intrinsic::stackrestore: {
4239 SDValue Tmp = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004240 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004241 return 0;
4242 }
Bill Wendling57344502008-11-18 11:01:33 +00004243 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00004244 // Emit code into the DAG to store the stack guard onto the stack.
4245 MachineFunction &MF = DAG.getMachineFunction();
4246 MachineFrameInfo *MFI = MF.getFrameInfo();
4247 MVT PtrTy = TLI.getPointerTy();
4248
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004249 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4250 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
Bill Wendlingb2a42982008-11-06 02:29:10 +00004251
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004252 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00004253 MFI->setStackProtectorIndex(FI);
4254
4255 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4256
4257 // Store the stack protector onto the stack.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004258 SDValue Result = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
Bill Wendlingb2a42982008-11-06 02:29:10 +00004259 PseudoSourceValue::getFixedStack(FI),
4260 0, true);
4261 setValue(&I, Result);
4262 DAG.setRoot(Result);
4263 return 0;
4264 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004265 case Intrinsic::var_annotation:
4266 // Discard annotate attributes
4267 return 0;
4268
4269 case Intrinsic::init_trampoline: {
4270 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4271
4272 SDValue Ops[6];
4273 Ops[0] = getRoot();
4274 Ops[1] = getValue(I.getOperand(1));
4275 Ops[2] = getValue(I.getOperand(2));
4276 Ops[3] = getValue(I.getOperand(3));
4277 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4278 Ops[5] = DAG.getSrcValue(F);
4279
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004280 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004281 DAG.getNodeValueTypes(TLI.getPointerTy(),
4282 MVT::Other), 2,
4283 Ops, 6);
4284
4285 setValue(&I, Tmp);
4286 DAG.setRoot(Tmp.getValue(1));
4287 return 0;
4288 }
4289
4290 case Intrinsic::gcroot:
4291 if (GFI) {
4292 Value *Alloca = I.getOperand(1);
4293 Constant *TypeMap = cast<Constant>(I.getOperand(2));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004294
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004295 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4296 GFI->addStackRoot(FI->getIndex(), TypeMap);
4297 }
4298 return 0;
4299
4300 case Intrinsic::gcread:
4301 case Intrinsic::gcwrite:
4302 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
4303 return 0;
4304
4305 case Intrinsic::flt_rounds: {
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004306 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004307 return 0;
4308 }
4309
4310 case Intrinsic::trap: {
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004311 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004312 return 0;
4313 }
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004314
Bill Wendlingef375462008-11-21 02:38:44 +00004315 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00004316 return implVisitAluOverflow(I, ISD::UADDO);
4317 case Intrinsic::sadd_with_overflow:
4318 return implVisitAluOverflow(I, ISD::SADDO);
4319 case Intrinsic::usub_with_overflow:
4320 return implVisitAluOverflow(I, ISD::USUBO);
4321 case Intrinsic::ssub_with_overflow:
4322 return implVisitAluOverflow(I, ISD::SSUBO);
4323 case Intrinsic::umul_with_overflow:
4324 return implVisitAluOverflow(I, ISD::UMULO);
4325 case Intrinsic::smul_with_overflow:
4326 return implVisitAluOverflow(I, ISD::SMULO);
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004327
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004328 case Intrinsic::prefetch: {
4329 SDValue Ops[4];
4330 Ops[0] = getRoot();
4331 Ops[1] = getValue(I.getOperand(1));
4332 Ops[2] = getValue(I.getOperand(2));
4333 Ops[3] = getValue(I.getOperand(3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004334 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004335 return 0;
4336 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004337
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004338 case Intrinsic::memory_barrier: {
4339 SDValue Ops[6];
4340 Ops[0] = getRoot();
4341 for (int x = 1; x < 6; ++x)
4342 Ops[x] = getValue(I.getOperand(x));
4343
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004344 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004345 return 0;
4346 }
4347 case Intrinsic::atomic_cmp_swap: {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004348 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004349 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00004350 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004351 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4352 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004353 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004354 getValue(I.getOperand(2)),
4355 getValue(I.getOperand(3)),
4356 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004357 setValue(&I, L);
4358 DAG.setRoot(L.getValue(1));
4359 return 0;
4360 }
4361 case Intrinsic::atomic_load_add:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004362 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004363 case Intrinsic::atomic_load_sub:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004364 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004365 case Intrinsic::atomic_load_or:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004366 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004367 case Intrinsic::atomic_load_xor:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004368 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004369 case Intrinsic::atomic_load_and:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004370 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004371 case Intrinsic::atomic_load_nand:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004372 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004373 case Intrinsic::atomic_load_max:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004374 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004375 case Intrinsic::atomic_load_min:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004376 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004377 case Intrinsic::atomic_load_umin:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004378 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004379 case Intrinsic::atomic_load_umax:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004380 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004381 case Intrinsic::atomic_swap:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004382 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004383 }
4384}
4385
4386
4387void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4388 bool IsTailCall,
4389 MachineBasicBlock *LandingPad) {
4390 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4391 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4392 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4393 unsigned BeginLabel = 0, EndLabel = 0;
4394
4395 TargetLowering::ArgListTy Args;
4396 TargetLowering::ArgListEntry Entry;
4397 Args.reserve(CS.arg_size());
4398 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4399 i != e; ++i) {
4400 SDValue ArgNode = getValue(*i);
4401 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4402
4403 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00004404 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4405 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4406 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4407 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4408 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4409 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004410 Entry.Alignment = CS.getParamAlignment(attrInd);
4411 Args.push_back(Entry);
4412 }
4413
4414 if (LandingPad && MMI) {
4415 // Insert a label before the invoke call to mark the try range. This can be
4416 // used to detect deletion of the invoke via the MachineModuleInfo.
4417 BeginLabel = MMI->NextLabelID();
4418 // Both PendingLoads and PendingExports must be flushed here;
4419 // this call might not return.
4420 (void)getRoot();
Dale Johannesen8ad9b432009-02-04 01:17:06 +00004421 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4422 getControlRoot(), BeginLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004423 }
4424
4425 std::pair<SDValue,SDValue> Result =
4426 TLI.LowerCallTo(getRoot(), CS.getType(),
Devang Patel05988662008-09-25 21:00:45 +00004427 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004428 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4429 CS.paramHasAttr(0, Attribute::InReg),
4430 CS.getCallingConv(),
Dan Gohman1937e2f2008-09-16 01:42:28 +00004431 IsTailCall && PerformTailCallOpt,
Dale Johannesen66978ee2009-01-31 02:22:37 +00004432 Callee, Args, DAG, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004433 if (CS.getType() != Type::VoidTy)
4434 setValue(CS.getInstruction(), Result.first);
4435 DAG.setRoot(Result.second);
4436
4437 if (LandingPad && MMI) {
4438 // Insert a label at the end of the invoke call to mark the try range. This
4439 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4440 EndLabel = MMI->NextLabelID();
Dale Johannesen8ad9b432009-02-04 01:17:06 +00004441 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4442 getRoot(), EndLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004443
4444 // Inform MachineModuleInfo of range.
4445 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4446 }
4447}
4448
4449
4450void SelectionDAGLowering::visitCall(CallInst &I) {
4451 const char *RenameFn = 0;
4452 if (Function *F = I.getCalledFunction()) {
4453 if (F->isDeclaration()) {
Dale Johannesen49de9822009-02-05 01:49:45 +00004454 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4455 if (II) {
4456 if (unsigned IID = II->getIntrinsicID(F)) {
4457 RenameFn = visitIntrinsicCall(I, IID);
4458 if (!RenameFn)
4459 return;
4460 }
4461 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004462 if (unsigned IID = F->getIntrinsicID()) {
4463 RenameFn = visitIntrinsicCall(I, IID);
4464 if (!RenameFn)
4465 return;
4466 }
4467 }
4468
4469 // Check for well-known libc/libm calls. If the function is internal, it
4470 // can't be a library call.
4471 unsigned NameLen = F->getNameLen();
Rafael Espindolabb46f522009-01-15 20:18:42 +00004472 if (!F->hasLocalLinkage() && NameLen) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004473 const char *NameStr = F->getNameStart();
4474 if (NameStr[0] == 'c' &&
4475 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4476 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4477 if (I.getNumOperands() == 3 && // Basic sanity checks.
4478 I.getOperand(1)->getType()->isFloatingPoint() &&
4479 I.getType() == I.getOperand(1)->getType() &&
4480 I.getType() == I.getOperand(2)->getType()) {
4481 SDValue LHS = getValue(I.getOperand(1));
4482 SDValue RHS = getValue(I.getOperand(2));
Scott Michelfdc40a02009-02-17 22:15:04 +00004483 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004484 LHS.getValueType(), LHS, RHS));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004485 return;
4486 }
4487 } else if (NameStr[0] == 'f' &&
4488 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4489 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4490 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4491 if (I.getNumOperands() == 2 && // Basic sanity checks.
4492 I.getOperand(1)->getType()->isFloatingPoint() &&
4493 I.getType() == I.getOperand(1)->getType()) {
4494 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004495 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004496 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004497 return;
4498 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004499 } else if (NameStr[0] == 's' &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004500 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4501 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4502 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4503 if (I.getNumOperands() == 2 && // Basic sanity checks.
4504 I.getOperand(1)->getType()->isFloatingPoint() &&
4505 I.getType() == I.getOperand(1)->getType()) {
4506 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004507 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004508 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004509 return;
4510 }
4511 } else if (NameStr[0] == 'c' &&
4512 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4513 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4514 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4515 if (I.getNumOperands() == 2 && // Basic sanity checks.
4516 I.getOperand(1)->getType()->isFloatingPoint() &&
4517 I.getType() == I.getOperand(1)->getType()) {
4518 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004519 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004520 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004521 return;
4522 }
4523 }
4524 }
4525 } else if (isa<InlineAsm>(I.getOperand(0))) {
4526 visitInlineAsm(&I);
4527 return;
4528 }
4529
4530 SDValue Callee;
4531 if (!RenameFn)
4532 Callee = getValue(I.getOperand(0));
4533 else
Bill Wendling056292f2008-09-16 21:48:12 +00004534 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004535
4536 LowerCallTo(&I, Callee, I.isTailCall());
4537}
4538
4539
4540/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004541/// this value and returns the result as a ValueVT value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004542/// Chain/Flag as the input and updates them for the output Chain/Flag.
4543/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004544SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004545 SDValue &Chain,
4546 SDValue *Flag) const {
4547 // Assemble the legal parts into the final values.
4548 SmallVector<SDValue, 4> Values(ValueVTs.size());
4549 SmallVector<SDValue, 8> Parts;
4550 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4551 // Copy the legal parts from the registers.
4552 MVT ValueVT = ValueVTs[Value];
4553 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4554 MVT RegisterVT = RegVTs[Value];
4555
4556 Parts.resize(NumRegs);
4557 for (unsigned i = 0; i != NumRegs; ++i) {
4558 SDValue P;
4559 if (Flag == 0)
Dale Johannesena04b7572009-02-03 23:04:43 +00004560 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004561 else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004562 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004563 *Flag = P.getValue(2);
4564 }
4565 Chain = P.getValue(1);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004566
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004567 // If the source register was virtual and if we know something about it,
4568 // add an assert node.
4569 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4570 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4571 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4572 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4573 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4574 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004575
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004576 unsigned RegSize = RegisterVT.getSizeInBits();
4577 unsigned NumSignBits = LOI.NumSignBits;
4578 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004579
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004580 // FIXME: We capture more information than the dag can represent. For
4581 // now, just use the tightest assertzext/assertsext possible.
4582 bool isSExt = true;
4583 MVT FromVT(MVT::Other);
4584 if (NumSignBits == RegSize)
4585 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4586 else if (NumZeroBits >= RegSize-1)
4587 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4588 else if (NumSignBits > RegSize-8)
4589 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4590 else if (NumZeroBits >= RegSize-9)
4591 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4592 else if (NumSignBits > RegSize-16)
Bill Wendling181b6272008-10-19 20:34:04 +00004593 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004594 else if (NumZeroBits >= RegSize-17)
Bill Wendling181b6272008-10-19 20:34:04 +00004595 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004596 else if (NumSignBits > RegSize-32)
Bill Wendling181b6272008-10-19 20:34:04 +00004597 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004598 else if (NumZeroBits >= RegSize-33)
Bill Wendling181b6272008-10-19 20:34:04 +00004599 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004600
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004601 if (FromVT != MVT::Other) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00004602 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004603 RegisterVT, P, DAG.getValueType(FromVT));
4604
4605 }
4606 }
4607 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004608
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004609 Parts[i] = P;
4610 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004611
Scott Michelfdc40a02009-02-17 22:15:04 +00004612 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00004613 NumRegs, RegisterVT, ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004614 Part += NumRegs;
4615 Parts.clear();
4616 }
4617
Dale Johannesen66978ee2009-01-31 02:22:37 +00004618 return DAG.getNode(ISD::MERGE_VALUES, dl,
Duncan Sandsaaffa052008-12-01 11:41:29 +00004619 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4620 &Values[0], ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004621}
4622
4623/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004624/// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004625/// Chain/Flag as the input and updates them for the output Chain/Flag.
4626/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004627void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004628 SDValue &Chain, SDValue *Flag) const {
4629 // Get the list of the values's legal parts.
4630 unsigned NumRegs = Regs.size();
4631 SmallVector<SDValue, 8> Parts(NumRegs);
4632 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4633 MVT ValueVT = ValueVTs[Value];
4634 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4635 MVT RegisterVT = RegVTs[Value];
4636
Dale Johannesen66978ee2009-01-31 02:22:37 +00004637 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004638 &Parts[Part], NumParts, RegisterVT);
4639 Part += NumParts;
4640 }
4641
4642 // Copy the parts into the registers.
4643 SmallVector<SDValue, 8> Chains(NumRegs);
4644 for (unsigned i = 0; i != NumRegs; ++i) {
4645 SDValue Part;
4646 if (Flag == 0)
Dale Johannesena04b7572009-02-03 23:04:43 +00004647 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004648 else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004649 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004650 *Flag = Part.getValue(1);
4651 }
4652 Chains[i] = Part.getValue(0);
4653 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004654
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004655 if (NumRegs == 1 || Flag)
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004656 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004657 // flagged to it. That is the CopyToReg nodes and the user are considered
4658 // a single scheduling unit. If we create a TokenFactor and return it as
4659 // chain, then the TokenFactor is both a predecessor (operand) of the
4660 // user as well as a successor (the TF operands are flagged to the user).
4661 // c1, f1 = CopyToReg
4662 // c2, f2 = CopyToReg
4663 // c3 = TokenFactor c1, c2
4664 // ...
4665 // = op c3, ..., f2
4666 Chain = Chains[NumRegs-1];
4667 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00004668 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004669}
4670
4671/// AddInlineAsmOperands - Add this value to the specified inlineasm node
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004672/// operand list. This adds the code marker and includes the number of
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004673/// values added into it.
Evan Cheng697cbbf2009-03-20 18:03:34 +00004674void RegsForValue::AddInlineAsmOperands(unsigned Code,
4675 bool HasMatching,unsigned MatchingIdx,
4676 SelectionDAG &DAG,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004677 std::vector<SDValue> &Ops) const {
4678 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Evan Cheng697cbbf2009-03-20 18:03:34 +00004679 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
4680 unsigned Flag = Code | (Regs.size() << 3);
4681 if (HasMatching)
4682 Flag |= 0x80000000 | (MatchingIdx << 16);
4683 Ops.push_back(DAG.getTargetConstant(Flag, IntPtrTy));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004684 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4685 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4686 MVT RegisterVT = RegVTs[Value];
Chris Lattner58f15c42008-10-17 16:21:11 +00004687 for (unsigned i = 0; i != NumRegs; ++i) {
4688 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004689 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner58f15c42008-10-17 16:21:11 +00004690 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004691 }
4692}
4693
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004694/// isAllocatableRegister - If the specified register is safe to allocate,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004695/// i.e. it isn't a stack pointer or some other special register, return the
4696/// register class for the register. Otherwise, return null.
4697static const TargetRegisterClass *
4698isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4699 const TargetLowering &TLI,
4700 const TargetRegisterInfo *TRI) {
4701 MVT FoundVT = MVT::Other;
4702 const TargetRegisterClass *FoundRC = 0;
4703 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4704 E = TRI->regclass_end(); RCI != E; ++RCI) {
4705 MVT ThisVT = MVT::Other;
4706
4707 const TargetRegisterClass *RC = *RCI;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004708 // If none of the the value types for this register class are valid, we
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004709 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4710 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4711 I != E; ++I) {
4712 if (TLI.isTypeLegal(*I)) {
4713 // If we have already found this register in a different register class,
4714 // choose the one with the largest VT specified. For example, on
4715 // PowerPC, we favor f64 register classes over f32.
4716 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4717 ThisVT = *I;
4718 break;
4719 }
4720 }
4721 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004722
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004723 if (ThisVT == MVT::Other) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004724
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004725 // NOTE: This isn't ideal. In particular, this might allocate the
4726 // frame pointer in functions that need it (due to them not being taken
4727 // out of allocation, because a variable sized allocation hasn't been seen
4728 // yet). This is a slight code pessimization, but should still work.
4729 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4730 E = RC->allocation_order_end(MF); I != E; ++I)
4731 if (*I == Reg) {
4732 // We found a matching register class. Keep looking at others in case
4733 // we find one with larger registers that this physreg is also in.
4734 FoundRC = RC;
4735 FoundVT = ThisVT;
4736 break;
4737 }
4738 }
4739 return FoundRC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004740}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004741
4742
4743namespace llvm {
4744/// AsmOperandInfo - This contains information for each constraint that we are
4745/// lowering.
Cedric Venetaff9c272009-02-14 16:06:42 +00004746class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
Daniel Dunbarc0c3b9a2008-09-10 04:16:29 +00004747 public TargetLowering::AsmOperandInfo {
Cedric Venetaff9c272009-02-14 16:06:42 +00004748public:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004749 /// CallOperand - If this is the result output operand or a clobber
4750 /// this is null, otherwise it is the incoming operand to the CallInst.
4751 /// This gets modified as the asm is processed.
4752 SDValue CallOperand;
4753
4754 /// AssignedRegs - If this is a register or register class operand, this
4755 /// contains the set of register corresponding to the operand.
4756 RegsForValue AssignedRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004757
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004758 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4759 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4760 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004761
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004762 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4763 /// busy in OutputRegs/InputRegs.
4764 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004765 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004766 std::set<unsigned> &InputRegs,
4767 const TargetRegisterInfo &TRI) const {
4768 if (isOutReg) {
4769 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4770 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4771 }
4772 if (isInReg) {
4773 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4774 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4775 }
4776 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004777
Chris Lattner81249c92008-10-17 17:05:25 +00004778 /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4779 /// corresponds to. If there is no Value* for this operand, it returns
4780 /// MVT::Other.
4781 MVT getCallOperandValMVT(const TargetLowering &TLI,
4782 const TargetData *TD) const {
4783 if (CallOperandVal == 0) return MVT::Other;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004784
Chris Lattner81249c92008-10-17 17:05:25 +00004785 if (isa<BasicBlock>(CallOperandVal))
4786 return TLI.getPointerTy();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004787
Chris Lattner81249c92008-10-17 17:05:25 +00004788 const llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004789
Chris Lattner81249c92008-10-17 17:05:25 +00004790 // If this is an indirect operand, the operand is a pointer to the
4791 // accessed type.
4792 if (isIndirect)
4793 OpTy = cast<PointerType>(OpTy)->getElementType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004794
Chris Lattner81249c92008-10-17 17:05:25 +00004795 // If OpTy is not a single value, it may be a struct/union that we
4796 // can tile with integers.
4797 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4798 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4799 switch (BitSize) {
4800 default: break;
4801 case 1:
4802 case 8:
4803 case 16:
4804 case 32:
4805 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00004806 case 128:
Chris Lattner81249c92008-10-17 17:05:25 +00004807 OpTy = IntegerType::get(BitSize);
4808 break;
4809 }
4810 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004811
Chris Lattner81249c92008-10-17 17:05:25 +00004812 return TLI.getValueType(OpTy, true);
4813 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004814
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004815private:
4816 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4817 /// specified set.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004818 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004819 const TargetRegisterInfo &TRI) {
4820 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4821 Regs.insert(Reg);
4822 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4823 for (; *Aliases; ++Aliases)
4824 Regs.insert(*Aliases);
4825 }
4826};
4827} // end llvm namespace.
4828
4829
4830/// GetRegistersForValue - Assign registers (virtual or physical) for the
4831/// specified operand. We prefer to assign virtual registers, to allow the
4832/// register allocator handle the assignment process. However, if the asm uses
4833/// features that we can't model on machineinstrs, we have SDISel do the
4834/// allocation. This produces generally horrible, but correct, code.
4835///
4836/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004837/// Input and OutputRegs are the set of already allocated physical registers.
4838///
4839void SelectionDAGLowering::
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004840GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004841 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004842 std::set<unsigned> &InputRegs) {
4843 // Compute whether this value requires an input register, an output register,
4844 // or both.
4845 bool isOutReg = false;
4846 bool isInReg = false;
4847 switch (OpInfo.Type) {
4848 case InlineAsm::isOutput:
4849 isOutReg = true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004850
4851 // If there is an input constraint that matches this, we need to reserve
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004852 // the input register so no other inputs allocate to it.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004853 isInReg = OpInfo.hasMatchingInput();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004854 break;
4855 case InlineAsm::isInput:
4856 isInReg = true;
4857 isOutReg = false;
4858 break;
4859 case InlineAsm::isClobber:
4860 isOutReg = true;
4861 isInReg = true;
4862 break;
4863 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004864
4865
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004866 MachineFunction &MF = DAG.getMachineFunction();
4867 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004868
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004869 // If this is a constraint for a single physreg, or a constraint for a
4870 // register class, find it.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004871 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004872 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4873 OpInfo.ConstraintVT);
4874
4875 unsigned NumRegs = 1;
Chris Lattner01426e12008-10-21 00:45:36 +00004876 if (OpInfo.ConstraintVT != MVT::Other) {
4877 // If this is a FP input in an integer register (or visa versa) insert a bit
4878 // cast of the input value. More generally, handle any case where the input
4879 // value disagrees with the register class we plan to stick this in.
4880 if (OpInfo.Type == InlineAsm::isInput &&
4881 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4882 // Try to convert to the first MVT that the reg class contains. If the
4883 // types are identical size, use a bitcast to convert (e.g. two differing
4884 // vector types).
4885 MVT RegVT = *PhysReg.second->vt_begin();
4886 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00004887 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004888 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00004889 OpInfo.ConstraintVT = RegVT;
4890 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4891 // If the input is a FP value and we want it in FP registers, do a
4892 // bitcast to the corresponding integer type. This turns an f64 value
4893 // into i64, which can be passed with two i32 values on a 32-bit
4894 // machine.
4895 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
Dale Johannesen66978ee2009-01-31 02:22:37 +00004896 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004897 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00004898 OpInfo.ConstraintVT = RegVT;
4899 }
4900 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004901
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004902 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00004903 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004904
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004905 MVT RegVT;
4906 MVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004907
4908 // If this is a constraint for a specific physical register, like {r17},
4909 // assign it now.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004910 if (unsigned AssignedReg = PhysReg.first) {
4911 const TargetRegisterClass *RC = PhysReg.second;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004912 if (OpInfo.ConstraintVT == MVT::Other)
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004913 ValueVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004914
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004915 // Get the actual register value type. This is important, because the user
4916 // may have asked for (e.g.) the AX register in i32 type. We need to
4917 // remember that AX is actually i16 to get the right extension.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004918 RegVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004919
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004920 // This is a explicit reference to a physical register.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004921 Regs.push_back(AssignedReg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004922
4923 // If this is an expanded reference, add the rest of the regs to Regs.
4924 if (NumRegs != 1) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004925 TargetRegisterClass::iterator I = RC->begin();
4926 for (; *I != AssignedReg; ++I)
4927 assert(I != RC->end() && "Didn't find reg!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004928
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004929 // Already added the first reg.
4930 --NumRegs; ++I;
4931 for (; NumRegs; --NumRegs, ++I) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004932 assert(I != RC->end() && "Ran out of registers to allocate!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004933 Regs.push_back(*I);
4934 }
4935 }
4936 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4937 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4938 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4939 return;
4940 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004941
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004942 // Otherwise, if this was a reference to an LLVM register class, create vregs
4943 // for this reference.
Chris Lattnerb3b44842009-03-24 15:25:07 +00004944 if (const TargetRegisterClass *RC = PhysReg.second) {
4945 RegVT = *RC->vt_begin();
Evan Chengfb112882009-03-23 08:01:15 +00004946 if (OpInfo.ConstraintVT == MVT::Other)
4947 ValueVT = RegVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004948
Evan Chengfb112882009-03-23 08:01:15 +00004949 // Create the appropriate number of virtual registers.
4950 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4951 for (; NumRegs; --NumRegs)
Chris Lattnerb3b44842009-03-24 15:25:07 +00004952 Regs.push_back(RegInfo.createVirtualRegister(RC));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004953
Evan Chengfb112882009-03-23 08:01:15 +00004954 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4955 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004956 }
Chris Lattnerfc9d1612009-03-24 15:22:11 +00004957
4958 // This is a reference to a register class that doesn't directly correspond
4959 // to an LLVM register class. Allocate NumRegs consecutive, available,
4960 // registers from the class.
4961 std::vector<unsigned> RegClassRegs
4962 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4963 OpInfo.ConstraintVT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004964
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004965 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4966 unsigned NumAllocated = 0;
4967 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4968 unsigned Reg = RegClassRegs[i];
4969 // See if this register is available.
4970 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4971 (isInReg && InputRegs.count(Reg))) { // Already used.
4972 // Make sure we find consecutive registers.
4973 NumAllocated = 0;
4974 continue;
4975 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004976
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004977 // Check to see if this register is allocatable (i.e. don't give out the
4978 // stack pointer).
Chris Lattnerfc9d1612009-03-24 15:22:11 +00004979 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4980 if (!RC) { // Couldn't allocate this register.
4981 // Reset NumAllocated to make sure we return consecutive registers.
4982 NumAllocated = 0;
4983 continue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004984 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004985
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004986 // Okay, this register is good, we can use it.
4987 ++NumAllocated;
4988
4989 // If we allocated enough consecutive registers, succeed.
4990 if (NumAllocated == NumRegs) {
4991 unsigned RegStart = (i-NumAllocated)+1;
4992 unsigned RegEnd = i+1;
4993 // Mark all of the allocated registers used.
4994 for (unsigned i = RegStart; i != RegEnd; ++i)
4995 Regs.push_back(RegClassRegs[i]);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004996
4997 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004998 OpInfo.ConstraintVT);
4999 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5000 return;
5001 }
5002 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005003
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005004 // Otherwise, we couldn't allocate enough registers for this.
5005}
5006
Evan Chengda43bcf2008-09-24 00:05:32 +00005007/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5008/// processed uses a memory 'm' constraint.
5009static bool
5010hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
Dan Gohmane9530ec2009-01-15 16:58:17 +00005011 const TargetLowering &TLI) {
Evan Chengda43bcf2008-09-24 00:05:32 +00005012 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5013 InlineAsm::ConstraintInfo &CI = CInfos[i];
5014 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5015 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5016 if (CType == TargetLowering::C_Memory)
5017 return true;
5018 }
5019 }
5020
5021 return false;
5022}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005023
5024/// visitInlineAsm - Handle a call to an InlineAsm object.
5025///
5026void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
5027 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5028
5029 /// ConstraintOperands - Information about all of the constraints.
5030 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005031
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005032 SDValue Chain = getRoot();
5033 SDValue Flag;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005034
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005035 std::set<unsigned> OutputRegs, InputRegs;
5036
5037 // Do a prepass over the constraints, canonicalizing them, and building up the
5038 // ConstraintOperands list.
5039 std::vector<InlineAsm::ConstraintInfo>
5040 ConstraintInfos = IA->ParseConstraints();
5041
Evan Chengda43bcf2008-09-24 00:05:32 +00005042 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005043
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005044 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5045 unsigned ResNo = 0; // ResNo - The result number of the next output.
5046 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5047 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5048 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005049
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005050 MVT OpVT = MVT::Other;
5051
5052 // Compute the value type for each operand.
5053 switch (OpInfo.Type) {
5054 case InlineAsm::isOutput:
5055 // Indirect outputs just consume an argument.
5056 if (OpInfo.isIndirect) {
5057 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5058 break;
5059 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005060
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005061 // The return value of the call is this value. As such, there is no
5062 // corresponding argument.
5063 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5064 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5065 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5066 } else {
5067 assert(ResNo == 0 && "Asm only has one result!");
5068 OpVT = TLI.getValueType(CS.getType());
5069 }
5070 ++ResNo;
5071 break;
5072 case InlineAsm::isInput:
5073 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5074 break;
5075 case InlineAsm::isClobber:
5076 // Nothing to do.
5077 break;
5078 }
5079
5080 // If this is an input or an indirect output, process the call argument.
5081 // BasicBlocks are labels, currently appearing only in asm's.
5082 if (OpInfo.CallOperandVal) {
Chris Lattner81249c92008-10-17 17:05:25 +00005083 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005084 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00005085 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005086 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005087 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005088
Chris Lattner81249c92008-10-17 17:05:25 +00005089 OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005090 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005091
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005092 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005093 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005094
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005095 // Second pass over the constraints: compute which constraint option to use
5096 // and assign registers to constraints that want a specific physreg.
5097 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5098 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005099
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005100 // If this is an output operand with a matching input operand, look up the
Evan Cheng09dc9c02008-12-16 18:21:39 +00005101 // matching input. If their types mismatch, e.g. one is an integer, the
5102 // other is floating point, or their sizes are different, flag it as an
5103 // error.
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005104 if (OpInfo.hasMatchingInput()) {
5105 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5106 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Evan Cheng09dc9c02008-12-16 18:21:39 +00005107 if ((OpInfo.ConstraintVT.isInteger() !=
5108 Input.ConstraintVT.isInteger()) ||
5109 (OpInfo.ConstraintVT.getSizeInBits() !=
5110 Input.ConstraintVT.getSizeInBits())) {
5111 cerr << "Unsupported asm: input constraint with a matching output "
5112 << "constraint of incompatible type!\n";
5113 exit(1);
5114 }
5115 Input.ConstraintVT = OpInfo.ConstraintVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005116 }
5117 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005118
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005119 // Compute the constraint code and ConstraintType to use.
Evan Chengda43bcf2008-09-24 00:05:32 +00005120 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005121
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005122 // If this is a memory input, and if the operand is not indirect, do what we
5123 // need to to provide an address for the memory input.
5124 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5125 !OpInfo.isIndirect) {
5126 assert(OpInfo.Type == InlineAsm::isInput &&
5127 "Can only indirectify direct input operands!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005128
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005129 // Memory operands really want the address of the value. If we don't have
5130 // an indirect input, put it in the constpool if we can, otherwise spill
5131 // it to a stack slot.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005132
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005133 // If the operand is a float, integer, or vector constant, spill to a
5134 // constant pool entry to get its address.
5135 Value *OpVal = OpInfo.CallOperandVal;
5136 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5137 isa<ConstantVector>(OpVal)) {
5138 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5139 TLI.getPointerTy());
5140 } else {
5141 // Otherwise, create a stack slot and emit a store to it before the
5142 // asm.
5143 const Type *Ty = OpVal->getType();
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005144 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005145 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5146 MachineFunction &MF = DAG.getMachineFunction();
5147 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
5148 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Dale Johannesen66978ee2009-01-31 02:22:37 +00005149 Chain = DAG.getStore(Chain, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005150 OpInfo.CallOperand, StackSlot, NULL, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005151 OpInfo.CallOperand = StackSlot;
5152 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005153
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005154 // There is no longer a Value* corresponding to this operand.
5155 OpInfo.CallOperandVal = 0;
5156 // It is now an indirect operand.
5157 OpInfo.isIndirect = true;
5158 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005159
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005160 // If this constraint is for a specific register, allocate it before
5161 // anything else.
5162 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005163 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005164 }
5165 ConstraintInfos.clear();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005166
5167
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005168 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00005169 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005170 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5171 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005172
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005173 // C_Register operands have already been allocated, Other/Memory don't need
5174 // to be.
5175 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005176 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005177 }
5178
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005179 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5180 std::vector<SDValue> AsmNodeOperands;
5181 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5182 AsmNodeOperands.push_back(
Bill Wendling056292f2008-09-16 21:48:12 +00005183 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005184
5185
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005186 // Loop over all of the inputs, copying the operand values into the
5187 // appropriate registers and processing the output regs.
5188 RegsForValue RetValRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005189
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005190 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5191 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005192
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005193 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5194 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5195
5196 switch (OpInfo.Type) {
5197 case InlineAsm::isOutput: {
5198 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5199 OpInfo.ConstraintType != TargetLowering::C_Register) {
5200 // Memory output, or 'other' output (e.g. 'X' constraint).
5201 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5202
5203 // Add information to the INLINEASM node to know about this output.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005204 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5205 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005206 TLI.getPointerTy()));
5207 AsmNodeOperands.push_back(OpInfo.CallOperand);
5208 break;
5209 }
5210
5211 // Otherwise, this is a register or register class output.
5212
5213 // Copy the output from the appropriate register. Find a register that
5214 // we can use.
5215 if (OpInfo.AssignedRegs.Regs.empty()) {
5216 cerr << "Couldn't allocate output reg for constraint '"
5217 << OpInfo.ConstraintCode << "'!\n";
5218 exit(1);
5219 }
5220
5221 // If this is an indirect operand, store through the pointer after the
5222 // asm.
5223 if (OpInfo.isIndirect) {
5224 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5225 OpInfo.CallOperandVal));
5226 } else {
5227 // This is the result value of the call.
5228 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5229 // Concatenate this output onto the outputs list.
5230 RetValRegs.append(OpInfo.AssignedRegs);
5231 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005232
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005233 // Add information to the INLINEASM node to know that this register is
5234 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00005235 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5236 6 /* EARLYCLOBBER REGDEF */ :
5237 2 /* REGDEF */ ,
Evan Chengfb112882009-03-23 08:01:15 +00005238 false,
5239 0,
Dale Johannesen913d3df2008-09-12 17:49:03 +00005240 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005241 break;
5242 }
5243 case InlineAsm::isInput: {
5244 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005245
Chris Lattner6bdcda32008-10-17 16:47:46 +00005246 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005247 // If this is required to match an output register we have already set,
5248 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00005249 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005250
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005251 // Scan until we find the definition we already emitted of this operand.
5252 // When we find it, create a RegsForValue operand.
5253 unsigned CurOp = 2; // The first operand.
5254 for (; OperandNo; --OperandNo) {
5255 // Advance to the next operand.
Evan Cheng697cbbf2009-03-20 18:03:34 +00005256 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005257 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005258 assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5259 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5260 (OpFlag & 7) == 4 /*MEM*/) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005261 "Skipped past definitions?");
Evan Cheng697cbbf2009-03-20 18:03:34 +00005262 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005263 }
5264
Evan Cheng697cbbf2009-03-20 18:03:34 +00005265 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005266 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005267 if ((OpFlag & 7) == 2 /*REGDEF*/
5268 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5269 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005270 RegsForValue MatchedRegs;
5271 MatchedRegs.TLI = &TLI;
5272 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
Evan Chengfb112882009-03-23 08:01:15 +00005273 MVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5274 MatchedRegs.RegVTs.push_back(RegVT);
5275 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005276 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
Evan Chengfb112882009-03-23 08:01:15 +00005277 i != e; ++i)
5278 MatchedRegs.Regs.
5279 push_back(RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005280
5281 // Use the produced MatchedRegs object to
Dale Johannesen66978ee2009-01-31 02:22:37 +00005282 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5283 Chain, &Flag);
Evan Chengfb112882009-03-23 08:01:15 +00005284 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5285 true, OpInfo.getMatchedOperand(),
Evan Cheng697cbbf2009-03-20 18:03:34 +00005286 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005287 break;
5288 } else {
Evan Cheng697cbbf2009-03-20 18:03:34 +00005289 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5290 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5291 "Unexpected number of operands");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005292 // Add information to the INLINEASM node to know about this input.
Evan Chengfb112882009-03-23 08:01:15 +00005293 // See InlineAsm.h isUseOperandTiedToDef.
5294 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
Evan Cheng697cbbf2009-03-20 18:03:34 +00005295 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005296 TLI.getPointerTy()));
5297 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5298 break;
5299 }
5300 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005301
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005302 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005303 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005304 "Don't know how to handle indirect other inputs yet!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005305
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005306 std::vector<SDValue> Ops;
5307 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Chengda43bcf2008-09-24 00:05:32 +00005308 hasMemory, Ops, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005309 if (Ops.empty()) {
5310 cerr << "Invalid operand for inline asm constraint '"
5311 << OpInfo.ConstraintCode << "'!\n";
5312 exit(1);
5313 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005314
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005315 // Add information to the INLINEASM node to know about this input.
5316 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005317 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005318 TLI.getPointerTy()));
5319 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5320 break;
5321 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5322 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5323 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5324 "Memory operands expect pointer values");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005325
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005326 // Add information to the INLINEASM node to know about this input.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005327 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5328 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005329 TLI.getPointerTy()));
5330 AsmNodeOperands.push_back(InOperandVal);
5331 break;
5332 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005333
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005334 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5335 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5336 "Unknown constraint type!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005337 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005338 "Don't know how to handle indirect register inputs yet!");
5339
5340 // Copy the input into the appropriate registers.
Evan Chengaa765b82008-09-25 00:14:04 +00005341 if (OpInfo.AssignedRegs.Regs.empty()) {
5342 cerr << "Couldn't allocate output reg for constraint '"
5343 << OpInfo.ConstraintCode << "'!\n";
5344 exit(1);
5345 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005346
Dale Johannesen66978ee2009-01-31 02:22:37 +00005347 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5348 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005349
Evan Cheng697cbbf2009-03-20 18:03:34 +00005350 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
Dale Johannesen86b49f82008-09-24 01:07:17 +00005351 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005352 break;
5353 }
5354 case InlineAsm::isClobber: {
5355 // Add the clobbered value to the operand list, so that the register
5356 // allocator is aware that the physreg got clobbered.
5357 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesen91aac102008-09-17 21:13:11 +00005358 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
Evan Cheng697cbbf2009-03-20 18:03:34 +00005359 false, 0, DAG,AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005360 break;
5361 }
5362 }
5363 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005364
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005365 // Finish up input operands.
5366 AsmNodeOperands[0] = Chain;
5367 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005368
Dale Johannesen66978ee2009-01-31 02:22:37 +00005369 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005370 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
5371 &AsmNodeOperands[0], AsmNodeOperands.size());
5372 Flag = Chain.getValue(1);
5373
5374 // If this asm returns a register value, copy the result from that register
5375 // and set it as the value of the call.
5376 if (!RetValRegs.Regs.empty()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00005377 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00005378 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005379
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005380 // FIXME: Why don't we do this for inline asms with MRVs?
5381 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5382 MVT ResultType = TLI.getValueType(CS.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005383
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005384 // If any of the results of the inline asm is a vector, it may have the
5385 // wrong width/num elts. This can happen for register classes that can
5386 // contain multiple different value types. The preg or vreg allocated may
5387 // not have the same VT as was expected. Convert it to the right type
5388 // with bit_convert.
5389 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005390 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005391 ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005392
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005393 } else if (ResultType != Val.getValueType() &&
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005394 ResultType.isInteger() && Val.getValueType().isInteger()) {
5395 // If a result value was tied to an input value, the computed result may
5396 // have a wider width than the expected result. Extract the relevant
5397 // portion.
Dale Johannesen66978ee2009-01-31 02:22:37 +00005398 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005399 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005400
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005401 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00005402 }
Dan Gohman95915732008-10-18 01:03:45 +00005403
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005404 setValue(CS.getInstruction(), Val);
5405 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005406
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005407 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005408
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005409 // Process indirect outputs, first output all of the flagged copies out of
5410 // physregs.
5411 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5412 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5413 Value *Ptr = IndirectStoresToEmit[i].second;
Dale Johannesen66978ee2009-01-31 02:22:37 +00005414 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5415 Chain, &Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005416 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5417 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005418
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005419 // Emit the non-flagged stores from the physregs.
5420 SmallVector<SDValue, 8> OutChains;
5421 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00005422 OutChains.push_back(DAG.getStore(Chain, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005423 StoresToEmit[i].first,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005424 getValue(StoresToEmit[i].second),
5425 StoresToEmit[i].second, 0));
5426 if (!OutChains.empty())
Dale Johannesen66978ee2009-01-31 02:22:37 +00005427 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005428 &OutChains[0], OutChains.size());
5429 DAG.setRoot(Chain);
5430}
5431
5432
5433void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5434 SDValue Src = getValue(I.getOperand(0));
5435
Chris Lattner0b18e592009-03-17 19:36:00 +00005436 // Scale up by the type size in the original i32 type width. Various
5437 // mid-level optimizers may make assumptions about demanded bits etc from the
5438 // i32-ness of the optimizer: we do not want to promote to i64 and then
5439 // multiply on 64-bit targets.
5440 // FIXME: Malloc inst should go away: PR715.
5441 uint64_t ElementSize = TD->getTypePaddedSize(I.getType()->getElementType());
5442 if (ElementSize != 1)
5443 Src = DAG.getNode(ISD::MUL, getCurDebugLoc(), Src.getValueType(),
5444 Src, DAG.getConstant(ElementSize, Src.getValueType()));
5445
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005446 MVT IntPtr = TLI.getPointerTy();
5447
5448 if (IntPtr.bitsLT(Src.getValueType()))
Dale Johannesen66978ee2009-01-31 02:22:37 +00005449 Src = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), IntPtr, Src);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005450 else if (IntPtr.bitsGT(Src.getValueType()))
Dale Johannesen66978ee2009-01-31 02:22:37 +00005451 Src = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), IntPtr, Src);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005452
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005453 TargetLowering::ArgListTy Args;
5454 TargetLowering::ArgListEntry Entry;
5455 Entry.Node = Src;
5456 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5457 Args.push_back(Entry);
5458
5459 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005460 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005461 CallingConv::C, PerformTailCallOpt,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005462 DAG.getExternalSymbol("malloc", IntPtr),
Dale Johannesen66978ee2009-01-31 02:22:37 +00005463 Args, DAG, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005464 setValue(&I, Result.first); // Pointers always fit in registers
5465 DAG.setRoot(Result.second);
5466}
5467
5468void SelectionDAGLowering::visitFree(FreeInst &I) {
5469 TargetLowering::ArgListTy Args;
5470 TargetLowering::ArgListEntry Entry;
5471 Entry.Node = getValue(I.getOperand(0));
5472 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5473 Args.push_back(Entry);
5474 MVT IntPtr = TLI.getPointerTy();
5475 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005476 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
Dan Gohman1937e2f2008-09-16 01:42:28 +00005477 CallingConv::C, PerformTailCallOpt,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005478 DAG.getExternalSymbol("free", IntPtr), Args, DAG,
Dale Johannesen66978ee2009-01-31 02:22:37 +00005479 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005480 DAG.setRoot(Result.second);
5481}
5482
5483void SelectionDAGLowering::visitVAStart(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005484 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005485 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005486 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005487 DAG.getSrcValue(I.getOperand(1))));
5488}
5489
5490void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Dale Johannesena04b7572009-02-03 23:04:43 +00005491 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5492 getRoot(), getValue(I.getOperand(0)),
5493 DAG.getSrcValue(I.getOperand(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005494 setValue(&I, V);
5495 DAG.setRoot(V.getValue(1));
5496}
5497
5498void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005499 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005500 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005501 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005502 DAG.getSrcValue(I.getOperand(1))));
5503}
5504
5505void SelectionDAGLowering::visitVACopy(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005506 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005507 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005508 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005509 getValue(I.getOperand(2)),
5510 DAG.getSrcValue(I.getOperand(1)),
5511 DAG.getSrcValue(I.getOperand(2))));
5512}
5513
5514/// TargetLowering::LowerArguments - This is the default LowerArguments
5515/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005516/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005517/// integrated into SDISel.
5518void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005519 SmallVectorImpl<SDValue> &ArgValues,
5520 DebugLoc dl) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005521 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5522 SmallVector<SDValue, 3+16> Ops;
5523 Ops.push_back(DAG.getRoot());
5524 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5525 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5526
5527 // Add one result value for each formal argument.
5528 SmallVector<MVT, 16> RetVals;
5529 unsigned j = 1;
5530 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5531 I != E; ++I, ++j) {
5532 SmallVector<MVT, 4> ValueVTs;
5533 ComputeValueVTs(*this, I->getType(), ValueVTs);
5534 for (unsigned Value = 0, NumValues = ValueVTs.size();
5535 Value != NumValues; ++Value) {
5536 MVT VT = ValueVTs[Value];
5537 const Type *ArgTy = VT.getTypeForMVT();
5538 ISD::ArgFlagsTy Flags;
5539 unsigned OriginalAlignment =
5540 getTargetData()->getABITypeAlignment(ArgTy);
5541
Devang Patel05988662008-09-25 21:00:45 +00005542 if (F.paramHasAttr(j, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005543 Flags.setZExt();
Devang Patel05988662008-09-25 21:00:45 +00005544 if (F.paramHasAttr(j, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005545 Flags.setSExt();
Devang Patel05988662008-09-25 21:00:45 +00005546 if (F.paramHasAttr(j, Attribute::InReg))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005547 Flags.setInReg();
Devang Patel05988662008-09-25 21:00:45 +00005548 if (F.paramHasAttr(j, Attribute::StructRet))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005549 Flags.setSRet();
Devang Patel05988662008-09-25 21:00:45 +00005550 if (F.paramHasAttr(j, Attribute::ByVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005551 Flags.setByVal();
5552 const PointerType *Ty = cast<PointerType>(I->getType());
5553 const Type *ElementTy = Ty->getElementType();
5554 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005555 unsigned FrameSize = getTargetData()->getTypePaddedSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005556 // For ByVal, alignment should be passed from FE. BE will guess if
5557 // this info is not there but there are cases it cannot get right.
5558 if (F.getParamAlignment(j))
5559 FrameAlign = F.getParamAlignment(j);
5560 Flags.setByValAlign(FrameAlign);
5561 Flags.setByValSize(FrameSize);
5562 }
Devang Patel05988662008-09-25 21:00:45 +00005563 if (F.paramHasAttr(j, Attribute::Nest))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005564 Flags.setNest();
5565 Flags.setOrigAlign(OriginalAlignment);
5566
5567 MVT RegisterVT = getRegisterType(VT);
5568 unsigned NumRegs = getNumRegisters(VT);
5569 for (unsigned i = 0; i != NumRegs; ++i) {
5570 RetVals.push_back(RegisterVT);
5571 ISD::ArgFlagsTy MyFlags = Flags;
5572 if (NumRegs > 1 && i == 0)
5573 MyFlags.setSplit();
5574 // if it isn't first piece, alignment must be 1
5575 else if (i > 0)
5576 MyFlags.setOrigAlign(1);
5577 Ops.push_back(DAG.getArgFlags(MyFlags));
5578 }
5579 }
5580 }
5581
5582 RetVals.push_back(MVT::Other);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005583
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005584 // Create the node.
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005585 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005586 DAG.getVTList(&RetVals[0], RetVals.size()),
5587 &Ops[0], Ops.size()).getNode();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005588
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005589 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5590 // allows exposing the loads that may be part of the argument access to the
5591 // first DAGCombiner pass.
5592 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005593
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005594 // The number of results should match up, except that the lowered one may have
5595 // an extra flag result.
5596 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5597 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5598 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5599 && "Lowering produced unexpected number of results!");
5600
5601 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5602 if (Result != TmpRes.getNode() && Result->use_empty()) {
5603 HandleSDNode Dummy(DAG.getRoot());
5604 DAG.RemoveDeadNode(Result);
5605 }
5606
5607 Result = TmpRes.getNode();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005608
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005609 unsigned NumArgRegs = Result->getNumValues() - 1;
5610 DAG.setRoot(SDValue(Result, NumArgRegs));
5611
5612 // Set up the return result vector.
5613 unsigned i = 0;
5614 unsigned Idx = 1;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005615 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005616 ++I, ++Idx) {
5617 SmallVector<MVT, 4> ValueVTs;
5618 ComputeValueVTs(*this, I->getType(), ValueVTs);
5619 for (unsigned Value = 0, NumValues = ValueVTs.size();
5620 Value != NumValues; ++Value) {
5621 MVT VT = ValueVTs[Value];
5622 MVT PartVT = getRegisterType(VT);
5623
5624 unsigned NumParts = getNumRegisters(VT);
5625 SmallVector<SDValue, 4> Parts(NumParts);
5626 for (unsigned j = 0; j != NumParts; ++j)
5627 Parts[j] = SDValue(Result, i++);
5628
5629 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Devang Patel05988662008-09-25 21:00:45 +00005630 if (F.paramHasAttr(Idx, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005631 AssertOp = ISD::AssertSext;
Devang Patel05988662008-09-25 21:00:45 +00005632 else if (F.paramHasAttr(Idx, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005633 AssertOp = ISD::AssertZext;
5634
Dale Johannesen66978ee2009-01-31 02:22:37 +00005635 ArgValues.push_back(getCopyFromParts(DAG, dl, &Parts[0], NumParts,
5636 PartVT, VT, AssertOp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005637 }
5638 }
5639 assert(i == NumArgRegs && "Argument register count mismatch!");
5640}
5641
5642
5643/// TargetLowering::LowerCallTo - This is the default LowerCallTo
5644/// implementation, which just inserts an ISD::CALL node, which is later custom
5645/// lowered by the target to something concrete. FIXME: When all targets are
5646/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5647std::pair<SDValue, SDValue>
5648TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5649 bool RetSExt, bool RetZExt, bool isVarArg,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005650 bool isInreg,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005651 unsigned CallingConv, bool isTailCall,
5652 SDValue Callee,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005653 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
Dan Gohman1937e2f2008-09-16 01:42:28 +00005654 assert((!isTailCall || PerformTailCallOpt) &&
5655 "isTailCall set when tail-call optimizations are disabled!");
5656
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005657 SmallVector<SDValue, 32> Ops;
5658 Ops.push_back(Chain); // Op#0 - Chain
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005659 Ops.push_back(Callee);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005660
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005661 // Handle all of the outgoing arguments.
5662 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5663 SmallVector<MVT, 4> ValueVTs;
5664 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5665 for (unsigned Value = 0, NumValues = ValueVTs.size();
5666 Value != NumValues; ++Value) {
5667 MVT VT = ValueVTs[Value];
5668 const Type *ArgTy = VT.getTypeForMVT();
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005669 SDValue Op = SDValue(Args[i].Node.getNode(),
5670 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005671 ISD::ArgFlagsTy Flags;
5672 unsigned OriginalAlignment =
5673 getTargetData()->getABITypeAlignment(ArgTy);
5674
5675 if (Args[i].isZExt)
5676 Flags.setZExt();
5677 if (Args[i].isSExt)
5678 Flags.setSExt();
5679 if (Args[i].isInReg)
5680 Flags.setInReg();
5681 if (Args[i].isSRet)
5682 Flags.setSRet();
5683 if (Args[i].isByVal) {
5684 Flags.setByVal();
5685 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5686 const Type *ElementTy = Ty->getElementType();
5687 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sandsceb4d1a2009-01-12 20:38:59 +00005688 unsigned FrameSize = getTargetData()->getTypePaddedSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005689 // For ByVal, alignment should come from FE. BE will guess if this
5690 // info is not there but there are cases it cannot get right.
5691 if (Args[i].Alignment)
5692 FrameAlign = Args[i].Alignment;
5693 Flags.setByValAlign(FrameAlign);
5694 Flags.setByValSize(FrameSize);
5695 }
5696 if (Args[i].isNest)
5697 Flags.setNest();
5698 Flags.setOrigAlign(OriginalAlignment);
5699
5700 MVT PartVT = getRegisterType(VT);
5701 unsigned NumParts = getNumRegisters(VT);
5702 SmallVector<SDValue, 4> Parts(NumParts);
5703 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5704
5705 if (Args[i].isSExt)
5706 ExtendKind = ISD::SIGN_EXTEND;
5707 else if (Args[i].isZExt)
5708 ExtendKind = ISD::ZERO_EXTEND;
5709
Dale Johannesen66978ee2009-01-31 02:22:37 +00005710 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, PartVT, ExtendKind);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005711
5712 for (unsigned i = 0; i != NumParts; ++i) {
5713 // if it isn't first piece, alignment must be 1
5714 ISD::ArgFlagsTy MyFlags = Flags;
5715 if (NumParts > 1 && i == 0)
5716 MyFlags.setSplit();
5717 else if (i != 0)
5718 MyFlags.setOrigAlign(1);
5719
5720 Ops.push_back(Parts[i]);
5721 Ops.push_back(DAG.getArgFlags(MyFlags));
5722 }
5723 }
5724 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005725
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005726 // Figure out the result value types. We start by making a list of
5727 // the potentially illegal return value types.
5728 SmallVector<MVT, 4> LoweredRetTys;
5729 SmallVector<MVT, 4> RetTys;
5730 ComputeValueVTs(*this, RetTy, RetTys);
5731
5732 // Then we translate that to a list of legal types.
5733 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5734 MVT VT = RetTys[I];
5735 MVT RegisterVT = getRegisterType(VT);
5736 unsigned NumRegs = getNumRegisters(VT);
5737 for (unsigned i = 0; i != NumRegs; ++i)
5738 LoweredRetTys.push_back(RegisterVT);
5739 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005740
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005741 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005742
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005743 // Create the CALL node.
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005744 SDValue Res = DAG.getCall(CallingConv, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005745 isVarArg, isTailCall, isInreg,
Dan Gohman095cc292008-09-13 01:54:27 +00005746 DAG.getVTList(&LoweredRetTys[0],
5747 LoweredRetTys.size()),
Dale Johannesen86098bd2008-09-26 19:31:26 +00005748 &Ops[0], Ops.size()
5749 );
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005750 Chain = Res.getValue(LoweredRetTys.size() - 1);
5751
5752 // Gather up the call result into a single value.
Dan Gohmanb5cc34d2008-10-07 00:12:37 +00005753 if (RetTy != Type::VoidTy && !RetTys.empty()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005754 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5755
5756 if (RetSExt)
5757 AssertOp = ISD::AssertSext;
5758 else if (RetZExt)
5759 AssertOp = ISD::AssertZext;
5760
5761 SmallVector<SDValue, 4> ReturnValues;
5762 unsigned RegNo = 0;
5763 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5764 MVT VT = RetTys[I];
5765 MVT RegisterVT = getRegisterType(VT);
5766 unsigned NumRegs = getNumRegisters(VT);
5767 unsigned RegNoEnd = NumRegs + RegNo;
5768 SmallVector<SDValue, 4> Results;
5769 for (; RegNo != RegNoEnd; ++RegNo)
5770 Results.push_back(Res.getValue(RegNo));
5771 SDValue ReturnValue =
Dale Johannesen66978ee2009-01-31 02:22:37 +00005772 getCopyFromParts(DAG, dl, &Results[0], NumRegs, RegisterVT, VT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005773 AssertOp);
5774 ReturnValues.push_back(ReturnValue);
5775 }
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005776 Res = DAG.getNode(ISD::MERGE_VALUES, dl,
Duncan Sandsaaffa052008-12-01 11:41:29 +00005777 DAG.getVTList(&RetTys[0], RetTys.size()),
5778 &ReturnValues[0], ReturnValues.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005779 }
5780
5781 return std::make_pair(Res, Chain);
5782}
5783
Duncan Sands9fbc7e22009-01-21 09:00:29 +00005784void TargetLowering::LowerOperationWrapper(SDNode *N,
5785 SmallVectorImpl<SDValue> &Results,
5786 SelectionDAG &DAG) {
5787 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptabb326bb2009-01-21 04:48:39 +00005788 if (Res.getNode())
5789 Results.push_back(Res);
5790}
5791
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005792SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5793 assert(0 && "LowerOperation not implemented for this target!");
5794 abort();
5795 return SDValue();
5796}
5797
5798
5799void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5800 SDValue Op = getValue(V);
5801 assert((Op.getOpcode() != ISD::CopyFromReg ||
5802 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5803 "Copy from a reg to the same reg!");
5804 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5805
5806 RegsForValue RFV(TLI, Reg, V->getType());
5807 SDValue Chain = DAG.getEntryNode();
Dale Johannesen66978ee2009-01-31 02:22:37 +00005808 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005809 PendingExports.push_back(Chain);
5810}
5811
5812#include "llvm/CodeGen/SelectionDAGISel.h"
5813
5814void SelectionDAGISel::
5815LowerArguments(BasicBlock *LLVMBB) {
5816 // If this is the entry block, emit arguments.
5817 Function &F = *LLVMBB->getParent();
5818 SDValue OldRoot = SDL->DAG.getRoot();
5819 SmallVector<SDValue, 16> Args;
Dale Johannesen66978ee2009-01-31 02:22:37 +00005820 TLI.LowerArguments(F, SDL->DAG, Args, SDL->getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005821
5822 unsigned a = 0;
5823 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5824 AI != E; ++AI) {
5825 SmallVector<MVT, 4> ValueVTs;
5826 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5827 unsigned NumValues = ValueVTs.size();
5828 if (!AI->use_empty()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00005829 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues,
Dale Johannesen4be0bdf2009-02-05 00:20:09 +00005830 SDL->getCurDebugLoc()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005831 // If this argument is live outside of the entry block, insert a copy from
5832 // whereever we got it to the vreg that other BB's will reference it as.
5833 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5834 if (VMI != FuncInfo->ValueMap.end()) {
5835 SDL->CopyValueToVirtualRegister(AI, VMI->second);
5836 }
5837 }
5838 a += NumValues;
5839 }
5840
5841 // Finally, if the target has anything special to do, allow it to do so.
5842 // FIXME: this should insert code into the DAG!
5843 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5844}
5845
5846/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5847/// ensure constants are generated when needed. Remember the virtual registers
5848/// that need to be added to the Machine PHI nodes as input. We cannot just
5849/// directly add them, because expansion might result in multiple MBB's for one
5850/// BB. As such, the start of the BB might correspond to a different MBB than
5851/// the end.
5852///
5853void
5854SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5855 TerminatorInst *TI = LLVMBB->getTerminator();
5856
5857 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5858
5859 // Check successor nodes' PHI nodes that expect a constant to be available
5860 // from this block.
5861 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5862 BasicBlock *SuccBB = TI->getSuccessor(succ);
5863 if (!isa<PHINode>(SuccBB->begin())) continue;
5864 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005865
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005866 // If this terminator has multiple identical successors (common for
5867 // switches), only handle each succ once.
5868 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005869
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005870 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5871 PHINode *PN;
5872
5873 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5874 // nodes and Machine PHI nodes, but the incoming operands have not been
5875 // emitted yet.
5876 for (BasicBlock::iterator I = SuccBB->begin();
5877 (PN = dyn_cast<PHINode>(I)); ++I) {
5878 // Ignore dead phi's.
5879 if (PN->use_empty()) continue;
5880
5881 unsigned Reg;
5882 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5883
5884 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5885 unsigned &RegOut = SDL->ConstantsOut[C];
5886 if (RegOut == 0) {
5887 RegOut = FuncInfo->CreateRegForValue(C);
5888 SDL->CopyValueToVirtualRegister(C, RegOut);
5889 }
5890 Reg = RegOut;
5891 } else {
5892 Reg = FuncInfo->ValueMap[PHIOp];
5893 if (Reg == 0) {
5894 assert(isa<AllocaInst>(PHIOp) &&
5895 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5896 "Didn't codegen value into a register!??");
5897 Reg = FuncInfo->CreateRegForValue(PHIOp);
5898 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5899 }
5900 }
5901
5902 // Remember that this register needs to added to the machine PHI node as
5903 // the input for this MBB.
5904 SmallVector<MVT, 4> ValueVTs;
5905 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5906 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5907 MVT VT = ValueVTs[vti];
5908 unsigned NumRegisters = TLI.getNumRegisters(VT);
5909 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5910 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5911 Reg += NumRegisters;
5912 }
5913 }
5914 }
5915 SDL->ConstantsOut.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005916}
5917
Dan Gohman3df24e62008-09-03 23:12:08 +00005918/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5919/// supports legal types, and it emits MachineInstrs directly instead of
5920/// creating SelectionDAG nodes.
5921///
5922bool
5923SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5924 FastISel *F) {
5925 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005926
Dan Gohman3df24e62008-09-03 23:12:08 +00005927 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5928 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5929
5930 // Check successor nodes' PHI nodes that expect a constant to be available
5931 // from this block.
5932 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5933 BasicBlock *SuccBB = TI->getSuccessor(succ);
5934 if (!isa<PHINode>(SuccBB->begin())) continue;
5935 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005936
Dan Gohman3df24e62008-09-03 23:12:08 +00005937 // If this terminator has multiple identical successors (common for
5938 // switches), only handle each succ once.
5939 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005940
Dan Gohman3df24e62008-09-03 23:12:08 +00005941 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5942 PHINode *PN;
5943
5944 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5945 // nodes and Machine PHI nodes, but the incoming operands have not been
5946 // emitted yet.
5947 for (BasicBlock::iterator I = SuccBB->begin();
5948 (PN = dyn_cast<PHINode>(I)); ++I) {
5949 // Ignore dead phi's.
5950 if (PN->use_empty()) continue;
5951
5952 // Only handle legal types. Two interesting things to note here. First,
5953 // by bailing out early, we may leave behind some dead instructions,
5954 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5955 // own moves. Second, this check is necessary becuase FastISel doesn't
5956 // use CreateRegForValue to create registers, so it always creates
5957 // exactly one register for each non-void instruction.
5958 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5959 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
Dan Gohman74321ab2008-09-10 21:01:31 +00005960 // Promote MVT::i1.
5961 if (VT == MVT::i1)
5962 VT = TLI.getTypeToTransformTo(VT);
5963 else {
5964 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5965 return false;
5966 }
Dan Gohman3df24e62008-09-03 23:12:08 +00005967 }
5968
5969 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5970
5971 unsigned Reg = F->getRegForValue(PHIOp);
5972 if (Reg == 0) {
5973 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5974 return false;
5975 }
5976 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
5977 }
5978 }
5979
5980 return true;
5981}