blob: f0b1ec8a27356950c813183d41d8f8d76429848e [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"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000048#include "llvm/Target/TargetOptions.h"
49#include "llvm/Support/Compiler.h"
Mikhail Glushenkov2388a582009-01-16 07:02:28 +000050#include "llvm/Support/CommandLine.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000051#include "llvm/Support/Debug.h"
52#include "llvm/Support/MathExtras.h"
Anton Korobeynikov56d245b2008-12-23 22:26:18 +000053#include "llvm/Support/raw_ostream.h"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000054#include <algorithm>
55using namespace llvm;
56
Dale Johannesen601d3c02008-09-05 01:48:15 +000057/// LimitFloatPrecision - Generate low-precision inline sequences for
58/// some float libcalls (6, 8 or 12 bits).
59static unsigned LimitFloatPrecision;
60
61static cl::opt<unsigned, true>
62LimitFPPrecision("limit-float-precision",
63 cl::desc("Generate low-precision inline sequences "
64 "for some float libcalls"),
65 cl::location(LimitFloatPrecision),
66 cl::init(0));
67
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000068/// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
Dan Gohman2c91d102009-01-06 22:53:52 +000069/// of insertvalue or extractvalue indices that identify a member, return
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000070/// the linearized index of the start of the member.
71///
72static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
73 const unsigned *Indices,
74 const unsigned *IndicesEnd,
75 unsigned CurIndex = 0) {
76 // Base case: We're done.
77 if (Indices && Indices == IndicesEnd)
78 return CurIndex;
79
80 // Given a struct type, recursively traverse the elements.
81 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
82 for (StructType::element_iterator EB = STy->element_begin(),
83 EI = EB,
84 EE = STy->element_end();
85 EI != EE; ++EI) {
86 if (Indices && *Indices == unsigned(EI - EB))
87 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
88 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
89 }
Dan Gohman2c91d102009-01-06 22:53:52 +000090 return CurIndex;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000091 }
92 // Given an array type, recursively traverse the elements.
93 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
94 const Type *EltTy = ATy->getElementType();
95 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
96 if (Indices && *Indices == i)
97 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
98 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
99 }
Dan Gohman2c91d102009-01-06 22:53:52 +0000100 return CurIndex;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000101 }
102 // We haven't found the type we're looking for, so keep searching.
103 return CurIndex + 1;
104}
105
106/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
107/// MVTs that represent all the individual underlying
108/// non-aggregate types that comprise it.
109///
110/// If Offsets is non-null, it points to a vector to be filled in
111/// with the in-memory offsets of each of the individual values.
112///
113static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
114 SmallVectorImpl<MVT> &ValueVTs,
115 SmallVectorImpl<uint64_t> *Offsets = 0,
116 uint64_t StartingOffset = 0) {
117 // Given a struct type, recursively traverse the elements.
118 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
119 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
120 for (StructType::element_iterator EB = STy->element_begin(),
121 EI = EB,
122 EE = STy->element_end();
123 EI != EE; ++EI)
124 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
125 StartingOffset + SL->getElementOffset(EI - EB));
126 return;
127 }
128 // Given an array type, recursively traverse the elements.
129 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
130 const Type *EltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000131 uint64_t EltSize = TLI.getTargetData()->getTypeAllocSize(EltTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000132 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
133 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
134 StartingOffset + i * EltSize);
135 return;
136 }
Dan Gohman5e5558b2009-04-23 22:50:03 +0000137 // Interpret void as zero return values.
138 if (Ty == Type::VoidTy)
139 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000140 // Base case: we can get an MVT for this LLVM IR type.
141 ValueVTs.push_back(TLI.getValueType(Ty));
142 if (Offsets)
143 Offsets->push_back(StartingOffset);
144}
145
Dan Gohman2a7c6712008-09-03 23:18:39 +0000146namespace llvm {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000147 /// RegsForValue - This struct represents the registers (physical or virtual)
148 /// that a particular set of values is assigned, and the type information about
149 /// the value. The most common situation is to represent one value at a time,
150 /// but struct or array values are handled element-wise as multiple values.
151 /// The splitting of aggregates is performed recursively, so that we never
152 /// have aggregate-typed registers. The values at this point do not necessarily
153 /// have legal types, so each value may require one or more registers of some
154 /// legal type.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000155 ///
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000156 struct VISIBILITY_HIDDEN RegsForValue {
157 /// TLI - The TargetLowering object.
158 ///
159 const TargetLowering *TLI;
160
161 /// ValueVTs - The value types of the values, which may not be legal, and
162 /// may need be promoted or synthesized from one or more registers.
163 ///
164 SmallVector<MVT, 4> ValueVTs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000165
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000166 /// RegVTs - The value types of the registers. This is the same size as
167 /// ValueVTs and it records, for each value, what the type of the assigned
168 /// register or registers are. (Individual values are never synthesized
169 /// from more than one type of register.)
170 ///
171 /// With virtual registers, the contents of RegVTs is redundant with TLI's
172 /// getRegisterType member function, however when with physical registers
173 /// it is necessary to have a separate record of the types.
174 ///
175 SmallVector<MVT, 4> RegVTs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000176
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000177 /// Regs - This list holds the registers assigned to the values.
178 /// Each legal or promoted value requires one register, and each
179 /// expanded value requires multiple registers.
180 ///
181 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000182
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000183 RegsForValue() : TLI(0) {}
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000184
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000185 RegsForValue(const TargetLowering &tli,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000186 const SmallVector<unsigned, 4> &regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000187 MVT regvt, MVT valuevt)
188 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
189 RegsForValue(const TargetLowering &tli,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000190 const SmallVector<unsigned, 4> &regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000191 const SmallVector<MVT, 4> &regvts,
192 const SmallVector<MVT, 4> &valuevts)
193 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
194 RegsForValue(const TargetLowering &tli,
195 unsigned Reg, const Type *Ty) : TLI(&tli) {
196 ComputeValueVTs(tli, Ty, ValueVTs);
197
198 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
199 MVT ValueVT = ValueVTs[Value];
200 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
201 MVT RegisterVT = TLI->getRegisterType(ValueVT);
202 for (unsigned i = 0; i != NumRegs; ++i)
203 Regs.push_back(Reg + i);
204 RegVTs.push_back(RegisterVT);
205 Reg += NumRegs;
206 }
207 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000208
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000209 /// append - Add the specified values to this one.
210 void append(const RegsForValue &RHS) {
211 TLI = RHS.TLI;
212 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
213 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
214 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
215 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000216
217
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000218 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000219 /// this value and returns the result as a ValueVTs value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000220 /// Chain/Flag as the input and updates them for the output Chain/Flag.
221 /// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000222 SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000223 SDValue &Chain, SDValue *Flag) const;
224
225 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000226 /// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000227 /// Chain/Flag as the input and updates them for the output Chain/Flag.
228 /// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000229 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000230 SDValue &Chain, SDValue *Flag) const;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000231
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000232 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
Evan Cheng697cbbf2009-03-20 18:03:34 +0000233 /// operand list. This adds the code marker, matching input operand index
234 /// (if applicable), and includes the number of values added into it.
235 void AddInlineAsmOperands(unsigned Code,
236 bool HasMatching, unsigned MatchingIdx,
237 SelectionDAG &DAG, std::vector<SDValue> &Ops) const;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000238 };
239}
240
241/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000242/// PHI nodes or outside of the basic block that defines it, or used by a
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000243/// switch or atomic instruction, which may expand to multiple basic blocks.
244static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
245 if (isa<PHINode>(I)) return true;
246 BasicBlock *BB = I->getParent();
247 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
Dan Gohman8e5c0da2009-04-09 02:33:36 +0000248 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000249 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 Sands777d2302009-05-09 07:06:46 +0000297 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(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
Argyrios Kyrtzidisa3437642009-05-20 22:57:17 +0000315 // FIXME: PHI instructions currently get an invalid scope. This is because
316 // tracking of debug scopes is done through a simple mechanism where
317 // "entering" a scope implies that the scope is entered for the first time.
318 // If we keep track of debug scopes for the following loop, the PHI
319 // instructions would get scopes that will not be used again later by the
320 // instruction selectors.
321 // Either provide a mechanism to re-enter a previously created scope or wait
322 // for when the DebugLoc is retrieved from Instruction, in which case the
323 // current debug scope tracking mechanism will be obsolete.
324 DebugScope DbgScope;
325
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000326 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
327 // also creates the initial PHI MachineInstrs, though none of the input
328 // operands are populated.
329 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
330 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
331 MBBMap[BB] = MBB;
332 MF->push_back(MBB);
333
334 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
335 // appropriate.
336 PHINode *PN;
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000337 DebugLoc DL;
338 for (BasicBlock::iterator
339 I = BB->begin(), E = BB->end(); I != E; ++I) {
340 if (CallInst *CI = dyn_cast<CallInst>(I)) {
341 if (Function *F = CI->getCalledFunction()) {
342 switch (F->getIntrinsicID()) {
343 default: break;
344 case Intrinsic::dbg_stoppoint: {
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000345 DbgStopPointInst *SPI = cast<DbgStopPointInst>(I);
346
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +0000347 if (DIDescriptor::ValidDebugInfo(SPI->getContext(),
348 CodeGenOpt::Default)) {
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000349 DICompileUnit CU(cast<GlobalVariable>(SPI->getContext()));
Argyrios Kyrtzidisa26eae62009-04-30 23:22:31 +0000350 unsigned idx = MF->getOrCreateDebugLocID(CU.getGV(),
Argyrios Kyrtzidisa3437642009-05-20 22:57:17 +0000351 DbgScope,
Scott Michelfdc40a02009-02-17 22:15:04 +0000352 SPI->getLine(),
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000353 SPI->getColumn());
354 DL = DebugLoc::get(idx);
355 }
356
357 break;
358 }
359 case Intrinsic::dbg_func_start: {
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +0000360 DbgFuncStartInst *FSI = cast<DbgFuncStartInst>(I);
361 Value *SP = FSI->getSubprogram();
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000362
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +0000363 if (DIDescriptor::ValidDebugInfo(SP, CodeGenOpt::Default)) {
364 DISubprogram Subprogram(cast<GlobalVariable>(SP));
365 DICompileUnit CU(Subprogram.getCompileUnit());
366 unsigned Line = Subprogram.getLineNumber();
Argyrios Kyrtzidisa3437642009-05-20 22:57:17 +0000367 DL = DebugLoc::get(MF->getOrCreateDebugLocID(CU.getGV(), DbgScope,
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +0000368 Line, 0));
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000369 }
Scott Michelfdc40a02009-02-17 22:15:04 +0000370
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000371 break;
372 }
373 }
374 }
375 }
376
377 PN = dyn_cast<PHINode>(I);
378 if (!PN || PN->use_empty()) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000379
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000380 unsigned PHIReg = ValueMap[PN];
381 assert(PHIReg && "PHI node does not have an assigned virtual register!");
382
383 SmallVector<MVT, 4> ValueVTs;
384 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
385 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
386 MVT VT = ValueVTs[vti];
387 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohman6448d912008-09-04 15:39:15 +0000388 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000389 for (unsigned i = 0; i != NumRegisters; ++i)
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000390 BuildMI(MBB, DL, TII->get(TargetInstrInfo::PHI), PHIReg + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000391 PHIReg += NumRegisters;
392 }
393 }
394 }
395}
396
397unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
398 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
399}
400
401/// CreateRegForValue - Allocate the appropriate number of virtual registers of
402/// the correctly promoted or expanded types. Assign these registers
403/// consecutive vreg numbers and return the first assigned number.
404///
405/// In the case that the given value has struct or array type, this function
406/// will assign registers for each member or element.
407///
408unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
409 SmallVector<MVT, 4> ValueVTs;
410 ComputeValueVTs(TLI, V->getType(), ValueVTs);
411
412 unsigned FirstReg = 0;
413 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
414 MVT ValueVT = ValueVTs[Value];
415 MVT RegisterVT = TLI.getRegisterType(ValueVT);
416
417 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
418 for (unsigned i = 0; i != NumRegs; ++i) {
419 unsigned R = MakeReg(RegisterVT);
420 if (!FirstReg) FirstReg = R;
421 }
422 }
423 return FirstReg;
424}
425
426/// getCopyFromParts - Create a value that contains the specified legal parts
427/// combined into the value they represent. If the parts combine to a type
428/// larger then ValueVT then AssertOp can be used to specify whether the extra
429/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
430/// (ISD::AssertSext).
Dale Johannesen66978ee2009-01-31 02:22:37 +0000431static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
432 const SDValue *Parts,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000433 unsigned NumParts, MVT PartVT, MVT ValueVT,
434 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000435 assert(NumParts > 0 && "No parts to assemble!");
Dan Gohmane9530ec2009-01-15 16:58:17 +0000436 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000437 SDValue Val = Parts[0];
438
439 if (NumParts > 1) {
440 // Assemble the value from multiple parts.
Eli Friedman2ac8b322009-05-20 06:02:09 +0000441 if (!ValueVT.isVector() && ValueVT.isInteger()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000442 unsigned PartBits = PartVT.getSizeInBits();
443 unsigned ValueBits = ValueVT.getSizeInBits();
444
445 // Assemble the power of 2 part.
446 unsigned RoundParts = NumParts & (NumParts - 1) ?
447 1 << Log2_32(NumParts) : NumParts;
448 unsigned RoundBits = PartBits * RoundParts;
449 MVT RoundVT = RoundBits == ValueBits ?
450 ValueVT : MVT::getIntegerVT(RoundBits);
451 SDValue Lo, Hi;
452
Eli Friedman2ac8b322009-05-20 06:02:09 +0000453 MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000454
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000455 if (RoundParts > 2) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000456 Lo = getCopyFromParts(DAG, dl, Parts, RoundParts/2, PartVT, HalfVT);
457 Hi = getCopyFromParts(DAG, dl, Parts+RoundParts/2, RoundParts/2,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000458 PartVT, HalfVT);
459 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000460 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
461 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000462 }
463 if (TLI.isBigEndian())
464 std::swap(Lo, Hi);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000465 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000466
467 if (RoundParts < NumParts) {
468 // Assemble the trailing non-power-of-2 part.
469 unsigned OddParts = NumParts - RoundParts;
470 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
Scott Michelfdc40a02009-02-17 22:15:04 +0000471 Hi = getCopyFromParts(DAG, dl,
Dale Johannesen66978ee2009-01-31 02:22:37 +0000472 Parts+RoundParts, OddParts, PartVT, OddVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000473
474 // Combine the round and odd parts.
475 Lo = Val;
476 if (TLI.isBigEndian())
477 std::swap(Lo, Hi);
478 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000479 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
480 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000481 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands92abc622009-01-31 15:50:11 +0000482 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000483 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
484 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000485 }
Eli Friedman2ac8b322009-05-20 06:02:09 +0000486 } else if (ValueVT.isVector()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000487 // Handle a multi-element vector.
488 MVT IntermediateVT, RegisterVT;
489 unsigned NumIntermediates;
490 unsigned NumRegs =
491 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
492 RegisterVT);
493 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
494 NumParts = NumRegs; // Silence a compiler warning.
495 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
496 assert(RegisterVT == Parts[0].getValueType() &&
497 "Part type doesn't match part!");
498
499 // Assemble the parts into intermediate operands.
500 SmallVector<SDValue, 8> Ops(NumIntermediates);
501 if (NumIntermediates == NumParts) {
502 // If the register was not expanded, truncate or copy the value,
503 // as appropriate.
504 for (unsigned i = 0; i != NumParts; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000505 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000506 PartVT, IntermediateVT);
507 } else if (NumParts > 0) {
508 // If the intermediate type was expanded, build the intermediate operands
509 // from the parts.
510 assert(NumParts % NumIntermediates == 0 &&
511 "Must expand into a divisible number of parts!");
512 unsigned Factor = NumParts / NumIntermediates;
513 for (unsigned i = 0; i != NumIntermediates; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000514 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000515 PartVT, IntermediateVT);
516 }
517
518 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
519 // operands.
520 Val = DAG.getNode(IntermediateVT.isVector() ?
Dale Johannesen66978ee2009-01-31 02:22:37 +0000521 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000522 ValueVT, &Ops[0], NumIntermediates);
Eli Friedman2ac8b322009-05-20 06:02:09 +0000523 } else if (PartVT.isFloatingPoint()) {
524 // FP split into multiple FP parts (for ppcf128)
525 assert(ValueVT == MVT(MVT::ppcf128) && PartVT == MVT(MVT::f64) &&
526 "Unexpected split");
527 SDValue Lo, Hi;
528 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, MVT(MVT::f64), Parts[0]);
529 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, MVT(MVT::f64), Parts[1]);
530 if (TLI.isBigEndian())
531 std::swap(Lo, Hi);
532 Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi);
533 } else {
534 // FP split into integer parts (soft fp)
535 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
536 !PartVT.isVector() && "Unexpected split");
537 MVT IntVT = MVT::getIntegerVT(ValueVT.getSizeInBits());
538 Val = getCopyFromParts(DAG, dl, Parts, NumParts, PartVT, IntVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000539 }
540 }
541
542 // There is now one part, held in Val. Correct it to match ValueVT.
543 PartVT = Val.getValueType();
544
545 if (PartVT == ValueVT)
546 return Val;
547
548 if (PartVT.isVector()) {
549 assert(ValueVT.isVector() && "Unknown vector conversion!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000550 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000551 }
552
553 if (ValueVT.isVector()) {
554 assert(ValueVT.getVectorElementType() == PartVT &&
555 ValueVT.getVectorNumElements() == 1 &&
556 "Only trivial scalar-to-vector conversions should get here!");
Evan Chenga87008d2009-02-25 22:49:59 +0000557 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000558 }
559
560 if (PartVT.isInteger() &&
561 ValueVT.isInteger()) {
562 if (ValueVT.bitsLT(PartVT)) {
563 // For a truncate, see if we have any information to
564 // indicate whether the truncated bits will always be
565 // zero or sign-extension.
566 if (AssertOp != ISD::DELETED_NODE)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000567 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000568 DAG.getValueType(ValueVT));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000569 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000570 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000571 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000572 }
573 }
574
575 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
576 if (ValueVT.bitsLT(Val.getValueType()))
577 // FP_ROUND's are always exact here.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000578 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000579 DAG.getIntPtrConstant(1));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000580 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000581 }
582
583 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
Dale Johannesen66978ee2009-01-31 02:22:37 +0000584 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000585
586 assert(0 && "Unknown mismatch!");
587 return SDValue();
588}
589
590/// getCopyToParts - Create a series of nodes that contain the specified value
591/// split into legal parts. If the parts contain more bits than Val, then, for
592/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000593static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, SDValue Val,
Chris Lattner01426e12008-10-21 00:45:36 +0000594 SDValue *Parts, unsigned NumParts, MVT PartVT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000595 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohmane9530ec2009-01-15 16:58:17 +0000596 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000597 MVT PtrVT = TLI.getPointerTy();
598 MVT ValueVT = Val.getValueType();
599 unsigned PartBits = PartVT.getSizeInBits();
Dale Johannesen8a36f502009-02-25 22:39:13 +0000600 unsigned OrigNumParts = NumParts;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000601 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
602
603 if (!NumParts)
604 return;
605
606 if (!ValueVT.isVector()) {
607 if (PartVT == ValueVT) {
608 assert(NumParts == 1 && "No-op copy with multiple parts!");
609 Parts[0] = Val;
610 return;
611 }
612
613 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
614 // If the parts cover more bits than the value has, promote the value.
615 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
616 assert(NumParts == 1 && "Do not know what to promote to!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000617 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000618 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
619 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000620 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000621 } else {
622 assert(0 && "Unknown mismatch!");
623 }
624 } else if (PartBits == ValueVT.getSizeInBits()) {
625 // Different types of the same size.
626 assert(NumParts == 1 && PartVT != ValueVT);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000627 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000628 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
629 // If the parts cover less bits than value has, truncate the value.
630 if (PartVT.isInteger() && ValueVT.isInteger()) {
631 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000632 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000633 } else {
634 assert(0 && "Unknown mismatch!");
635 }
636 }
637
638 // The value may have changed - recompute ValueVT.
639 ValueVT = Val.getValueType();
640 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
641 "Failed to tile the value with PartVT!");
642
643 if (NumParts == 1) {
644 assert(PartVT == ValueVT && "Type conversion failed!");
645 Parts[0] = Val;
646 return;
647 }
648
649 // Expand the value into multiple parts.
650 if (NumParts & (NumParts - 1)) {
651 // The number of parts is not a power of 2. Split off and copy the tail.
652 assert(PartVT.isInteger() && ValueVT.isInteger() &&
653 "Do not know what to expand to!");
654 unsigned RoundParts = 1 << Log2_32(NumParts);
655 unsigned RoundBits = RoundParts * PartBits;
656 unsigned OddParts = NumParts - RoundParts;
Dale Johannesen66978ee2009-01-31 02:22:37 +0000657 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000658 DAG.getConstant(RoundBits,
Duncan Sands92abc622009-01-31 15:50:11 +0000659 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000660 getCopyToParts(DAG, dl, OddVal, Parts + RoundParts, OddParts, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000661 if (TLI.isBigEndian())
662 // The odd parts were reversed by getCopyToParts - unreverse them.
663 std::reverse(Parts + RoundParts, Parts + NumParts);
664 NumParts = RoundParts;
665 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000666 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000667 }
668
669 // The number of parts is a power of 2. Repeatedly bisect the value using
670 // EXTRACT_ELEMENT.
Scott Michelfdc40a02009-02-17 22:15:04 +0000671 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000672 MVT::getIntegerVT(ValueVT.getSizeInBits()),
673 Val);
674 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
675 for (unsigned i = 0; i < NumParts; i += StepSize) {
676 unsigned ThisBits = StepSize * PartBits / 2;
677 MVT ThisVT = MVT::getIntegerVT (ThisBits);
678 SDValue &Part0 = Parts[i];
679 SDValue &Part1 = Parts[i+StepSize/2];
680
Scott Michelfdc40a02009-02-17 22:15:04 +0000681 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000682 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000683 DAG.getConstant(1, PtrVT));
Scott Michelfdc40a02009-02-17 22:15:04 +0000684 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000685 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000686 DAG.getConstant(0, PtrVT));
687
688 if (ThisBits == PartBits && ThisVT != PartVT) {
Scott Michelfdc40a02009-02-17 22:15:04 +0000689 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000690 PartVT, Part0);
Scott Michelfdc40a02009-02-17 22:15:04 +0000691 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000692 PartVT, Part1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000693 }
694 }
695 }
696
697 if (TLI.isBigEndian())
Dale Johannesen8a36f502009-02-25 22:39:13 +0000698 std::reverse(Parts, Parts + OrigNumParts);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000699
700 return;
701 }
702
703 // Vector ValueVT.
704 if (NumParts == 1) {
705 if (PartVT != ValueVT) {
706 if (PartVT.isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000707 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000708 } else {
709 assert(ValueVT.getVectorElementType() == PartVT &&
710 ValueVT.getVectorNumElements() == 1 &&
711 "Only trivial vector-to-scalar conversions should get here!");
Scott Michelfdc40a02009-02-17 22:15:04 +0000712 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000713 PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000714 DAG.getConstant(0, PtrVT));
715 }
716 }
717
718 Parts[0] = Val;
719 return;
720 }
721
722 // Handle a multi-element vector.
723 MVT IntermediateVT, RegisterVT;
724 unsigned NumIntermediates;
Dan Gohmane9530ec2009-01-15 16:58:17 +0000725 unsigned NumRegs = TLI
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000726 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
727 RegisterVT);
728 unsigned NumElements = ValueVT.getVectorNumElements();
729
730 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
731 NumParts = NumRegs; // Silence a compiler warning.
732 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
733
734 // Split the vector into intermediate operands.
735 SmallVector<SDValue, 8> Ops(NumIntermediates);
736 for (unsigned i = 0; i != NumIntermediates; ++i)
737 if (IntermediateVT.isVector())
Scott Michelfdc40a02009-02-17 22:15:04 +0000738 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000739 IntermediateVT, Val,
740 DAG.getConstant(i * (NumElements / NumIntermediates),
741 PtrVT));
742 else
Scott Michelfdc40a02009-02-17 22:15:04 +0000743 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000744 IntermediateVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000745 DAG.getConstant(i, PtrVT));
746
747 // Split the intermediate operands into legal parts.
748 if (NumParts == NumIntermediates) {
749 // If the register was not expanded, promote or copy the value,
750 // as appropriate.
751 for (unsigned i = 0; i != NumParts; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000752 getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000753 } else if (NumParts > 0) {
754 // If the intermediate type was expanded, split each the value into
755 // legal parts.
756 assert(NumParts % NumIntermediates == 0 &&
757 "Must expand into a divisible number of parts!");
758 unsigned Factor = NumParts / NumIntermediates;
759 for (unsigned i = 0; i != NumIntermediates; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000760 getCopyToParts(DAG, dl, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000761 }
762}
763
764
765void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
766 AA = &aa;
767 GFI = gfi;
768 TD = DAG.getTarget().getTargetData();
769}
770
771/// clear - Clear out the curret SelectionDAG and the associated
772/// state and prepare this SelectionDAGLowering object to be used
773/// for a new block. This doesn't clear out information about
774/// additional blocks that are needed to complete switch lowering
775/// or PHI node updating; that information is cleared out as it is
776/// consumed.
777void SelectionDAGLowering::clear() {
778 NodeMap.clear();
779 PendingLoads.clear();
780 PendingExports.clear();
781 DAG.clear();
Bill Wendling8fcf1702009-02-06 21:36:23 +0000782 CurDebugLoc = DebugLoc::getUnknownLoc();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000783}
784
785/// getRoot - Return the current virtual root of the Selection DAG,
786/// flushing any PendingLoad items. This must be done before emitting
787/// a store or any other node that may need to be ordered after any
788/// prior load instructions.
789///
790SDValue SelectionDAGLowering::getRoot() {
791 if (PendingLoads.empty())
792 return DAG.getRoot();
793
794 if (PendingLoads.size() == 1) {
795 SDValue Root = PendingLoads[0];
796 DAG.setRoot(Root);
797 PendingLoads.clear();
798 return Root;
799 }
800
801 // Otherwise, we have to make a token factor node.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000802 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000803 &PendingLoads[0], PendingLoads.size());
804 PendingLoads.clear();
805 DAG.setRoot(Root);
806 return Root;
807}
808
809/// getControlRoot - Similar to getRoot, but instead of flushing all the
810/// PendingLoad items, flush all the PendingExports items. It is necessary
811/// to do this before emitting a terminator instruction.
812///
813SDValue SelectionDAGLowering::getControlRoot() {
814 SDValue Root = DAG.getRoot();
815
816 if (PendingExports.empty())
817 return Root;
818
819 // Turn all of the CopyToReg chains into one factored node.
820 if (Root.getOpcode() != ISD::EntryToken) {
821 unsigned i = 0, e = PendingExports.size();
822 for (; i != e; ++i) {
823 assert(PendingExports[i].getNode()->getNumOperands() > 1);
824 if (PendingExports[i].getNode()->getOperand(0) == Root)
825 break; // Don't add the root if we already indirectly depend on it.
826 }
827
828 if (i == e)
829 PendingExports.push_back(Root);
830 }
831
Dale Johannesen66978ee2009-01-31 02:22:37 +0000832 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000833 &PendingExports[0],
834 PendingExports.size());
835 PendingExports.clear();
836 DAG.setRoot(Root);
837 return Root;
838}
839
840void SelectionDAGLowering::visit(Instruction &I) {
841 visit(I.getOpcode(), I);
842}
843
844void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
845 // Note: this doesn't use InstVisitor, because it has to work with
846 // ConstantExpr's in addition to instructions.
847 switch (Opcode) {
848 default: assert(0 && "Unknown instruction type encountered!");
849 abort();
850 // Build the switch statement using the Instruction.def file.
851#define HANDLE_INST(NUM, OPCODE, CLASS) \
852 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
853#include "llvm/Instruction.def"
854 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000855}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000856
857void SelectionDAGLowering::visitAdd(User &I) {
858 if (I.getType()->isFPOrFPVector())
859 visitBinary(I, ISD::FADD);
860 else
861 visitBinary(I, ISD::ADD);
862}
863
864void SelectionDAGLowering::visitMul(User &I) {
865 if (I.getType()->isFPOrFPVector())
866 visitBinary(I, ISD::FMUL);
867 else
868 visitBinary(I, ISD::MUL);
869}
870
871SDValue SelectionDAGLowering::getValue(const Value *V) {
872 SDValue &N = NodeMap[V];
873 if (N.getNode()) return N;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000874
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000875 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
876 MVT VT = TLI.getValueType(V->getType(), true);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000877
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000878 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000879 return N = DAG.getConstant(*CI, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000880
881 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
882 return N = DAG.getGlobalAddress(GV, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000883
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000884 if (isa<ConstantPointerNull>(C))
885 return N = DAG.getConstant(0, TLI.getPointerTy());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000886
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000887 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000888 return N = DAG.getConstantFP(*CFP, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000889
Nate Begeman9008ca62009-04-27 18:41:29 +0000890 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
Dale Johannesene8d72302009-02-06 23:05:02 +0000891 return N = DAG.getUNDEF(VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000892
893 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
894 visit(CE->getOpcode(), *CE);
895 SDValue N1 = NodeMap[V];
896 assert(N1.getNode() && "visit didn't populate the ValueMap!");
897 return N1;
898 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000899
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000900 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
901 SmallVector<SDValue, 4> Constants;
902 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
903 OI != OE; ++OI) {
904 SDNode *Val = getValue(*OI).getNode();
905 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
906 Constants.push_back(SDValue(Val, i));
907 }
Dale Johannesen4be0bdf2009-02-05 00:20:09 +0000908 return DAG.getMergeValues(&Constants[0], Constants.size(),
909 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000910 }
911
912 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
913 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
914 "Unknown struct or array constant!");
915
916 SmallVector<MVT, 4> ValueVTs;
917 ComputeValueVTs(TLI, C->getType(), ValueVTs);
918 unsigned NumElts = ValueVTs.size();
919 if (NumElts == 0)
920 return SDValue(); // empty struct
921 SmallVector<SDValue, 4> Constants(NumElts);
922 for (unsigned i = 0; i != NumElts; ++i) {
923 MVT EltVT = ValueVTs[i];
924 if (isa<UndefValue>(C))
Dale Johannesene8d72302009-02-06 23:05:02 +0000925 Constants[i] = DAG.getUNDEF(EltVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000926 else if (EltVT.isFloatingPoint())
927 Constants[i] = DAG.getConstantFP(0, EltVT);
928 else
929 Constants[i] = DAG.getConstant(0, EltVT);
930 }
Dale Johannesen4be0bdf2009-02-05 00:20:09 +0000931 return DAG.getMergeValues(&Constants[0], NumElts, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000932 }
933
934 const VectorType *VecTy = cast<VectorType>(V->getType());
935 unsigned NumElements = VecTy->getNumElements();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000936
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000937 // Now that we know the number and type of the elements, get that number of
938 // elements into the Ops array based on what kind of constant it is.
939 SmallVector<SDValue, 16> Ops;
940 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
941 for (unsigned i = 0; i != NumElements; ++i)
942 Ops.push_back(getValue(CP->getOperand(i)));
943 } else {
Nate Begeman9008ca62009-04-27 18:41:29 +0000944 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000945 MVT EltVT = TLI.getValueType(VecTy->getElementType());
946
947 SDValue Op;
Nate Begeman9008ca62009-04-27 18:41:29 +0000948 if (EltVT.isFloatingPoint())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000949 Op = DAG.getConstantFP(0, EltVT);
950 else
951 Op = DAG.getConstant(0, EltVT);
952 Ops.assign(NumElements, Op);
953 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000954
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000955 // Create a BUILD_VECTOR node.
Evan Chenga87008d2009-02-25 22:49:59 +0000956 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
957 VT, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000958 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000959
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000960 // If this is a static alloca, generate it as the frameindex instead of
961 // computation.
962 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
963 DenseMap<const AllocaInst*, int>::iterator SI =
964 FuncInfo.StaticAllocaMap.find(AI);
965 if (SI != FuncInfo.StaticAllocaMap.end())
966 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
967 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000968
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000969 unsigned InReg = FuncInfo.ValueMap[V];
970 assert(InReg && "Value not in map!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000971
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000972 RegsForValue RFV(TLI, InReg, V->getType());
973 SDValue Chain = DAG.getEntryNode();
Dale Johannesen66978ee2009-01-31 02:22:37 +0000974 return RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000975}
976
977
978void SelectionDAGLowering::visitRet(ReturnInst &I) {
979 if (I.getNumOperands() == 0) {
Scott Michelfdc40a02009-02-17 22:15:04 +0000980 DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000981 MVT::Other, getControlRoot()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000982 return;
983 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000984
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000985 SmallVector<SDValue, 8> NewValues;
986 NewValues.push_back(getControlRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000987 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000988 SmallVector<MVT, 4> ValueVTs;
989 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
Dan Gohman7ea1ca62008-10-21 20:00:42 +0000990 unsigned NumValues = ValueVTs.size();
991 if (NumValues == 0) continue;
992
993 SDValue RetOp = getValue(I.getOperand(i));
994 for (unsigned j = 0, f = NumValues; j != f; ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000995 MVT VT = ValueVTs[j];
996
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000997 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000998
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000999 const Function *F = I.getParent()->getParent();
Devang Patel05988662008-09-25 21:00:45 +00001000 if (F->paramHasAttr(0, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001001 ExtendKind = ISD::SIGN_EXTEND;
Devang Patel05988662008-09-25 21:00:45 +00001002 else if (F->paramHasAttr(0, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001003 ExtendKind = ISD::ZERO_EXTEND;
1004
Evan Cheng3927f432009-03-25 20:20:11 +00001005 // FIXME: C calling convention requires the return type to be promoted to
1006 // at least 32-bit. But this is not necessary for non-C calling
1007 // conventions. The frontend should mark functions whose return values
1008 // require promoting with signext or zeroext attributes.
1009 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
1010 MVT MinVT = TLI.getRegisterType(MVT::i32);
1011 if (VT.bitsLT(MinVT))
1012 VT = MinVT;
1013 }
1014
1015 unsigned NumParts = TLI.getNumRegisters(VT);
1016 MVT PartVT = TLI.getRegisterType(VT);
1017 SmallVector<SDValue, 4> Parts(NumParts);
Dale Johannesen66978ee2009-01-31 02:22:37 +00001018 getCopyToParts(DAG, getCurDebugLoc(),
1019 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001020 &Parts[0], NumParts, PartVT, ExtendKind);
1021
Dale Johannesenc9c6da62008-09-25 20:47:45 +00001022 // 'inreg' on function refers to return value
1023 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Devang Patel05988662008-09-25 21:00:45 +00001024 if (F->paramHasAttr(0, Attribute::InReg))
Dale Johannesenc9c6da62008-09-25 20:47:45 +00001025 Flags.setInReg();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001026 for (unsigned i = 0; i < NumParts; ++i) {
1027 NewValues.push_back(Parts[i]);
Dale Johannesenc9c6da62008-09-25 20:47:45 +00001028 NewValues.push_back(DAG.getArgFlags(Flags));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001029 }
1030 }
1031 }
Dale Johannesen66978ee2009-01-31 02:22:37 +00001032 DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001033 &NewValues[0], NewValues.size()));
1034}
1035
Dan Gohmanad62f532009-04-23 23:13:24 +00001036/// CopyToExportRegsIfNeeded - If the given value has virtual registers
1037/// created for it, emit nodes to copy the value into the virtual
1038/// registers.
1039void SelectionDAGLowering::CopyToExportRegsIfNeeded(Value *V) {
1040 if (!V->use_empty()) {
1041 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1042 if (VMI != FuncInfo.ValueMap.end())
1043 CopyValueToVirtualRegister(V, VMI->second);
1044 }
1045}
1046
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001047/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1048/// the current basic block, add it to ValueMap now so that we'll get a
1049/// CopyTo/FromReg.
1050void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1051 // No need to export constants.
1052 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001053
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001054 // Already exported?
1055 if (FuncInfo.isExportedInst(V)) return;
1056
1057 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1058 CopyValueToVirtualRegister(V, Reg);
1059}
1060
1061bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1062 const BasicBlock *FromBB) {
1063 // The operands of the setcc have to be in this block. We don't know
1064 // how to export them from some other block.
1065 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1066 // Can export from current BB.
1067 if (VI->getParent() == FromBB)
1068 return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001069
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001070 // Is already exported, noop.
1071 return FuncInfo.isExportedInst(V);
1072 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001073
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001074 // If this is an argument, we can export it if the BB is the entry block or
1075 // if it is already exported.
1076 if (isa<Argument>(V)) {
1077 if (FromBB == &FromBB->getParent()->getEntryBlock())
1078 return true;
1079
1080 // Otherwise, can only export this if it is already exported.
1081 return FuncInfo.isExportedInst(V);
1082 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001083
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001084 // Otherwise, constants can always be exported.
1085 return true;
1086}
1087
1088static bool InBlock(const Value *V, const BasicBlock *BB) {
1089 if (const Instruction *I = dyn_cast<Instruction>(V))
1090 return I->getParent() == BB;
1091 return true;
1092}
1093
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001094/// getFCmpCondCode - Return the ISD condition code corresponding to
1095/// the given LLVM IR floating-point condition code. This includes
1096/// consideration of global floating-point math flags.
1097///
1098static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1099 ISD::CondCode FPC, FOC;
1100 switch (Pred) {
1101 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1102 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1103 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1104 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1105 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1106 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1107 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1108 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1109 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1110 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1111 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1112 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1113 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1114 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1115 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1116 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1117 default:
1118 assert(0 && "Invalid FCmp predicate opcode!");
1119 FOC = FPC = ISD::SETFALSE;
1120 break;
1121 }
1122 if (FiniteOnlyFPMath())
1123 return FOC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001124 else
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001125 return FPC;
1126}
1127
1128/// getICmpCondCode - Return the ISD condition code corresponding to
1129/// the given LLVM IR integer condition code.
1130///
1131static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1132 switch (Pred) {
1133 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1134 case ICmpInst::ICMP_NE: return ISD::SETNE;
1135 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1136 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1137 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1138 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1139 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1140 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1141 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1142 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1143 default:
1144 assert(0 && "Invalid ICmp predicate opcode!");
1145 return ISD::SETNE;
1146 }
1147}
1148
Dan Gohmanc2277342008-10-17 21:16:08 +00001149/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1150/// This function emits a branch and is used at the leaves of an OR or an
1151/// AND operator tree.
1152///
1153void
1154SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1155 MachineBasicBlock *TBB,
1156 MachineBasicBlock *FBB,
1157 MachineBasicBlock *CurBB) {
1158 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001159
Dan Gohmanc2277342008-10-17 21:16:08 +00001160 // If the leaf of the tree is a comparison, merge the condition into
1161 // the caseblock.
1162 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1163 // The operands of the cmp have to be in this block. We don't know
1164 // how to export them from some other block. If this is the first block
1165 // of the sequence, no exporting is needed.
1166 if (CurBB == CurMBB ||
1167 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1168 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001169 ISD::CondCode Condition;
1170 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001171 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001172 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001173 Condition = getFCmpCondCode(FC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001174 } else {
1175 Condition = ISD::SETEQ; // silence warning.
1176 assert(0 && "Unknown compare instruction");
1177 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001178
1179 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001180 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1181 SwitchCases.push_back(CB);
1182 return;
1183 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001184 }
1185
1186 // Create a CaseBlock record representing this branch.
1187 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1188 NULL, TBB, FBB, CurBB);
1189 SwitchCases.push_back(CB);
1190}
1191
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001192/// FindMergedConditions - If Cond is an expression like
Dan Gohmanc2277342008-10-17 21:16:08 +00001193void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1194 MachineBasicBlock *TBB,
1195 MachineBasicBlock *FBB,
1196 MachineBasicBlock *CurBB,
1197 unsigned Opc) {
1198 // If this node is not part of the or/and tree, emit it as a branch.
1199 Instruction *BOp = dyn_cast<Instruction>(Cond);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001200 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohmanc2277342008-10-17 21:16:08 +00001201 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1202 BOp->getParent() != CurBB->getBasicBlock() ||
1203 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1204 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1205 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001206 return;
1207 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001208
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001209 // Create TmpBB after CurBB.
1210 MachineFunction::iterator BBI = CurBB;
1211 MachineFunction &MF = DAG.getMachineFunction();
1212 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1213 CurBB->getParent()->insert(++BBI, TmpBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001214
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001215 if (Opc == Instruction::Or) {
1216 // Codegen X | Y as:
1217 // jmp_if_X TBB
1218 // jmp TmpBB
1219 // TmpBB:
1220 // jmp_if_Y TBB
1221 // jmp FBB
1222 //
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001223
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001224 // Emit the LHS condition.
1225 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001226
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001227 // Emit the RHS condition into TmpBB.
1228 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1229 } else {
1230 assert(Opc == Instruction::And && "Unknown merge op!");
1231 // Codegen X & Y as:
1232 // jmp_if_X TmpBB
1233 // jmp FBB
1234 // TmpBB:
1235 // jmp_if_Y TBB
1236 // jmp FBB
1237 //
1238 // This requires creation of TmpBB after CurBB.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001239
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001240 // Emit the LHS condition.
1241 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001242
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001243 // Emit the RHS condition into TmpBB.
1244 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1245 }
1246}
1247
1248/// If the set of cases should be emitted as a series of branches, return true.
1249/// If we should emit this as a bunch of and/or'd together conditions, return
1250/// false.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001251bool
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001252SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1253 if (Cases.size() != 2) return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001254
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001255 // If this is two comparisons of the same values or'd or and'd together, they
1256 // will get folded into a single comparison, so don't emit two blocks.
1257 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1258 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1259 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1260 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1261 return false;
1262 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001263
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001264 return true;
1265}
1266
1267void SelectionDAGLowering::visitBr(BranchInst &I) {
1268 // Update machine-CFG edges.
1269 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1270
1271 // Figure out which block is immediately after the current one.
1272 MachineBasicBlock *NextBlock = 0;
1273 MachineFunction::iterator BBI = CurMBB;
1274 if (++BBI != CurMBB->getParent()->end())
1275 NextBlock = BBI;
1276
1277 if (I.isUnconditional()) {
1278 // Update machine-CFG edges.
1279 CurMBB->addSuccessor(Succ0MBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001280
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001281 // If this is not a fall-through branch, emit the branch.
1282 if (Succ0MBB != NextBlock)
Scott Michelfdc40a02009-02-17 22:15:04 +00001283 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001284 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001285 DAG.getBasicBlock(Succ0MBB)));
1286 return;
1287 }
1288
1289 // If this condition is one of the special cases we handle, do special stuff
1290 // now.
1291 Value *CondVal = I.getCondition();
1292 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1293
1294 // If this is a series of conditions that are or'd or and'd together, emit
1295 // this as a sequence of branches instead of setcc's with and/or operations.
1296 // For example, instead of something like:
1297 // cmp A, B
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001298 // C = seteq
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001299 // cmp D, E
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001300 // F = setle
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001301 // or C, F
1302 // jnz foo
1303 // Emit:
1304 // cmp A, B
1305 // je foo
1306 // cmp D, E
1307 // jle foo
1308 //
1309 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001310 if (BOp->hasOneUse() &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001311 (BOp->getOpcode() == Instruction::And ||
1312 BOp->getOpcode() == Instruction::Or)) {
1313 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1314 // If the compares in later blocks need to use values not currently
1315 // exported from this block, export them now. This block should always
1316 // be the first entry.
1317 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001318
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001319 // Allow some cases to be rejected.
1320 if (ShouldEmitAsBranches(SwitchCases)) {
1321 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1322 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1323 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1324 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001325
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001326 // Emit the branch for this block.
1327 visitSwitchCase(SwitchCases[0]);
1328 SwitchCases.erase(SwitchCases.begin());
1329 return;
1330 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001331
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001332 // Okay, we decided not to do this, remove any inserted MBB's and clear
1333 // SwitchCases.
1334 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1335 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001336
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001337 SwitchCases.clear();
1338 }
1339 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001340
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001341 // Create a CaseBlock record representing this branch.
1342 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1343 NULL, Succ0MBB, Succ1MBB, CurMBB);
1344 // Use visitSwitchCase to actually insert the fast branch sequence for this
1345 // cond branch.
1346 visitSwitchCase(CB);
1347}
1348
1349/// visitSwitchCase - Emits the necessary code to represent a single node in
1350/// the binary search tree resulting from lowering a switch instruction.
1351void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1352 SDValue Cond;
1353 SDValue CondLHS = getValue(CB.CmpLHS);
Dale Johannesenf5d97892009-02-04 01:48:28 +00001354 DebugLoc dl = getCurDebugLoc();
Anton Korobeynikov23218582008-12-23 22:25:27 +00001355
1356 // Build the setcc now.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001357 if (CB.CmpMHS == NULL) {
1358 // Fold "(X == true)" to X and "(X == false)" to !X to
1359 // handle common cases produced by branch lowering.
1360 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1361 Cond = CondLHS;
1362 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1363 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001364 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001365 } else
Dale Johannesenf5d97892009-02-04 01:48:28 +00001366 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001367 } else {
1368 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1369
Anton Korobeynikov23218582008-12-23 22:25:27 +00001370 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1371 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001372
1373 SDValue CmpOp = getValue(CB.CmpMHS);
1374 MVT VT = CmpOp.getValueType();
1375
1376 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
Scott Michelfdc40a02009-02-17 22:15:04 +00001377 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
Dale Johannesenf5d97892009-02-04 01:48:28 +00001378 ISD::SETLE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001379 } else {
Dale Johannesenf5d97892009-02-04 01:48:28 +00001380 SDValue SUB = DAG.getNode(ISD::SUB, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001381 VT, CmpOp, DAG.getConstant(Low, VT));
Dale Johannesenf5d97892009-02-04 01:48:28 +00001382 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001383 DAG.getConstant(High-Low, VT), ISD::SETULE);
1384 }
1385 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001386
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001387 // Update successor info
1388 CurMBB->addSuccessor(CB.TrueBB);
1389 CurMBB->addSuccessor(CB.FalseBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001390
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001391 // Set NextBlock to be the MBB immediately after the current one, if any.
1392 // This is used to avoid emitting unnecessary branches to the next block.
1393 MachineBasicBlock *NextBlock = 0;
1394 MachineFunction::iterator BBI = CurMBB;
1395 if (++BBI != CurMBB->getParent()->end())
1396 NextBlock = BBI;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001397
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001398 // If the lhs block is the next block, invert the condition so that we can
1399 // fall through to the lhs instead of the rhs block.
1400 if (CB.TrueBB == NextBlock) {
1401 std::swap(CB.TrueBB, CB.FalseBB);
1402 SDValue True = DAG.getConstant(1, Cond.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001403 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001404 }
Dale Johannesenf5d97892009-02-04 01:48:28 +00001405 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001406 MVT::Other, getControlRoot(), Cond,
1407 DAG.getBasicBlock(CB.TrueBB));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001408
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001409 // If the branch was constant folded, fix up the CFG.
1410 if (BrCond.getOpcode() == ISD::BR) {
1411 CurMBB->removeSuccessor(CB.FalseBB);
1412 DAG.setRoot(BrCond);
1413 } else {
1414 // Otherwise, go ahead and insert the false branch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001415 if (BrCond == getControlRoot())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001416 CurMBB->removeSuccessor(CB.TrueBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001417
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001418 if (CB.FalseBB == NextBlock)
1419 DAG.setRoot(BrCond);
1420 else
Dale Johannesenf5d97892009-02-04 01:48:28 +00001421 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001422 DAG.getBasicBlock(CB.FalseBB)));
1423 }
1424}
1425
1426/// visitJumpTable - Emit JumpTable node in the current MBB
1427void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1428 // Emit the code for the jump table
1429 assert(JT.Reg != -1U && "Should lower JT Header first!");
1430 MVT PTy = TLI.getPointerTy();
Dale Johannesena04b7572009-02-03 23:04:43 +00001431 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1432 JT.Reg, PTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001433 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Scott Michelfdc40a02009-02-17 22:15:04 +00001434 DAG.setRoot(DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001435 MVT::Other, Index.getValue(1),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001436 Table, Index));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001437}
1438
1439/// visitJumpTableHeader - This function emits necessary code to produce index
1440/// in the JumpTable from switch case.
1441void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1442 JumpTableHeader &JTH) {
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001443 // Subtract the lowest switch case value from the value being switched on and
1444 // conditional branch to default mbb if the result is greater than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001445 // difference between smallest and largest cases.
1446 SDValue SwitchOp = getValue(JTH.SValue);
1447 MVT VT = SwitchOp.getValueType();
Dale Johannesen66978ee2009-01-31 02:22:37 +00001448 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001449 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001450
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001451 // The SDNode we just created, which holds the value being switched on minus
1452 // the the smallest case value, needs to be copied to a virtual register so it
1453 // can be used as an index into the jump table in a subsequent basic block.
1454 // This value may be smaller or larger than the target's pointer type, and
1455 // therefore require extension or truncating.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001456 if (VT.bitsGT(TLI.getPointerTy()))
Scott Michelfdc40a02009-02-17 22:15:04 +00001457 SwitchOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001458 TLI.getPointerTy(), SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001459 else
Scott Michelfdc40a02009-02-17 22:15:04 +00001460 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001461 TLI.getPointerTy(), SUB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001462
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001463 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001464 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1465 JumpTableReg, SwitchOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001466 JT.Reg = JumpTableReg;
1467
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001468 // Emit the range check for the jump table, and branch to the default block
1469 // for the switch statement if the value being switched on exceeds the largest
1470 // case in the switch.
Dale Johannesenf5d97892009-02-04 01:48:28 +00001471 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1472 TLI.getSetCCResultType(SUB.getValueType()), SUB,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001473 DAG.getConstant(JTH.Last-JTH.First,VT),
1474 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001475
1476 // Set NextBlock to be the MBB immediately after the current one, if any.
1477 // This is used to avoid emitting unnecessary branches to the next block.
1478 MachineBasicBlock *NextBlock = 0;
1479 MachineFunction::iterator BBI = CurMBB;
1480 if (++BBI != CurMBB->getParent()->end())
1481 NextBlock = BBI;
1482
Dale Johannesen66978ee2009-01-31 02:22:37 +00001483 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001484 MVT::Other, CopyTo, CMP,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001485 DAG.getBasicBlock(JT.Default));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001486
1487 if (JT.MBB == NextBlock)
1488 DAG.setRoot(BrCond);
1489 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001490 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001491 DAG.getBasicBlock(JT.MBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001492}
1493
1494/// visitBitTestHeader - This function emits necessary code to produce value
1495/// suitable for "bit tests"
1496void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1497 // Subtract the minimum value
1498 SDValue SwitchOp = getValue(B.SValue);
1499 MVT VT = SwitchOp.getValueType();
Dale Johannesen66978ee2009-01-31 02:22:37 +00001500 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001501 DAG.getConstant(B.First, VT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001502
1503 // Check range
Dale Johannesenf5d97892009-02-04 01:48:28 +00001504 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1505 TLI.getSetCCResultType(SUB.getValueType()),
1506 SUB, DAG.getConstant(B.Range, VT),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001507 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001508
1509 SDValue ShiftOp;
Duncan Sands92abc622009-01-31 15:50:11 +00001510 if (VT.bitsGT(TLI.getPointerTy()))
Scott Michelfdc40a02009-02-17 22:15:04 +00001511 ShiftOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00001512 TLI.getPointerTy(), SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001513 else
Scott Michelfdc40a02009-02-17 22:15:04 +00001514 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00001515 TLI.getPointerTy(), SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001516
Duncan Sands92abc622009-01-31 15:50:11 +00001517 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001518 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1519 B.Reg, ShiftOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001520
1521 // Set NextBlock to be the MBB immediately after the current one, if any.
1522 // This is used to avoid emitting unnecessary branches to the next block.
1523 MachineBasicBlock *NextBlock = 0;
1524 MachineFunction::iterator BBI = CurMBB;
1525 if (++BBI != CurMBB->getParent()->end())
1526 NextBlock = BBI;
1527
1528 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1529
1530 CurMBB->addSuccessor(B.Default);
1531 CurMBB->addSuccessor(MBB);
1532
Dale Johannesen66978ee2009-01-31 02:22:37 +00001533 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001534 MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001535 DAG.getBasicBlock(B.Default));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001536
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001537 if (MBB == NextBlock)
1538 DAG.setRoot(BrRange);
1539 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001540 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001541 DAG.getBasicBlock(MBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001542}
1543
1544/// visitBitTestCase - this function produces one "bit test"
1545void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1546 unsigned Reg,
1547 BitTestCase &B) {
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001548 // Make desired shift
Dale Johannesena04b7572009-02-03 23:04:43 +00001549 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
Duncan Sands92abc622009-01-31 15:50:11 +00001550 TLI.getPointerTy());
Scott Michelfdc40a02009-02-17 22:15:04 +00001551 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001552 TLI.getPointerTy(),
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001553 DAG.getConstant(1, TLI.getPointerTy()),
1554 ShiftOp);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001555
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001556 // Emit bit tests and jumps
Scott Michelfdc40a02009-02-17 22:15:04 +00001557 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001558 TLI.getPointerTy(), SwitchVal,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001559 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Dale Johannesenf5d97892009-02-04 01:48:28 +00001560 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1561 TLI.getSetCCResultType(AndOp.getValueType()),
Duncan Sands5480c042009-01-01 15:52:00 +00001562 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001563 ISD::SETNE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001564
1565 CurMBB->addSuccessor(B.TargetBB);
1566 CurMBB->addSuccessor(NextMBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001567
Dale Johannesen66978ee2009-01-31 02:22:37 +00001568 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001569 MVT::Other, getControlRoot(),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001570 AndCmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001571
1572 // Set NextBlock to be the MBB immediately after the current one, if any.
1573 // This is used to avoid emitting unnecessary branches to the next block.
1574 MachineBasicBlock *NextBlock = 0;
1575 MachineFunction::iterator BBI = CurMBB;
1576 if (++BBI != CurMBB->getParent()->end())
1577 NextBlock = BBI;
1578
1579 if (NextMBB == NextBlock)
1580 DAG.setRoot(BrAnd);
1581 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001582 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001583 DAG.getBasicBlock(NextMBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001584}
1585
1586void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1587 // Retrieve successors.
1588 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1589 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1590
Gabor Greifb67e6b32009-01-15 11:10:44 +00001591 const Value *Callee(I.getCalledValue());
1592 if (isa<InlineAsm>(Callee))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001593 visitInlineAsm(&I);
1594 else
Gabor Greifb67e6b32009-01-15 11:10:44 +00001595 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001596
1597 // If the value of the invoke is used outside of its defining block, make it
1598 // available as a virtual register.
Dan Gohmanad62f532009-04-23 23:13:24 +00001599 CopyToExportRegsIfNeeded(&I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001600
1601 // Update successor info
1602 CurMBB->addSuccessor(Return);
1603 CurMBB->addSuccessor(LandingPad);
1604
1605 // Drop into normal successor.
Scott Michelfdc40a02009-02-17 22:15:04 +00001606 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001607 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001608 DAG.getBasicBlock(Return)));
1609}
1610
1611void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1612}
1613
1614/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1615/// small case ranges).
1616bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1617 CaseRecVector& WorkList,
1618 Value* SV,
1619 MachineBasicBlock* Default) {
1620 Case& BackCase = *(CR.Range.second-1);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001621
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001622 // Size is the number of Cases represented by this range.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001623 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001624 if (Size > 3)
Anton Korobeynikov23218582008-12-23 22:25:27 +00001625 return false;
1626
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001627 // Get the MachineFunction which holds the current MBB. This is used when
1628 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001629 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001630
1631 // Figure out which block is immediately after the current one.
1632 MachineBasicBlock *NextBlock = 0;
1633 MachineFunction::iterator BBI = CR.CaseBB;
1634
1635 if (++BBI != CurMBB->getParent()->end())
1636 NextBlock = BBI;
1637
1638 // TODO: If any two of the cases has the same destination, and if one value
1639 // is the same as the other, but has one bit unset that the other has set,
1640 // use bit manipulation to do two compares at once. For example:
1641 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Anton Korobeynikov23218582008-12-23 22:25:27 +00001642
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001643 // Rearrange the case blocks so that the last one falls through if possible.
1644 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1645 // The last case block won't fall through into 'NextBlock' if we emit the
1646 // branches in this order. See if rearranging a case value would help.
1647 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1648 if (I->BB == NextBlock) {
1649 std::swap(*I, BackCase);
1650 break;
1651 }
1652 }
1653 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001654
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001655 // Create a CaseBlock record representing a conditional branch to
1656 // the Case's target mbb if the value being switched on SV is equal
1657 // to C.
1658 MachineBasicBlock *CurBlock = CR.CaseBB;
1659 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1660 MachineBasicBlock *FallThrough;
1661 if (I != E-1) {
1662 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1663 CurMF->insert(BBI, FallThrough);
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001664
1665 // Put SV in a virtual register to make it available from the new blocks.
1666 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001667 } else {
1668 // If the last case doesn't match, go to the default block.
1669 FallThrough = Default;
1670 }
1671
1672 Value *RHS, *LHS, *MHS;
1673 ISD::CondCode CC;
1674 if (I->High == I->Low) {
1675 // This is just small small case range :) containing exactly 1 case
1676 CC = ISD::SETEQ;
1677 LHS = SV; RHS = I->High; MHS = NULL;
1678 } else {
1679 CC = ISD::SETLE;
1680 LHS = I->Low; MHS = SV; RHS = I->High;
1681 }
1682 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001683
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001684 // If emitting the first comparison, just call visitSwitchCase to emit the
1685 // code into the current block. Otherwise, push the CaseBlock onto the
1686 // vector to be later processed by SDISel, and insert the node's MBB
1687 // before the next MBB.
1688 if (CurBlock == CurMBB)
1689 visitSwitchCase(CB);
1690 else
1691 SwitchCases.push_back(CB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001692
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001693 CurBlock = FallThrough;
1694 }
1695
1696 return true;
1697}
1698
1699static inline bool areJTsAllowed(const TargetLowering &TLI) {
1700 return !DisableJumpTables &&
Dan Gohmanf560ffa2009-01-28 17:46:25 +00001701 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1702 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001703}
Anton Korobeynikov23218582008-12-23 22:25:27 +00001704
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001705static APInt ComputeRange(const APInt &First, const APInt &Last) {
1706 APInt LastExt(Last), FirstExt(First);
1707 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1708 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1709 return (LastExt - FirstExt + 1ULL);
1710}
1711
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001712/// handleJTSwitchCase - Emit jumptable for current switch case range
1713bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1714 CaseRecVector& WorkList,
1715 Value* SV,
1716 MachineBasicBlock* Default) {
1717 Case& FrontCase = *CR.Range.first;
1718 Case& BackCase = *(CR.Range.second-1);
1719
Anton Korobeynikov23218582008-12-23 22:25:27 +00001720 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1721 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001722
Anton Korobeynikov23218582008-12-23 22:25:27 +00001723 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001724 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1725 I!=E; ++I)
1726 TSize += I->size();
1727
1728 if (!areJTsAllowed(TLI) || TSize <= 3)
1729 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001730
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001731 APInt Range = ComputeRange(First, Last);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001732 double Density = (double)TSize / Range.roundToDouble();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001733 if (Density < 0.4)
1734 return false;
1735
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001736 DEBUG(errs() << "Lowering jump table\n"
1737 << "First entry: " << First << ". Last entry: " << Last << '\n'
1738 << "Range: " << Range
1739 << "Size: " << TSize << ". Density: " << Density << "\n\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001740
1741 // Get the MachineFunction which holds the current MBB. This is used when
1742 // inserting any additional MBBs necessary to represent the switch.
1743 MachineFunction *CurMF = CurMBB->getParent();
1744
1745 // Figure out which block is immediately after the current one.
1746 MachineBasicBlock *NextBlock = 0;
1747 MachineFunction::iterator BBI = CR.CaseBB;
1748
1749 if (++BBI != CurMBB->getParent()->end())
1750 NextBlock = BBI;
1751
1752 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1753
1754 // Create a new basic block to hold the code for loading the address
1755 // of the jump table, and jumping to it. Update successor information;
1756 // we will either branch to the default case for the switch, or the jump
1757 // table.
1758 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1759 CurMF->insert(BBI, JumpTableBB);
1760 CR.CaseBB->addSuccessor(Default);
1761 CR.CaseBB->addSuccessor(JumpTableBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001762
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001763 // Build a vector of destination BBs, corresponding to each target
1764 // of the jump table. If the value of the jump table slot corresponds to
1765 // a case statement, push the case's BB onto the vector, otherwise, push
1766 // the default BB.
1767 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001768 APInt TEI = First;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001769 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001770 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1771 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1772
1773 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001774 DestBBs.push_back(I->BB);
1775 if (TEI==High)
1776 ++I;
1777 } else {
1778 DestBBs.push_back(Default);
1779 }
1780 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001781
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001782 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001783 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1784 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001785 E = DestBBs.end(); I != E; ++I) {
1786 if (!SuccsHandled[(*I)->getNumber()]) {
1787 SuccsHandled[(*I)->getNumber()] = true;
1788 JumpTableBB->addSuccessor(*I);
1789 }
1790 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001791
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001792 // Create a jump table index for this jump table, or return an existing
1793 // one.
1794 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001795
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001796 // Set the jump table information so that we can codegen it as a second
1797 // MachineBasicBlock
1798 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1799 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1800 if (CR.CaseBB == CurMBB)
1801 visitJumpTableHeader(JT, JTH);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001802
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001803 JTCases.push_back(JumpTableBlock(JTH, JT));
1804
1805 return true;
1806}
1807
1808/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1809/// 2 subtrees.
1810bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1811 CaseRecVector& WorkList,
1812 Value* SV,
1813 MachineBasicBlock* Default) {
1814 // Get the MachineFunction which holds the current MBB. This is used when
1815 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001816 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001817
1818 // Figure out which block is immediately after the current one.
1819 MachineBasicBlock *NextBlock = 0;
1820 MachineFunction::iterator BBI = CR.CaseBB;
1821
1822 if (++BBI != CurMBB->getParent()->end())
1823 NextBlock = BBI;
1824
1825 Case& FrontCase = *CR.Range.first;
1826 Case& BackCase = *(CR.Range.second-1);
1827 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1828
1829 // Size is the number of Cases represented by this range.
1830 unsigned Size = CR.Range.second - CR.Range.first;
1831
Anton Korobeynikov23218582008-12-23 22:25:27 +00001832 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1833 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001834 double FMetric = 0;
1835 CaseItr Pivot = CR.Range.first + Size/2;
1836
1837 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1838 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001839 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001840 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1841 I!=E; ++I)
1842 TSize += I->size();
1843
Anton Korobeynikov23218582008-12-23 22:25:27 +00001844 size_t LSize = FrontCase.size();
1845 size_t RSize = TSize-LSize;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001846 DEBUG(errs() << "Selecting best pivot: \n"
1847 << "First: " << First << ", Last: " << Last <<'\n'
1848 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001849 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1850 J!=E; ++I, ++J) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001851 const APInt& LEnd = cast<ConstantInt>(I->High)->getValue();
1852 const APInt& RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001853 APInt Range = ComputeRange(LEnd, RBegin);
1854 assert((Range - 2ULL).isNonNegative() &&
1855 "Invalid case distance");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001856 double LDensity = (double)LSize / (LEnd - First + 1ULL).roundToDouble();
1857 double RDensity = (double)RSize / (Last - RBegin + 1ULL).roundToDouble();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001858 double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001859 // Should always split in some non-trivial place
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001860 DEBUG(errs() <<"=>Step\n"
1861 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1862 << "LDensity: " << LDensity
1863 << ", RDensity: " << RDensity << '\n'
1864 << "Metric: " << Metric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001865 if (FMetric < Metric) {
1866 Pivot = J;
1867 FMetric = Metric;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001868 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001869 }
1870
1871 LSize += J->size();
1872 RSize -= J->size();
1873 }
1874 if (areJTsAllowed(TLI)) {
1875 // If our case is dense we *really* should handle it earlier!
1876 assert((FMetric > 0) && "Should handle dense range earlier!");
1877 } else {
1878 Pivot = CR.Range.first + Size/2;
1879 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001880
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001881 CaseRange LHSR(CR.Range.first, Pivot);
1882 CaseRange RHSR(Pivot, CR.Range.second);
1883 Constant *C = Pivot->Low;
1884 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001885
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001886 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001887 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001888 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001889 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001890 // Pivot's Value, then we can branch directly to the LHS's Target,
1891 // rather than creating a leaf node for it.
1892 if ((LHSR.second - LHSR.first) == 1 &&
1893 LHSR.first->High == CR.GE &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001894 cast<ConstantInt>(C)->getValue() ==
1895 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001896 TrueBB = LHSR.first->BB;
1897 } else {
1898 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1899 CurMF->insert(BBI, TrueBB);
1900 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001901
1902 // Put SV in a virtual register to make it available from the new blocks.
1903 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001904 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001905
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001906 // Similar to the optimization above, if the Value being switched on is
1907 // known to be less than the Constant CR.LT, and the current Case Value
1908 // is CR.LT - 1, then we can branch directly to the target block for
1909 // the current Case Value, rather than emitting a RHS leaf node for it.
1910 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001911 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1912 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001913 FalseBB = RHSR.first->BB;
1914 } else {
1915 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1916 CurMF->insert(BBI, FalseBB);
1917 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001918
1919 // Put SV in a virtual register to make it available from the new blocks.
1920 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001921 }
1922
1923 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001924 // the LHS node if the value being switched on SV is less than C.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001925 // Otherwise, branch to LHS.
1926 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1927
1928 if (CR.CaseBB == CurMBB)
1929 visitSwitchCase(CB);
1930 else
1931 SwitchCases.push_back(CB);
1932
1933 return true;
1934}
1935
1936/// handleBitTestsSwitchCase - if current case range has few destination and
1937/// range span less, than machine word bitwidth, encode case range into series
1938/// of masks and emit bit tests with these masks.
1939bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1940 CaseRecVector& WorkList,
1941 Value* SV,
1942 MachineBasicBlock* Default){
1943 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1944
1945 Case& FrontCase = *CR.Range.first;
1946 Case& BackCase = *(CR.Range.second-1);
1947
1948 // Get the MachineFunction which holds the current MBB. This is used when
1949 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001950 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001951
Anton Korobeynikovd34167a2009-05-08 18:51:34 +00001952 // If target does not have legal shift left, do not emit bit tests at all.
1953 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
1954 return false;
1955
Anton Korobeynikov23218582008-12-23 22:25:27 +00001956 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001957 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1958 I!=E; ++I) {
1959 // Single case counts one, case range - two.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001960 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001961 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001962
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001963 // Count unique destinations
1964 SmallSet<MachineBasicBlock*, 4> Dests;
1965 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1966 Dests.insert(I->BB);
1967 if (Dests.size() > 3)
1968 // Don't bother the code below, if there are too much unique destinations
1969 return false;
1970 }
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001971 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1972 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001973
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001974 // Compute span of values.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001975 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1976 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001977 APInt cmpRange = maxValue - minValue;
1978
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001979 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1980 << "Low bound: " << minValue << '\n'
1981 << "High bound: " << maxValue << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001982
1983 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001984 (!(Dests.size() == 1 && numCmps >= 3) &&
1985 !(Dests.size() == 2 && numCmps >= 5) &&
1986 !(Dests.size() >= 3 && numCmps >= 6)))
1987 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001988
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001989 DEBUG(errs() << "Emitting bit tests\n");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001990 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1991
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001992 // Optimize the case where all the case values fit in a
1993 // word without having to subtract minValue. In this case,
1994 // we can optimize away the subtraction.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001995 if (minValue.isNonNegative() &&
1996 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1997 cmpRange = maxValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001998 } else {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001999 lowBound = minValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002000 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002001
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002002 CaseBitsVector CasesBits;
2003 unsigned i, count = 0;
2004
2005 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2006 MachineBasicBlock* Dest = I->BB;
2007 for (i = 0; i < count; ++i)
2008 if (Dest == CasesBits[i].BB)
2009 break;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002010
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002011 if (i == count) {
2012 assert((count < 3) && "Too much destinations to test!");
2013 CasesBits.push_back(CaseBits(0, Dest, 0));
2014 count++;
2015 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002016
2017 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2018 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2019
2020 uint64_t lo = (lowValue - lowBound).getZExtValue();
2021 uint64_t hi = (highValue - lowBound).getZExtValue();
2022
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002023 for (uint64_t j = lo; j <= hi; j++) {
2024 CasesBits[i].Mask |= 1ULL << j;
2025 CasesBits[i].Bits++;
2026 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002027
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002028 }
2029 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov23218582008-12-23 22:25:27 +00002030
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002031 BitTestInfo BTC;
2032
2033 // Figure out which block is immediately after the current one.
2034 MachineFunction::iterator BBI = CR.CaseBB;
2035 ++BBI;
2036
2037 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2038
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002039 DEBUG(errs() << "Cases:\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002040 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002041 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
2042 << ", Bits: " << CasesBits[i].Bits
2043 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002044
2045 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2046 CurMF->insert(BBI, CaseBB);
2047 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2048 CaseBB,
2049 CasesBits[i].BB));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00002050
2051 // Put SV in a virtual register to make it available from the new blocks.
2052 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002053 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002054
2055 BitTestBlock BTB(lowBound, cmpRange, SV,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002056 -1U, (CR.CaseBB == CurMBB),
2057 CR.CaseBB, Default, BTC);
2058
2059 if (CR.CaseBB == CurMBB)
2060 visitBitTestHeader(BTB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002061
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002062 BitTestCases.push_back(BTB);
2063
2064 return true;
2065}
2066
2067
2068/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov23218582008-12-23 22:25:27 +00002069size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002070 const SwitchInst& SI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00002071 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002072
2073 // Start with "simple" cases
Anton Korobeynikov23218582008-12-23 22:25:27 +00002074 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002075 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2076 Cases.push_back(Case(SI.getSuccessorValue(i),
2077 SI.getSuccessorValue(i),
2078 SMBB));
2079 }
2080 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2081
2082 // Merge case into clusters
Anton Korobeynikov23218582008-12-23 22:25:27 +00002083 if (Cases.size() >= 2)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002084 // Must recompute end() each iteration because it may be
2085 // invalidated by erase if we hold on to it
Anton Korobeynikov23218582008-12-23 22:25:27 +00002086 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
2087 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2088 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002089 MachineBasicBlock* nextBB = J->BB;
2090 MachineBasicBlock* currentBB = I->BB;
2091
2092 // If the two neighboring cases go to the same destination, merge them
2093 // into a single case.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002094 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002095 I->High = J->High;
2096 J = Cases.erase(J);
2097 } else {
2098 I = J++;
2099 }
2100 }
2101
2102 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2103 if (I->Low != I->High)
2104 // A range counts double, since it requires two compares.
2105 ++numCmps;
2106 }
2107
2108 return numCmps;
2109}
2110
Anton Korobeynikov23218582008-12-23 22:25:27 +00002111void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002112 // Figure out which block is immediately after the current one.
2113 MachineBasicBlock *NextBlock = 0;
2114 MachineFunction::iterator BBI = CurMBB;
2115
2116 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2117
2118 // If there is only the default destination, branch to it if it is not the
2119 // next basic block. Otherwise, just fall through.
2120 if (SI.getNumOperands() == 2) {
2121 // Update machine-CFG edges.
2122
2123 // If this is not a fall-through branch, emit the branch.
2124 CurMBB->addSuccessor(Default);
2125 if (Default != NextBlock)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002126 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002127 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002128 DAG.getBasicBlock(Default)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002129 return;
2130 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002131
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002132 // If there are any non-default case statements, create a vector of Cases
2133 // representing each one, and sort the vector so that we can efficiently
2134 // create a binary search tree from them.
2135 CaseVector Cases;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002136 size_t numCmps = Clusterify(Cases, SI);
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002137 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2138 << ". Total compares: " << numCmps << '\n');
Devang Patel8a84e442009-01-05 17:31:22 +00002139 numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002140
2141 // Get the Value to be switched on and default basic blocks, which will be
2142 // inserted into CaseBlock records, representing basic blocks in the binary
2143 // search tree.
2144 Value *SV = SI.getOperand(0);
2145
2146 // Push the initial CaseRec onto the worklist
2147 CaseRecVector WorkList;
2148 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2149
2150 while (!WorkList.empty()) {
2151 // Grab a record representing a case range to process off the worklist
2152 CaseRec CR = WorkList.back();
2153 WorkList.pop_back();
2154
2155 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2156 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002157
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002158 // If the range has few cases (two or less) emit a series of specific
2159 // tests.
2160 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2161 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002162
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002163 // If the switch has more than 5 blocks, and at least 40% dense, and the
2164 // target supports indirect branches, then emit a jump table rather than
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002165 // lowering the switch to a binary tree of conditional branches.
2166 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2167 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002168
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002169 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2170 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2171 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2172 }
2173}
2174
2175
2176void SelectionDAGLowering::visitSub(User &I) {
2177 // -0.0 - X --> fneg
2178 const Type *Ty = I.getType();
2179 if (isa<VectorType>(Ty)) {
2180 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2181 const VectorType *DestTy = cast<VectorType>(I.getType());
2182 const Type *ElTy = DestTy->getElementType();
2183 if (ElTy->isFloatingPoint()) {
2184 unsigned VL = DestTy->getNumElements();
2185 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2186 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2187 if (CV == CNZ) {
2188 SDValue Op2 = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002189 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002190 Op2.getValueType(), Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002191 return;
2192 }
2193 }
2194 }
2195 }
2196 if (Ty->isFloatingPoint()) {
2197 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2198 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2199 SDValue Op2 = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002200 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002201 Op2.getValueType(), Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002202 return;
2203 }
2204 }
2205
2206 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2207}
2208
2209void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2210 SDValue Op1 = getValue(I.getOperand(0));
2211 SDValue Op2 = getValue(I.getOperand(1));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002212
Scott Michelfdc40a02009-02-17 22:15:04 +00002213 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002214 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002215}
2216
2217void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2218 SDValue Op1 = getValue(I.getOperand(0));
2219 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman57fc82d2009-04-09 03:51:29 +00002220 if (!isa<VectorType>(I.getType()) &&
2221 Op2.getValueType() != TLI.getShiftAmountTy()) {
2222 // If the operand is smaller than the shift count type, promote it.
2223 if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2224 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2225 TLI.getShiftAmountTy(), Op2);
2226 // If the operand is larger than the shift count type but the shift
2227 // count type has enough bits to represent any shift value, truncate
2228 // it now. This is a common case and it exposes the truncate to
2229 // optimization early.
2230 else if (TLI.getShiftAmountTy().getSizeInBits() >=
2231 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2232 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2233 TLI.getShiftAmountTy(), Op2);
2234 // Otherwise we'll need to temporarily settle for some other
2235 // convenient type; type legalization will make adjustments as
2236 // needed.
2237 else if (TLI.getPointerTy().bitsLT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002238 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002239 TLI.getPointerTy(), Op2);
2240 else if (TLI.getPointerTy().bitsGT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002241 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002242 TLI.getPointerTy(), Op2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002243 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002244
Scott Michelfdc40a02009-02-17 22:15:04 +00002245 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002246 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002247}
2248
2249void SelectionDAGLowering::visitICmp(User &I) {
2250 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2251 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2252 predicate = IC->getPredicate();
2253 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2254 predicate = ICmpInst::Predicate(IC->getPredicate());
2255 SDValue Op1 = getValue(I.getOperand(0));
2256 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002257 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dale Johannesenf5d97892009-02-04 01:48:28 +00002258 setValue(&I, DAG.getSetCC(getCurDebugLoc(),MVT::i1, Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002259}
2260
2261void SelectionDAGLowering::visitFCmp(User &I) {
2262 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2263 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2264 predicate = FC->getPredicate();
2265 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2266 predicate = FCmpInst::Predicate(FC->getPredicate());
2267 SDValue Op1 = getValue(I.getOperand(0));
2268 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002269 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dale Johannesenf5d97892009-02-04 01:48:28 +00002270 setValue(&I, DAG.getSetCC(getCurDebugLoc(), MVT::i1, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002271}
2272
2273void SelectionDAGLowering::visitVICmp(User &I) {
2274 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2275 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2276 predicate = IC->getPredicate();
2277 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2278 predicate = ICmpInst::Predicate(IC->getPredicate());
2279 SDValue Op1 = getValue(I.getOperand(0));
2280 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002281 ISD::CondCode Opcode = getICmpCondCode(predicate);
Scott Michelfdc40a02009-02-17 22:15:04 +00002282 setValue(&I, DAG.getVSetCC(getCurDebugLoc(), Op1.getValueType(),
Dale Johannesenf5d97892009-02-04 01:48:28 +00002283 Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002284}
2285
2286void SelectionDAGLowering::visitVFCmp(User &I) {
2287 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2288 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2289 predicate = FC->getPredicate();
2290 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2291 predicate = FCmpInst::Predicate(FC->getPredicate());
2292 SDValue Op1 = getValue(I.getOperand(0));
2293 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002294 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002295 MVT DestVT = TLI.getValueType(I.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002296
Dale Johannesenf5d97892009-02-04 01:48:28 +00002297 setValue(&I, DAG.getVSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002298}
2299
2300void SelectionDAGLowering::visitSelect(User &I) {
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002301 SmallVector<MVT, 4> ValueVTs;
2302 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2303 unsigned NumValues = ValueVTs.size();
2304 if (NumValues != 0) {
2305 SmallVector<SDValue, 4> Values(NumValues);
2306 SDValue Cond = getValue(I.getOperand(0));
2307 SDValue TrueVal = getValue(I.getOperand(1));
2308 SDValue FalseVal = getValue(I.getOperand(2));
2309
2310 for (unsigned i = 0; i != NumValues; ++i)
Scott Michelfdc40a02009-02-17 22:15:04 +00002311 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002312 TrueVal.getValueType(), Cond,
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002313 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2314 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2315
Scott Michelfdc40a02009-02-17 22:15:04 +00002316 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002317 DAG.getVTList(&ValueVTs[0], NumValues),
2318 &Values[0], NumValues));
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002319 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002320}
2321
2322
2323void SelectionDAGLowering::visitTrunc(User &I) {
2324 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2325 SDValue N = getValue(I.getOperand(0));
2326 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002327 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002328}
2329
2330void SelectionDAGLowering::visitZExt(User &I) {
2331 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2332 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2333 SDValue N = getValue(I.getOperand(0));
2334 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002335 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002336}
2337
2338void SelectionDAGLowering::visitSExt(User &I) {
2339 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2340 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2341 SDValue N = getValue(I.getOperand(0));
2342 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002343 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002344}
2345
2346void SelectionDAGLowering::visitFPTrunc(User &I) {
2347 // FPTrunc is never a no-op cast, no need to check
2348 SDValue N = getValue(I.getOperand(0));
2349 MVT DestVT = TLI.getValueType(I.getType());
Scott Michelfdc40a02009-02-17 22:15:04 +00002350 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002351 DestVT, N, DAG.getIntPtrConstant(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002352}
2353
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002354void SelectionDAGLowering::visitFPExt(User &I){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002355 // FPTrunc is never a no-op cast, no need to check
2356 SDValue N = getValue(I.getOperand(0));
2357 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002358 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002359}
2360
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002361void SelectionDAGLowering::visitFPToUI(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002362 // FPToUI is never a no-op cast, no need to check
2363 SDValue N = getValue(I.getOperand(0));
2364 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002365 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002366}
2367
2368void SelectionDAGLowering::visitFPToSI(User &I) {
2369 // FPToSI is never a no-op cast, no need to check
2370 SDValue N = getValue(I.getOperand(0));
2371 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002372 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002373}
2374
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002375void SelectionDAGLowering::visitUIToFP(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002376 // UIToFP is never a no-op cast, no need to check
2377 SDValue N = getValue(I.getOperand(0));
2378 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002379 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002380}
2381
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002382void SelectionDAGLowering::visitSIToFP(User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002383 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002384 SDValue N = getValue(I.getOperand(0));
2385 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002386 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002387}
2388
2389void SelectionDAGLowering::visitPtrToInt(User &I) {
2390 // What to do depends on the size of the integer and the size of the pointer.
2391 // We can either truncate, zero extend, or no-op, accordingly.
2392 SDValue N = getValue(I.getOperand(0));
2393 MVT SrcVT = N.getValueType();
2394 MVT DestVT = TLI.getValueType(I.getType());
2395 SDValue Result;
2396 if (DestVT.bitsLT(SrcVT))
Dale Johannesen66978ee2009-01-31 02:22:37 +00002397 Result = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002398 else
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002399 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
Dale Johannesen66978ee2009-01-31 02:22:37 +00002400 Result = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002401 setValue(&I, Result);
2402}
2403
2404void SelectionDAGLowering::visitIntToPtr(User &I) {
2405 // What to do depends on the size of the integer and the size of the pointer.
2406 // We can either truncate, zero extend, or no-op, accordingly.
2407 SDValue N = getValue(I.getOperand(0));
2408 MVT SrcVT = N.getValueType();
2409 MVT DestVT = TLI.getValueType(I.getType());
2410 if (DestVT.bitsLT(SrcVT))
Dale Johannesen66978ee2009-01-31 02:22:37 +00002411 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002412 else
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002413 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
Scott Michelfdc40a02009-02-17 22:15:04 +00002414 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002415 DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002416}
2417
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002418void SelectionDAGLowering::visitBitCast(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002419 SDValue N = getValue(I.getOperand(0));
2420 MVT DestVT = TLI.getValueType(I.getType());
2421
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002422 // BitCast assures us that source and destination are the same size so this
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002423 // is either a BIT_CONVERT or a no-op.
2424 if (DestVT != N.getValueType())
Scott Michelfdc40a02009-02-17 22:15:04 +00002425 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002426 DestVT, N)); // convert types
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002427 else
2428 setValue(&I, N); // noop cast.
2429}
2430
2431void SelectionDAGLowering::visitInsertElement(User &I) {
2432 SDValue InVec = getValue(I.getOperand(0));
2433 SDValue InVal = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002434 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002435 TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002436 getValue(I.getOperand(2)));
2437
Scott Michelfdc40a02009-02-17 22:15:04 +00002438 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002439 TLI.getValueType(I.getType()),
2440 InVec, InVal, InIdx));
2441}
2442
2443void SelectionDAGLowering::visitExtractElement(User &I) {
2444 SDValue InVec = getValue(I.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00002445 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002446 TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002447 getValue(I.getOperand(1)));
Dale Johannesen66978ee2009-01-31 02:22:37 +00002448 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002449 TLI.getValueType(I.getType()), InVec, InIdx));
2450}
2451
Mon P Wangaeb06d22008-11-10 04:46:22 +00002452
2453// Utility for visitShuffleVector - Returns true if the mask is mask starting
2454// from SIndx and increasing to the element length (undefs are allowed).
Nate Begeman5a5ca152009-04-29 05:20:52 +00002455static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2456 unsigned MaskNumElts = Mask.size();
2457 for (unsigned i = 0; i != MaskNumElts; ++i)
2458 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
Nate Begeman9008ca62009-04-27 18:41:29 +00002459 return false;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002460 return true;
2461}
2462
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002463void SelectionDAGLowering::visitShuffleVector(User &I) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002464 SmallVector<int, 8> Mask;
Mon P Wang230e4fa2008-11-21 04:25:21 +00002465 SDValue Src1 = getValue(I.getOperand(0));
2466 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002467
Nate Begeman9008ca62009-04-27 18:41:29 +00002468 // Convert the ConstantVector mask operand into an array of ints, with -1
2469 // representing undef values.
2470 SmallVector<Constant*, 8> MaskElts;
2471 cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
Nate Begeman5a5ca152009-04-29 05:20:52 +00002472 unsigned MaskNumElts = MaskElts.size();
2473 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002474 if (isa<UndefValue>(MaskElts[i]))
2475 Mask.push_back(-1);
2476 else
2477 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2478 }
2479
Mon P Wangaeb06d22008-11-10 04:46:22 +00002480 MVT VT = TLI.getValueType(I.getType());
Mon P Wang230e4fa2008-11-21 04:25:21 +00002481 MVT SrcVT = Src1.getValueType();
Nate Begeman5a5ca152009-04-29 05:20:52 +00002482 unsigned SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002483
Mon P Wangc7849c22008-11-16 05:06:27 +00002484 if (SrcNumElts == MaskNumElts) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002485 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2486 &Mask[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002487 return;
2488 }
2489
2490 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002491 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2492 // Mask is longer than the source vectors and is a multiple of the source
2493 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang230e4fa2008-11-21 04:25:21 +00002494 // lengths match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002495 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2496 // The shuffle is concatenating two vectors together.
Scott Michelfdc40a02009-02-17 22:15:04 +00002497 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002498 VT, Src1, Src2));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002499 return;
2500 }
2501
Mon P Wangc7849c22008-11-16 05:06:27 +00002502 // Pad both vectors with undefs to make them the same length as the mask.
2503 unsigned NumConcat = MaskNumElts / SrcNumElts;
Nate Begeman9008ca62009-04-27 18:41:29 +00002504 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2505 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
Dale Johannesene8d72302009-02-06 23:05:02 +00002506 SDValue UndefVal = DAG.getUNDEF(SrcVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002507
Nate Begeman9008ca62009-04-27 18:41:29 +00002508 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2509 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002510 MOps1[0] = Src1;
2511 MOps2[0] = Src2;
Nate Begeman9008ca62009-04-27 18:41:29 +00002512
2513 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2514 getCurDebugLoc(), VT,
2515 &MOps1[0], NumConcat);
2516 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2517 getCurDebugLoc(), VT,
2518 &MOps2[0], NumConcat);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002519
Mon P Wangaeb06d22008-11-10 04:46:22 +00002520 // Readjust mask for new input vector length.
Nate Begeman9008ca62009-04-27 18:41:29 +00002521 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002522 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002523 int Idx = Mask[i];
Nate Begeman5a5ca152009-04-29 05:20:52 +00002524 if (Idx < (int)SrcNumElts)
Nate Begeman9008ca62009-04-27 18:41:29 +00002525 MappedOps.push_back(Idx);
2526 else
2527 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002528 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002529 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2530 &MappedOps[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002531 return;
2532 }
2533
Mon P Wangc7849c22008-11-16 05:06:27 +00002534 if (SrcNumElts > MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002535 // Analyze the access pattern of the vector to see if we can extract
2536 // two subvectors and do the shuffle. The analysis is done by calculating
2537 // the range of elements the mask access on both vectors.
2538 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2539 int MaxRange[2] = {-1, -1};
2540
Nate Begeman5a5ca152009-04-29 05:20:52 +00002541 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002542 int Idx = Mask[i];
2543 int Input = 0;
2544 if (Idx < 0)
2545 continue;
2546
Nate Begeman5a5ca152009-04-29 05:20:52 +00002547 if (Idx >= (int)SrcNumElts) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002548 Input = 1;
2549 Idx -= SrcNumElts;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002550 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002551 if (Idx > MaxRange[Input])
2552 MaxRange[Input] = Idx;
2553 if (Idx < MinRange[Input])
2554 MinRange[Input] = Idx;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002555 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002556
Mon P Wangc7849c22008-11-16 05:06:27 +00002557 // Check if the access is smaller than the vector size and can we find
2558 // a reasonable extract index.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002559 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
Mon P Wangc7849c22008-11-16 05:06:27 +00002560 int StartIdx[2]; // StartIdx to extract from
2561 for (int Input=0; Input < 2; ++Input) {
Nate Begeman5a5ca152009-04-29 05:20:52 +00002562 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002563 RangeUse[Input] = 0; // Unused
2564 StartIdx[Input] = 0;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002565 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002566 // Fits within range but we should see if we can find a good
Mon P Wang230e4fa2008-11-21 04:25:21 +00002567 // start index that is a multiple of the mask length.
Nate Begeman5a5ca152009-04-29 05:20:52 +00002568 if (MaxRange[Input] < (int)MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002569 RangeUse[Input] = 1; // Extract from beginning of the vector
2570 StartIdx[Input] = 0;
2571 } else {
2572 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002573 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002574 StartIdx[Input] + MaskNumElts < SrcNumElts)
Mon P Wangc7849c22008-11-16 05:06:27 +00002575 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002576 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002577 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002578 }
2579
2580 if (RangeUse[0] == 0 && RangeUse[0] == 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002581 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
Mon P Wangc7849c22008-11-16 05:06:27 +00002582 return;
2583 }
2584 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2585 // Extract appropriate subvector and generate a vector shuffle
2586 for (int Input=0; Input < 2; ++Input) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002587 SDValue& Src = Input == 0 ? Src1 : Src2;
Mon P Wangc7849c22008-11-16 05:06:27 +00002588 if (RangeUse[Input] == 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002589 Src = DAG.getUNDEF(VT);
Mon P Wangc7849c22008-11-16 05:06:27 +00002590 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002591 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002592 Src, DAG.getIntPtrConstant(StartIdx[Input]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002593 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002594 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002595 // Calculate new mask.
Nate Begeman9008ca62009-04-27 18:41:29 +00002596 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002597 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002598 int Idx = Mask[i];
2599 if (Idx < 0)
2600 MappedOps.push_back(Idx);
Nate Begeman5a5ca152009-04-29 05:20:52 +00002601 else if (Idx < (int)SrcNumElts)
Nate Begeman9008ca62009-04-27 18:41:29 +00002602 MappedOps.push_back(Idx - StartIdx[0]);
2603 else
2604 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
Mon P Wangc7849c22008-11-16 05:06:27 +00002605 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002606 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2607 &MappedOps[0]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002608 return;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002609 }
2610 }
2611
Mon P Wangc7849c22008-11-16 05:06:27 +00002612 // We can't use either concat vectors or extract subvectors so fall back to
2613 // replacing the shuffle with extract and build vector.
2614 // to insert and build vector.
Mon P Wangaeb06d22008-11-10 04:46:22 +00002615 MVT EltVT = VT.getVectorElementType();
2616 MVT PtrVT = TLI.getPointerTy();
2617 SmallVector<SDValue,8> Ops;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002618 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002619 if (Mask[i] < 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002620 Ops.push_back(DAG.getUNDEF(EltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002621 } else {
Nate Begeman9008ca62009-04-27 18:41:29 +00002622 int Idx = Mask[i];
Nate Begeman5a5ca152009-04-29 05:20:52 +00002623 if (Idx < (int)SrcNumElts)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002624 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002625 EltVT, Src1, DAG.getConstant(Idx, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002626 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00002627 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Scott Michelfdc40a02009-02-17 22:15:04 +00002628 EltVT, Src2,
Mon P Wangc7849c22008-11-16 05:06:27 +00002629 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002630 }
2631 }
Evan Chenga87008d2009-02-25 22:49:59 +00002632 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2633 VT, &Ops[0], Ops.size()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002634}
2635
2636void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2637 const Value *Op0 = I.getOperand(0);
2638 const Value *Op1 = I.getOperand(1);
2639 const Type *AggTy = I.getType();
2640 const Type *ValTy = Op1->getType();
2641 bool IntoUndef = isa<UndefValue>(Op0);
2642 bool FromUndef = isa<UndefValue>(Op1);
2643
2644 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2645 I.idx_begin(), I.idx_end());
2646
2647 SmallVector<MVT, 4> AggValueVTs;
2648 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2649 SmallVector<MVT, 4> ValValueVTs;
2650 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2651
2652 unsigned NumAggValues = AggValueVTs.size();
2653 unsigned NumValValues = ValValueVTs.size();
2654 SmallVector<SDValue, 4> Values(NumAggValues);
2655
2656 SDValue Agg = getValue(Op0);
2657 SDValue Val = getValue(Op1);
2658 unsigned i = 0;
2659 // Copy the beginning value(s) from the original aggregate.
2660 for (; i != LinearIndex; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002661 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002662 SDValue(Agg.getNode(), Agg.getResNo() + i);
2663 // Copy values from the inserted value(s).
2664 for (; i != LinearIndex + NumValValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002665 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002666 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2667 // Copy remaining value(s) from the original aggregate.
2668 for (; i != NumAggValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002669 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002670 SDValue(Agg.getNode(), Agg.getResNo() + i);
2671
Scott Michelfdc40a02009-02-17 22:15:04 +00002672 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002673 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2674 &Values[0], NumAggValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002675}
2676
2677void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2678 const Value *Op0 = I.getOperand(0);
2679 const Type *AggTy = Op0->getType();
2680 const Type *ValTy = I.getType();
2681 bool OutOfUndef = isa<UndefValue>(Op0);
2682
2683 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2684 I.idx_begin(), I.idx_end());
2685
2686 SmallVector<MVT, 4> ValValueVTs;
2687 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2688
2689 unsigned NumValValues = ValValueVTs.size();
2690 SmallVector<SDValue, 4> Values(NumValValues);
2691
2692 SDValue Agg = getValue(Op0);
2693 // Copy out the selected value(s).
2694 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2695 Values[i - LinearIndex] =
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002696 OutOfUndef ?
Dale Johannesene8d72302009-02-06 23:05:02 +00002697 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002698 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002699
Scott Michelfdc40a02009-02-17 22:15:04 +00002700 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002701 DAG.getVTList(&ValValueVTs[0], NumValValues),
2702 &Values[0], NumValValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002703}
2704
2705
2706void SelectionDAGLowering::visitGetElementPtr(User &I) {
2707 SDValue N = getValue(I.getOperand(0));
2708 const Type *Ty = I.getOperand(0)->getType();
2709
2710 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2711 OI != E; ++OI) {
2712 Value *Idx = *OI;
2713 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2714 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2715 if (Field) {
2716 // N = N + Offset
2717 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002718 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002719 DAG.getIntPtrConstant(Offset));
2720 }
2721 Ty = StTy->getElementType(Field);
2722 } else {
2723 Ty = cast<SequentialType>(Ty)->getElementType();
2724
2725 // If this is a constant subscript, handle it quickly.
2726 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2727 if (CI->getZExtValue() == 0) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002728 uint64_t Offs =
Duncan Sands777d2302009-05-09 07:06:46 +00002729 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Evan Cheng65b52df2009-02-09 21:01:06 +00002730 SDValue OffsVal;
Evan Chengb1032a82009-02-09 20:54:38 +00002731 unsigned PtrBits = TLI.getPointerTy().getSizeInBits();
Evan Cheng65b52df2009-02-09 21:01:06 +00002732 if (PtrBits < 64) {
2733 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2734 TLI.getPointerTy(),
2735 DAG.getConstant(Offs, MVT::i64));
2736 } else
Evan Chengb1032a82009-02-09 20:54:38 +00002737 OffsVal = DAG.getIntPtrConstant(Offs);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002738 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Evan Chengb1032a82009-02-09 20:54:38 +00002739 OffsVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002740 continue;
2741 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002742
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002743 // N = N + Idx * ElementSize;
Duncan Sands777d2302009-05-09 07:06:46 +00002744 uint64_t ElementSize = TD->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002745 SDValue IdxN = getValue(Idx);
2746
2747 // If the index is smaller or larger than intptr_t, truncate or extend
2748 // it.
2749 if (IdxN.getValueType().bitsLT(N.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002750 IdxN = DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002751 N.getValueType(), IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002752 else if (IdxN.getValueType().bitsGT(N.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002753 IdxN = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002754 N.getValueType(), IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002755
2756 // If this is a multiply by a power of two, turn it into a shl
2757 // immediately. This is a very common case.
2758 if (ElementSize != 1) {
2759 if (isPowerOf2_64(ElementSize)) {
2760 unsigned Amt = Log2_64(ElementSize);
Scott Michelfdc40a02009-02-17 22:15:04 +00002761 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002762 N.getValueType(), IdxN,
Duncan Sands92abc622009-01-31 15:50:11 +00002763 DAG.getConstant(Amt, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002764 } else {
2765 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
Scott Michelfdc40a02009-02-17 22:15:04 +00002766 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002767 N.getValueType(), IdxN, Scale);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002768 }
2769 }
2770
Scott Michelfdc40a02009-02-17 22:15:04 +00002771 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002772 N.getValueType(), N, IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002773 }
2774 }
2775 setValue(&I, N);
2776}
2777
2778void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2779 // If this is a fixed sized alloca in the entry block of the function,
2780 // allocate it statically on the stack.
2781 if (FuncInfo.StaticAllocaMap.count(&I))
2782 return; // getValue will auto-populate this.
2783
2784 const Type *Ty = I.getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002785 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002786 unsigned Align =
2787 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2788 I.getAlignment());
2789
2790 SDValue AllocSize = getValue(I.getArraySize());
Chris Lattner0b18e592009-03-17 19:36:00 +00002791
2792 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2793 AllocSize,
2794 DAG.getConstant(TySize, AllocSize.getValueType()));
2795
2796
2797
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002798 MVT IntPtr = TLI.getPointerTy();
2799 if (IntPtr.bitsLT(AllocSize.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002800 AllocSize = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002801 IntPtr, AllocSize);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002802 else if (IntPtr.bitsGT(AllocSize.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002803 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002804 IntPtr, AllocSize);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002805
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002806 // Handle alignment. If the requested alignment is less than or equal to
2807 // the stack alignment, ignore it. If the size is greater than or equal to
2808 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2809 unsigned StackAlign =
2810 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2811 if (Align <= StackAlign)
2812 Align = 0;
2813
2814 // Round the size of the allocation up to the stack alignment size
2815 // by add SA-1 to the size.
Scott Michelfdc40a02009-02-17 22:15:04 +00002816 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002817 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002818 DAG.getIntPtrConstant(StackAlign-1));
2819 // Mask out the low bits for alignment purposes.
Scott Michelfdc40a02009-02-17 22:15:04 +00002820 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002821 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002822 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2823
2824 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Dan Gohmanfc166572009-04-09 23:54:40 +00002825 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
Scott Michelfdc40a02009-02-17 22:15:04 +00002826 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002827 VTs, Ops, 3);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002828 setValue(&I, DSA);
2829 DAG.setRoot(DSA.getValue(1));
2830
2831 // Inform the Frame Information that we have just allocated a variable-sized
2832 // object.
2833 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2834}
2835
2836void SelectionDAGLowering::visitLoad(LoadInst &I) {
2837 const Value *SV = I.getOperand(0);
2838 SDValue Ptr = getValue(SV);
2839
2840 const Type *Ty = I.getType();
2841 bool isVolatile = I.isVolatile();
2842 unsigned Alignment = I.getAlignment();
2843
2844 SmallVector<MVT, 4> ValueVTs;
2845 SmallVector<uint64_t, 4> Offsets;
2846 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2847 unsigned NumValues = ValueVTs.size();
2848 if (NumValues == 0)
2849 return;
2850
2851 SDValue Root;
2852 bool ConstantMemory = false;
2853 if (I.isVolatile())
2854 // Serialize volatile loads with other side effects.
2855 Root = getRoot();
2856 else if (AA->pointsToConstantMemory(SV)) {
2857 // Do not serialize (non-volatile) loads of constant memory with anything.
2858 Root = DAG.getEntryNode();
2859 ConstantMemory = true;
2860 } else {
2861 // Do not serialize non-volatile loads against each other.
2862 Root = DAG.getRoot();
2863 }
2864
2865 SmallVector<SDValue, 4> Values(NumValues);
2866 SmallVector<SDValue, 4> Chains(NumValues);
2867 MVT PtrVT = Ptr.getValueType();
2868 for (unsigned i = 0; i != NumValues; ++i) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002869 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
Scott Michelfdc40a02009-02-17 22:15:04 +00002870 DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002871 PtrVT, Ptr,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002872 DAG.getConstant(Offsets[i], PtrVT)),
2873 SV, Offsets[i],
2874 isVolatile, Alignment);
2875 Values[i] = L;
2876 Chains[i] = L.getValue(1);
2877 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002878
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002879 if (!ConstantMemory) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002880 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002881 MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002882 &Chains[0], NumValues);
2883 if (isVolatile)
2884 DAG.setRoot(Chain);
2885 else
2886 PendingLoads.push_back(Chain);
2887 }
2888
Scott Michelfdc40a02009-02-17 22:15:04 +00002889 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002890 DAG.getVTList(&ValueVTs[0], NumValues),
2891 &Values[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002892}
2893
2894
2895void SelectionDAGLowering::visitStore(StoreInst &I) {
2896 Value *SrcV = I.getOperand(0);
2897 Value *PtrV = I.getOperand(1);
2898
2899 SmallVector<MVT, 4> ValueVTs;
2900 SmallVector<uint64_t, 4> Offsets;
2901 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2902 unsigned NumValues = ValueVTs.size();
2903 if (NumValues == 0)
2904 return;
2905
2906 // Get the lowered operands. Note that we do this after
2907 // checking if NumResults is zero, because with zero results
2908 // the operands won't have values in the map.
2909 SDValue Src = getValue(SrcV);
2910 SDValue Ptr = getValue(PtrV);
2911
2912 SDValue Root = getRoot();
2913 SmallVector<SDValue, 4> Chains(NumValues);
2914 MVT PtrVT = Ptr.getValueType();
2915 bool isVolatile = I.isVolatile();
2916 unsigned Alignment = I.getAlignment();
2917 for (unsigned i = 0; i != NumValues; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002918 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002919 SDValue(Src.getNode(), Src.getResNo() + i),
Scott Michelfdc40a02009-02-17 22:15:04 +00002920 DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002921 PtrVT, Ptr,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002922 DAG.getConstant(Offsets[i], PtrVT)),
2923 PtrV, Offsets[i],
2924 isVolatile, Alignment);
2925
Scott Michelfdc40a02009-02-17 22:15:04 +00002926 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002927 MVT::Other, &Chains[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002928}
2929
2930/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2931/// node.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002932void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002933 unsigned Intrinsic) {
2934 bool HasChain = !I.doesNotAccessMemory();
2935 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2936
2937 // Build the operand list.
2938 SmallVector<SDValue, 8> Ops;
2939 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2940 if (OnlyLoad) {
2941 // We don't need to serialize loads against other loads.
2942 Ops.push_back(DAG.getRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002943 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002944 Ops.push_back(getRoot());
2945 }
2946 }
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002947
2948 // Info is set by getTgtMemInstrinsic
2949 TargetLowering::IntrinsicInfo Info;
2950 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2951
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002952 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002953 if (!IsTgtIntrinsic)
2954 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002955
2956 // Add all operands of the call to the operand list.
2957 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2958 SDValue Op = getValue(I.getOperand(i));
2959 assert(TLI.isTypeLegal(Op.getValueType()) &&
2960 "Intrinsic uses a non-legal type?");
2961 Ops.push_back(Op);
2962 }
2963
Dan Gohmanfc166572009-04-09 23:54:40 +00002964 std::vector<MVT> VTArray;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002965 if (I.getType() != Type::VoidTy) {
2966 MVT VT = TLI.getValueType(I.getType());
2967 if (VT.isVector()) {
2968 const VectorType *DestTy = cast<VectorType>(I.getType());
2969 MVT EltVT = TLI.getValueType(DestTy->getElementType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002970
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002971 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2972 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2973 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002974
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002975 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
Dan Gohmanfc166572009-04-09 23:54:40 +00002976 VTArray.push_back(VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002977 }
2978 if (HasChain)
Dan Gohmanfc166572009-04-09 23:54:40 +00002979 VTArray.push_back(MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002980
Dan Gohmanfc166572009-04-09 23:54:40 +00002981 SDVTList VTs = DAG.getVTList(&VTArray[0], VTArray.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002982
2983 // Create the node.
2984 SDValue Result;
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002985 if (IsTgtIntrinsic) {
2986 // This is target intrinsic that touches memory
Dale Johannesen66978ee2009-01-31 02:22:37 +00002987 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002988 VTs, &Ops[0], Ops.size(),
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002989 Info.memVT, Info.ptrVal, Info.offset,
2990 Info.align, Info.vol,
2991 Info.readMem, Info.writeMem);
2992 }
2993 else if (!HasChain)
Scott Michelfdc40a02009-02-17 22:15:04 +00002994 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002995 VTs, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002996 else if (I.getType() != Type::VoidTy)
Scott Michelfdc40a02009-02-17 22:15:04 +00002997 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002998 VTs, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002999 else
Scott Michelfdc40a02009-02-17 22:15:04 +00003000 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00003001 VTs, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003002
3003 if (HasChain) {
3004 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3005 if (OnlyLoad)
3006 PendingLoads.push_back(Chain);
3007 else
3008 DAG.setRoot(Chain);
3009 }
3010 if (I.getType() != Type::VoidTy) {
3011 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3012 MVT VT = TLI.getValueType(PTy);
Dale Johannesen66978ee2009-01-31 02:22:37 +00003013 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003014 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003015 setValue(&I, Result);
3016 }
3017}
3018
3019/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
3020static GlobalVariable *ExtractTypeInfo(Value *V) {
3021 V = V->stripPointerCasts();
3022 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
3023 assert ((GV || isa<ConstantPointerNull>(V)) &&
3024 "TypeInfo must be a global variable or NULL");
3025 return GV;
3026}
3027
3028namespace llvm {
3029
3030/// AddCatchInfo - Extract the personality and type infos from an eh.selector
3031/// call, and add them to the specified machine basic block.
3032void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3033 MachineBasicBlock *MBB) {
3034 // Inform the MachineModuleInfo of the personality for this landing pad.
3035 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3036 assert(CE->getOpcode() == Instruction::BitCast &&
3037 isa<Function>(CE->getOperand(0)) &&
3038 "Personality should be a function");
3039 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3040
3041 // Gather all the type infos for this landing pad and pass them along to
3042 // MachineModuleInfo.
3043 std::vector<GlobalVariable *> TyInfo;
3044 unsigned N = I.getNumOperands();
3045
3046 for (unsigned i = N - 1; i > 2; --i) {
3047 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3048 unsigned FilterLength = CI->getZExtValue();
3049 unsigned FirstCatch = i + FilterLength + !FilterLength;
3050 assert (FirstCatch <= N && "Invalid filter length");
3051
3052 if (FirstCatch < N) {
3053 TyInfo.reserve(N - FirstCatch);
3054 for (unsigned j = FirstCatch; j < N; ++j)
3055 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3056 MMI->addCatchTypeInfo(MBB, TyInfo);
3057 TyInfo.clear();
3058 }
3059
3060 if (!FilterLength) {
3061 // Cleanup.
3062 MMI->addCleanup(MBB);
3063 } else {
3064 // Filter.
3065 TyInfo.reserve(FilterLength - 1);
3066 for (unsigned j = i + 1; j < FirstCatch; ++j)
3067 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3068 MMI->addFilterTypeInfo(MBB, TyInfo);
3069 TyInfo.clear();
3070 }
3071
3072 N = i;
3073 }
3074 }
3075
3076 if (N > 3) {
3077 TyInfo.reserve(N - 3);
3078 for (unsigned j = 3; j < N; ++j)
3079 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3080 MMI->addCatchTypeInfo(MBB, TyInfo);
3081 }
3082}
3083
3084}
3085
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003086/// GetSignificand - Get the significand and build it into a floating-point
3087/// number with exponent of 1:
3088///
3089/// Op = (Op & 0x007fffff) | 0x3f800000;
3090///
3091/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003092static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003093GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
3094 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003095 DAG.getConstant(0x007fffff, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003096 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003097 DAG.getConstant(0x3f800000, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003098 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003099}
3100
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003101/// GetExponent - Get the exponent:
3102///
Bill Wendlinge9a72862009-01-20 21:17:57 +00003103/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003104///
3105/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003106static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003107GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3108 DebugLoc dl) {
3109 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003110 DAG.getConstant(0x7f800000, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003111 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
Duncan Sands92abc622009-01-31 15:50:11 +00003112 DAG.getConstant(23, TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003113 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003114 DAG.getConstant(127, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003115 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003116}
3117
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003118/// getF32Constant - Get 32-bit floating point constant.
3119static SDValue
3120getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3121 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3122}
3123
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003124/// Inlined utility function to implement binary input atomic intrinsics for
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003125/// visitIntrinsicCall: I is a call instruction
3126/// Op is the associated NodeType for I
3127const char *
3128SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003129 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003130 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00003131 DAG.getAtomic(Op, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003132 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003133 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003134 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003135 getValue(I.getOperand(2)),
3136 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003137 setValue(&I, L);
3138 DAG.setRoot(L.getValue(1));
3139 return 0;
3140}
3141
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003142// implVisitAluOverflow - Lower arithmetic overflow instrinsics.
Bill Wendling74c37652008-12-09 22:08:41 +00003143const char *
3144SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003145 SDValue Op1 = getValue(I.getOperand(1));
3146 SDValue Op2 = getValue(I.getOperand(2));
Bill Wendling74c37652008-12-09 22:08:41 +00003147
Dan Gohmanfc166572009-04-09 23:54:40 +00003148 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
3149 SDValue Result = DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2);
Bill Wendling74c37652008-12-09 22:08:41 +00003150
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003151 setValue(&I, Result);
3152 return 0;
3153}
Bill Wendling74c37652008-12-09 22:08:41 +00003154
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003155/// visitExp - Lower an exp intrinsic. Handles the special sequences for
3156/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003157void
3158SelectionDAGLowering::visitExp(CallInst &I) {
3159 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003160 DebugLoc dl = getCurDebugLoc();
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003161
3162 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3163 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3164 SDValue Op = getValue(I.getOperand(1));
3165
3166 // Put the exponent in the right bit position for later addition to the
3167 // final result:
3168 //
3169 // #define LOG2OFe 1.4426950f
3170 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003171 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003172 getF32Constant(DAG, 0x3fb8aa3b));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003173 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003174
3175 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003176 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3177 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003178
3179 // IntegerPartOfX <<= 23;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003180 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003181 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003182
3183 if (LimitFloatPrecision <= 6) {
3184 // For floating-point precision of 6:
3185 //
3186 // TwoToFractionalPartOfX =
3187 // 0.997535578f +
3188 // (0.735607626f + 0.252464424f * x) * x;
3189 //
3190 // error 0.0144103317, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003191 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003192 getF32Constant(DAG, 0x3e814304));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003193 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003194 getF32Constant(DAG, 0x3f3c50c8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003195 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3196 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003197 getF32Constant(DAG, 0x3f7f5e7e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003198 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003199
3200 // Add the exponent into the result in integer domain.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003201 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003202 TwoToFracPartOfX, IntegerPartOfX);
3203
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003204 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003205 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3206 // For floating-point precision of 12:
3207 //
3208 // TwoToFractionalPartOfX =
3209 // 0.999892986f +
3210 // (0.696457318f +
3211 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3212 //
3213 // 0.000107046256 error, which is 13 to 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003214 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003215 getF32Constant(DAG, 0x3da235e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003216 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003217 getF32Constant(DAG, 0x3e65b8f3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003218 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3219 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003220 getF32Constant(DAG, 0x3f324b07));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003221 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3222 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003223 getF32Constant(DAG, 0x3f7ff8fd));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003224 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003225
3226 // Add the exponent into the result in integer domain.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003227 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003228 TwoToFracPartOfX, IntegerPartOfX);
3229
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003230 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003231 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3232 // For floating-point precision of 18:
3233 //
3234 // TwoToFractionalPartOfX =
3235 // 0.999999982f +
3236 // (0.693148872f +
3237 // (0.240227044f +
3238 // (0.554906021e-1f +
3239 // (0.961591928e-2f +
3240 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3241 //
3242 // error 2.47208000*10^(-7), which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003243 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003244 getF32Constant(DAG, 0x3924b03e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003245 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003246 getF32Constant(DAG, 0x3ab24b87));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003247 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3248 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003249 getF32Constant(DAG, 0x3c1d8c17));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003250 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3251 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003252 getF32Constant(DAG, 0x3d634a1d));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003253 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3254 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003255 getF32Constant(DAG, 0x3e75fe14));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003256 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3257 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003258 getF32Constant(DAG, 0x3f317234));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003259 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3260 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003261 getF32Constant(DAG, 0x3f800000));
Scott Michelfdc40a02009-02-17 22:15:04 +00003262 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003263 MVT::i32, t13);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003264
3265 // Add the exponent into the result in integer domain.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003266 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003267 TwoToFracPartOfX, IntegerPartOfX);
3268
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003269 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003270 }
3271 } else {
3272 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003273 result = DAG.getNode(ISD::FEXP, dl,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003274 getValue(I.getOperand(1)).getValueType(),
3275 getValue(I.getOperand(1)));
3276 }
3277
Dale Johannesen59e577f2008-09-05 18:38:42 +00003278 setValue(&I, result);
3279}
3280
Bill Wendling39150252008-09-09 20:39:27 +00003281/// visitLog - Lower a log intrinsic. Handles the special sequences for
3282/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003283void
3284SelectionDAGLowering::visitLog(CallInst &I) {
3285 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003286 DebugLoc dl = getCurDebugLoc();
Bill Wendling39150252008-09-09 20:39:27 +00003287
3288 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3289 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3290 SDValue Op = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003291 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling39150252008-09-09 20:39:27 +00003292
3293 // Scale the exponent by log(2) [0.69314718f].
Dale Johannesen66978ee2009-01-31 02:22:37 +00003294 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003295 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003296 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003297
3298 // Get the significand and build it into a floating-point number with
3299 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003300 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling39150252008-09-09 20:39:27 +00003301
3302 if (LimitFloatPrecision <= 6) {
3303 // For floating-point precision of 6:
3304 //
3305 // LogofMantissa =
3306 // -1.1609546f +
3307 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003308 //
Bill Wendling39150252008-09-09 20:39:27 +00003309 // error 0.0034276066, which is better than 8 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003310 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003311 getF32Constant(DAG, 0xbe74c456));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003312 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003313 getF32Constant(DAG, 0x3fb3a2b1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003314 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3315 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003316 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00003317
Scott Michelfdc40a02009-02-17 22:15:04 +00003318 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003319 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003320 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3321 // For floating-point precision of 12:
3322 //
3323 // LogOfMantissa =
3324 // -1.7417939f +
3325 // (2.8212026f +
3326 // (-1.4699568f +
3327 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3328 //
3329 // error 0.000061011436, which is 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003330 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003331 getF32Constant(DAG, 0xbd67b6d6));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003332 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003333 getF32Constant(DAG, 0x3ee4f4b8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003334 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3335 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003336 getF32Constant(DAG, 0x3fbc278b));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003337 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3338 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003339 getF32Constant(DAG, 0x40348e95));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003340 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3341 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003342 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00003343
Scott Michelfdc40a02009-02-17 22:15:04 +00003344 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003345 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003346 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3347 // For floating-point precision of 18:
3348 //
3349 // LogOfMantissa =
3350 // -2.1072184f +
3351 // (4.2372794f +
3352 // (-3.7029485f +
3353 // (2.2781945f +
3354 // (-0.87823314f +
3355 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3356 //
3357 // error 0.0000023660568, which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003358 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003359 getF32Constant(DAG, 0xbc91e5ac));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003360 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003361 getF32Constant(DAG, 0x3e4350aa));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003362 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3363 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003364 getF32Constant(DAG, 0x3f60d3e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003365 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3366 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003367 getF32Constant(DAG, 0x4011cdf0));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003368 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3369 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003370 getF32Constant(DAG, 0x406cfd1c));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003371 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3372 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003373 getF32Constant(DAG, 0x408797cb));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003374 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3375 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003376 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003377
Scott Michelfdc40a02009-02-17 22:15:04 +00003378 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003379 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003380 }
3381 } else {
3382 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003383 result = DAG.getNode(ISD::FLOG, dl,
Bill Wendling39150252008-09-09 20:39:27 +00003384 getValue(I.getOperand(1)).getValueType(),
3385 getValue(I.getOperand(1)));
3386 }
3387
Dale Johannesen59e577f2008-09-05 18:38:42 +00003388 setValue(&I, result);
3389}
3390
Bill Wendling3eb59402008-09-09 00:28:24 +00003391/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3392/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003393void
3394SelectionDAGLowering::visitLog2(CallInst &I) {
3395 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003396 DebugLoc dl = getCurDebugLoc();
Bill Wendling3eb59402008-09-09 00:28:24 +00003397
Dale Johannesen853244f2008-09-05 23:49:37 +00003398 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003399 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3400 SDValue Op = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003401 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003402
Bill Wendling39150252008-09-09 20:39:27 +00003403 // Get the exponent.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003404 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00003405
3406 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003407 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003408 SDValue X = GetSignificand(DAG, Op1, dl);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003409
Bill Wendling3eb59402008-09-09 00:28:24 +00003410 // Different possible minimax approximations of significand in
3411 // floating-point for various degrees of accuracy over [1,2].
3412 if (LimitFloatPrecision <= 6) {
3413 // For floating-point precision of 6:
3414 //
3415 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3416 //
3417 // error 0.0049451742, which is more than 7 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003418 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003419 getF32Constant(DAG, 0xbeb08fe0));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003420 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003421 getF32Constant(DAG, 0x40019463));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003422 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3423 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003424 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003425
Scott Michelfdc40a02009-02-17 22:15:04 +00003426 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003427 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003428 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3429 // For floating-point precision of 12:
3430 //
3431 // Log2ofMantissa =
3432 // -2.51285454f +
3433 // (4.07009056f +
3434 // (-2.12067489f +
3435 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003436 //
Bill Wendling3eb59402008-09-09 00:28:24 +00003437 // error 0.0000876136000, which is better than 13 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003438 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003439 getF32Constant(DAG, 0xbda7262e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003440 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003441 getF32Constant(DAG, 0x3f25280b));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003442 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3443 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003444 getF32Constant(DAG, 0x4007b923));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003445 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3446 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003447 getF32Constant(DAG, 0x40823e2f));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003448 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3449 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003450 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003451
Scott Michelfdc40a02009-02-17 22:15:04 +00003452 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003453 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003454 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3455 // For floating-point precision of 18:
3456 //
3457 // Log2ofMantissa =
3458 // -3.0400495f +
3459 // (6.1129976f +
3460 // (-5.3420409f +
3461 // (3.2865683f +
3462 // (-1.2669343f +
3463 // (0.27515199f -
3464 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3465 //
3466 // error 0.0000018516, which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003467 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003468 getF32Constant(DAG, 0xbcd2769e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003469 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003470 getF32Constant(DAG, 0x3e8ce0b9));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003471 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3472 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003473 getF32Constant(DAG, 0x3fa22ae7));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003474 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3475 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003476 getF32Constant(DAG, 0x40525723));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003477 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3478 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003479 getF32Constant(DAG, 0x40aaf200));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003480 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3481 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003482 getF32Constant(DAG, 0x40c39dad));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003483 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3484 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003485 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003486
Scott Michelfdc40a02009-02-17 22:15:04 +00003487 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003488 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003489 }
Dale Johannesen853244f2008-09-05 23:49:37 +00003490 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003491 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003492 result = DAG.getNode(ISD::FLOG2, dl,
Dale Johannesen853244f2008-09-05 23:49:37 +00003493 getValue(I.getOperand(1)).getValueType(),
3494 getValue(I.getOperand(1)));
3495 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003496
Dale Johannesen59e577f2008-09-05 18:38:42 +00003497 setValue(&I, result);
3498}
3499
Bill Wendling3eb59402008-09-09 00:28:24 +00003500/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3501/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003502void
3503SelectionDAGLowering::visitLog10(CallInst &I) {
3504 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003505 DebugLoc dl = getCurDebugLoc();
Bill Wendling181b6272008-10-19 20:34:04 +00003506
Dale Johannesen852680a2008-09-05 21:27:19 +00003507 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003508 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3509 SDValue Op = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003510 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003511
Bill Wendling39150252008-09-09 20:39:27 +00003512 // Scale the exponent by log10(2) [0.30102999f].
Dale Johannesen66978ee2009-01-31 02:22:37 +00003513 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003514 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003515 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003516
3517 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003518 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003519 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00003520
3521 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003522 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003523 //
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003524 // Log10ofMantissa =
3525 // -0.50419619f +
3526 // (0.60948995f - 0.10380950f * x) * x;
3527 //
3528 // error 0.0014886165, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003529 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003530 getF32Constant(DAG, 0xbdd49a13));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003531 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003532 getF32Constant(DAG, 0x3f1c0789));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003533 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3534 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003535 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003536
Scott Michelfdc40a02009-02-17 22:15:04 +00003537 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003538 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003539 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3540 // For floating-point precision of 12:
3541 //
3542 // Log10ofMantissa =
3543 // -0.64831180f +
3544 // (0.91751397f +
3545 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3546 //
3547 // error 0.00019228036, which is better than 12 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003548 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003549 getF32Constant(DAG, 0x3d431f31));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003550 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003551 getF32Constant(DAG, 0x3ea21fb2));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003552 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3553 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003554 getF32Constant(DAG, 0x3f6ae232));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003555 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3556 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003557 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00003558
Scott Michelfdc40a02009-02-17 22:15:04 +00003559 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003560 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003561 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003562 // For floating-point precision of 18:
3563 //
3564 // Log10ofMantissa =
3565 // -0.84299375f +
3566 // (1.5327582f +
3567 // (-1.0688956f +
3568 // (0.49102474f +
3569 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3570 //
3571 // error 0.0000037995730, which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003572 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003573 getF32Constant(DAG, 0x3c5d51ce));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003574 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003575 getF32Constant(DAG, 0x3e00685a));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003576 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3577 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003578 getF32Constant(DAG, 0x3efb6798));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003579 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3580 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003581 getF32Constant(DAG, 0x3f88d192));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003582 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3583 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003584 getF32Constant(DAG, 0x3fc4316c));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003585 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3586 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003587 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003588
Scott Michelfdc40a02009-02-17 22:15:04 +00003589 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003590 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003591 }
Dale Johannesen852680a2008-09-05 21:27:19 +00003592 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003593 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003594 result = DAG.getNode(ISD::FLOG10, dl,
Dale Johannesen852680a2008-09-05 21:27:19 +00003595 getValue(I.getOperand(1)).getValueType(),
3596 getValue(I.getOperand(1)));
3597 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003598
Dale Johannesen59e577f2008-09-05 18:38:42 +00003599 setValue(&I, result);
3600}
3601
Bill Wendlinge10c8142008-09-09 22:39:21 +00003602/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3603/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003604void
3605SelectionDAGLowering::visitExp2(CallInst &I) {
3606 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003607 DebugLoc dl = getCurDebugLoc();
Bill Wendlinge10c8142008-09-09 22:39:21 +00003608
Dale Johannesen601d3c02008-09-05 01:48:15 +00003609 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00003610 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3611 SDValue Op = getValue(I.getOperand(1));
3612
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003613 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003614
3615 // FractionalPartOfX = x - (float)IntegerPartOfX;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003616 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3617 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003618
3619 // IntegerPartOfX <<= 23;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003620 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003621 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003622
3623 if (LimitFloatPrecision <= 6) {
3624 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003625 //
Bill Wendlinge10c8142008-09-09 22:39:21 +00003626 // TwoToFractionalPartOfX =
3627 // 0.997535578f +
3628 // (0.735607626f + 0.252464424f * x) * x;
3629 //
3630 // error 0.0144103317, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003631 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003632 getF32Constant(DAG, 0x3e814304));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003633 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003634 getF32Constant(DAG, 0x3f3c50c8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003635 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3636 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003637 getF32Constant(DAG, 0x3f7f5e7e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003638 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003639 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003640 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003641
Scott Michelfdc40a02009-02-17 22:15:04 +00003642 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003643 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003644 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3645 // For floating-point precision of 12:
3646 //
3647 // TwoToFractionalPartOfX =
3648 // 0.999892986f +
3649 // (0.696457318f +
3650 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3651 //
3652 // error 0.000107046256, which is 13 to 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003653 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003654 getF32Constant(DAG, 0x3da235e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003655 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003656 getF32Constant(DAG, 0x3e65b8f3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003657 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3658 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003659 getF32Constant(DAG, 0x3f324b07));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003660 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3661 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003662 getF32Constant(DAG, 0x3f7ff8fd));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003663 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003664 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003665 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003666
Scott Michelfdc40a02009-02-17 22:15:04 +00003667 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003668 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003669 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3670 // For floating-point precision of 18:
3671 //
3672 // TwoToFractionalPartOfX =
3673 // 0.999999982f +
3674 // (0.693148872f +
3675 // (0.240227044f +
3676 // (0.554906021e-1f +
3677 // (0.961591928e-2f +
3678 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3679 // error 2.47208000*10^(-7), which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003680 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003681 getF32Constant(DAG, 0x3924b03e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003682 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003683 getF32Constant(DAG, 0x3ab24b87));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003684 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3685 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003686 getF32Constant(DAG, 0x3c1d8c17));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003687 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3688 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003689 getF32Constant(DAG, 0x3d634a1d));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003690 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3691 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003692 getF32Constant(DAG, 0x3e75fe14));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003693 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3694 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003695 getF32Constant(DAG, 0x3f317234));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003696 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3697 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003698 getF32Constant(DAG, 0x3f800000));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003699 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003700 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003701 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003702
Scott Michelfdc40a02009-02-17 22:15:04 +00003703 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003704 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003705 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00003706 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003707 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003708 result = DAG.getNode(ISD::FEXP2, dl,
Dale Johannesen601d3c02008-09-05 01:48:15 +00003709 getValue(I.getOperand(1)).getValueType(),
3710 getValue(I.getOperand(1)));
3711 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00003712
Dale Johannesen601d3c02008-09-05 01:48:15 +00003713 setValue(&I, result);
3714}
3715
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003716/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3717/// limited-precision mode with x == 10.0f.
3718void
3719SelectionDAGLowering::visitPow(CallInst &I) {
3720 SDValue result;
3721 Value *Val = I.getOperand(1);
Dale Johannesen66978ee2009-01-31 02:22:37 +00003722 DebugLoc dl = getCurDebugLoc();
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003723 bool IsExp10 = false;
3724
3725 if (getValue(Val).getValueType() == MVT::f32 &&
Bill Wendling277fc242008-09-10 00:24:59 +00003726 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003727 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3728 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3729 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3730 APFloat Ten(10.0f);
3731 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3732 }
3733 }
3734 }
3735
3736 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3737 SDValue Op = getValue(I.getOperand(2));
3738
3739 // Put the exponent in the right bit position for later addition to the
3740 // final result:
3741 //
3742 // #define LOG2OF10 3.3219281f
3743 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003744 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003745 getF32Constant(DAG, 0x40549a78));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003746 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003747
3748 // FractionalPartOfX = x - (float)IntegerPartOfX;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003749 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3750 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003751
3752 // IntegerPartOfX <<= 23;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003753 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003754 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003755
3756 if (LimitFloatPrecision <= 6) {
3757 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003758 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003759 // twoToFractionalPartOfX =
3760 // 0.997535578f +
3761 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003762 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003763 // error 0.0144103317, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003764 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003765 getF32Constant(DAG, 0x3e814304));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003766 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003767 getF32Constant(DAG, 0x3f3c50c8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003768 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3769 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003770 getF32Constant(DAG, 0x3f7f5e7e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003771 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003772 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003773 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003774
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003775 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3776 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003777 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3778 // For floating-point precision of 12:
3779 //
3780 // TwoToFractionalPartOfX =
3781 // 0.999892986f +
3782 // (0.696457318f +
3783 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3784 //
3785 // error 0.000107046256, which is 13 to 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003786 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003787 getF32Constant(DAG, 0x3da235e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003788 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003789 getF32Constant(DAG, 0x3e65b8f3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003790 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3791 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003792 getF32Constant(DAG, 0x3f324b07));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003793 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3794 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003795 getF32Constant(DAG, 0x3f7ff8fd));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003796 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003797 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003798 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003799
Scott Michelfdc40a02009-02-17 22:15:04 +00003800 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003801 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003802 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3803 // For floating-point precision of 18:
3804 //
3805 // TwoToFractionalPartOfX =
3806 // 0.999999982f +
3807 // (0.693148872f +
3808 // (0.240227044f +
3809 // (0.554906021e-1f +
3810 // (0.961591928e-2f +
3811 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3812 // error 2.47208000*10^(-7), which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003813 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003814 getF32Constant(DAG, 0x3924b03e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003815 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003816 getF32Constant(DAG, 0x3ab24b87));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003817 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3818 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003819 getF32Constant(DAG, 0x3c1d8c17));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003820 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3821 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003822 getF32Constant(DAG, 0x3d634a1d));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003823 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3824 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003825 getF32Constant(DAG, 0x3e75fe14));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003826 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3827 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003828 getF32Constant(DAG, 0x3f317234));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003829 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3830 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003831 getF32Constant(DAG, 0x3f800000));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003832 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003833 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003834 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003835
Scott Michelfdc40a02009-02-17 22:15:04 +00003836 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003837 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003838 }
3839 } else {
3840 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003841 result = DAG.getNode(ISD::FPOW, dl,
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003842 getValue(I.getOperand(1)).getValueType(),
3843 getValue(I.getOperand(1)),
3844 getValue(I.getOperand(2)));
3845 }
3846
3847 setValue(&I, result);
3848}
3849
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003850/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3851/// we want to emit this as a call to a named external function, return the name
3852/// otherwise lower it and return null.
3853const char *
3854SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00003855 DebugLoc dl = getCurDebugLoc();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003856 switch (Intrinsic) {
3857 default:
3858 // By default, turn this into a target intrinsic node.
3859 visitTargetIntrinsic(I, Intrinsic);
3860 return 0;
3861 case Intrinsic::vastart: visitVAStart(I); return 0;
3862 case Intrinsic::vaend: visitVAEnd(I); return 0;
3863 case Intrinsic::vacopy: visitVACopy(I); return 0;
3864 case Intrinsic::returnaddress:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003865 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003866 getValue(I.getOperand(1))));
3867 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00003868 case Intrinsic::frameaddress:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003869 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003870 getValue(I.getOperand(1))));
3871 return 0;
3872 case Intrinsic::setjmp:
3873 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3874 break;
3875 case Intrinsic::longjmp:
3876 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3877 break;
Chris Lattner824b9582008-11-21 16:42:48 +00003878 case Intrinsic::memcpy: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003879 SDValue Op1 = getValue(I.getOperand(1));
3880 SDValue Op2 = getValue(I.getOperand(2));
3881 SDValue Op3 = getValue(I.getOperand(3));
3882 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Dale Johannesena04b7572009-02-03 23:04:43 +00003883 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003884 I.getOperand(1), 0, I.getOperand(2), 0));
3885 return 0;
3886 }
Chris Lattner824b9582008-11-21 16:42:48 +00003887 case Intrinsic::memset: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003888 SDValue Op1 = getValue(I.getOperand(1));
3889 SDValue Op2 = getValue(I.getOperand(2));
3890 SDValue Op3 = getValue(I.getOperand(3));
3891 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Dale Johannesena04b7572009-02-03 23:04:43 +00003892 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003893 I.getOperand(1), 0));
3894 return 0;
3895 }
Chris Lattner824b9582008-11-21 16:42:48 +00003896 case Intrinsic::memmove: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003897 SDValue Op1 = getValue(I.getOperand(1));
3898 SDValue Op2 = getValue(I.getOperand(2));
3899 SDValue Op3 = getValue(I.getOperand(3));
3900 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3901
3902 // If the source and destination are known to not be aliases, we can
3903 // lower memmove as memcpy.
3904 uint64_t Size = -1ULL;
3905 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003906 Size = C->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003907 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3908 AliasAnalysis::NoAlias) {
Dale Johannesena04b7572009-02-03 23:04:43 +00003909 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003910 I.getOperand(1), 0, I.getOperand(2), 0));
3911 return 0;
3912 }
3913
Dale Johannesena04b7572009-02-03 23:04:43 +00003914 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003915 I.getOperand(1), 0, I.getOperand(2), 0));
3916 return 0;
3917 }
3918 case Intrinsic::dbg_stoppoint: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003919 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00003920 if (DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLevel)) {
Evan Chenge3d42322009-02-25 07:04:34 +00003921 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattneraf29a522009-05-04 22:10:05 +00003922 DICompileUnit CU(cast<GlobalVariable>(SPI.getContext()));
3923 DebugLoc Loc = DebugLoc::get(MF.getOrCreateDebugLocID(CU.getGV(),
Argyrios Kyrtzidisa3437642009-05-20 22:57:17 +00003924 DbgScopeTrack.getCurScope(),
3925 SPI.getLine(),
3926 SPI.getColumn()));
Chris Lattneraf29a522009-05-04 22:10:05 +00003927 setCurDebugLoc(Loc);
3928
Bill Wendling98a366d2009-04-29 23:29:43 +00003929 if (OptLevel == CodeGenOpt::None)
Chris Lattneraf29a522009-05-04 22:10:05 +00003930 DAG.setRoot(DAG.getDbgStopPoint(Loc, getRoot(),
Dale Johannesenbeaec4c2009-03-25 17:36:08 +00003931 SPI.getLine(),
3932 SPI.getColumn(),
3933 SPI.getContext()));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003934 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003935 return 0;
3936 }
3937 case Intrinsic::dbg_region_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003938 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003939 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Argyrios Kyrtzidisa3437642009-05-20 22:57:17 +00003940 if (!DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLevel))
3941 return 0;
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +00003942
Argyrios Kyrtzidisa3437642009-05-20 22:57:17 +00003943 MachineFunction &MF = DAG.getMachineFunction();
3944 GlobalVariable *Rgn = cast<GlobalVariable>(RSI.getContext());
3945 DbgScopeTrack.EnterDebugScope(Rgn, MF);
3946 if (DW && DW->ShouldEmitDwarfDebug()) {
3947 unsigned LabelID = DW->RecordRegionStart(Rgn);
Devang Patel48c7fa22009-04-13 18:13:16 +00003948 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3949 getRoot(), LabelID));
Bill Wendling92c1e122009-02-13 02:16:35 +00003950 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003951
3952 return 0;
3953 }
3954 case Intrinsic::dbg_region_end: {
Devang Patel83489bb2009-01-13 00:35:13 +00003955 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003956 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Argyrios Kyrtzidisa3437642009-05-20 22:57:17 +00003957 if (!DIDescriptor::ValidDebugInfo(REI.getContext(), OptLevel))
3958 return 0;
Devang Patel0f7fef32009-04-13 17:02:03 +00003959
Argyrios Kyrtzidisa3437642009-05-20 22:57:17 +00003960 MachineFunction &MF = DAG.getMachineFunction();
3961 GlobalVariable *Rgn = cast<GlobalVariable>(REI.getContext());
3962 DbgScopeTrack.ExitDebugScope(Rgn, MF);
3963 if (DW && DW->ShouldEmitDwarfDebug()) {
3964 DISubprogram Subprogram(Rgn);
Bill Wendling6c4311d2009-05-08 21:14:49 +00003965
Bill Wendling805da892009-05-18 18:21:03 +00003966 if (Subprogram.isNull() || Subprogram.describes(MF.getFunction())) {
Bill Wendling6c4311d2009-05-08 21:14:49 +00003967 unsigned LabelID =
3968 DW->RecordRegionEnd(cast<GlobalVariable>(REI.getContext()));
3969 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3970 getRoot(), LabelID));
3971 } else {
3972 // This is end of inlined function. Debugging information for inlined
3973 // function is not handled yet (only supported by FastISel).
Bill Wendling98a366d2009-04-29 23:29:43 +00003974 if (OptLevel == CodeGenOpt::None) {
Devang Patel16f2ffd2009-04-16 02:33:41 +00003975 unsigned ID = DW->RecordInlinedFnEnd(Subprogram);
3976 if (ID != 0)
Devang Patel02f8c412009-04-16 17:55:30 +00003977 // Returned ID is 0 if this is unbalanced "end of inlined
Bill Wendling6c4311d2009-05-08 21:14:49 +00003978 // scope". This could happen if optimizer eats dbg intrinsics or
3979 // "beginning of inlined scope" is not recoginized due to missing
3980 // location info. In such cases, do ignore this region.end.
Devang Patel16f2ffd2009-04-16 02:33:41 +00003981 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3982 getRoot(), ID));
3983 }
Devang Patel0f7fef32009-04-13 17:02:03 +00003984 }
Bill Wendling92c1e122009-02-13 02:16:35 +00003985 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003986
3987 return 0;
3988 }
3989 case Intrinsic::dbg_func_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003990 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003991 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3992 Value *SP = FSI.getSubprogram();
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00003993 if (!DIDescriptor::ValidDebugInfo(SP, OptLevel))
3994 return 0;
Devang Patel16f2ffd2009-04-16 02:33:41 +00003995
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00003996 MachineFunction &MF = DAG.getMachineFunction();
Argyrios Kyrtzidisa3437642009-05-20 22:57:17 +00003997 DbgScopeTrack.EnterDebugScope(cast<GlobalVariable>(SP), MF);
Bill Wendlingc677fe52009-05-10 00:10:50 +00003998 if (OptLevel == CodeGenOpt::None) {
3999 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is what
4000 // (most?) gdb expects.
4001 DebugLoc PrevLoc = CurDebugLoc;
4002 DISubprogram Subprogram(cast<GlobalVariable>(SP));
4003 DICompileUnit CompileUnit = Subprogram.getCompileUnit();
Devang Patel02f8c412009-04-16 17:55:30 +00004004
Bill Wendlingc677fe52009-05-10 00:10:50 +00004005 if (!Subprogram.describes(MF.getFunction())) {
4006 // This is a beginning of an inlined function.
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00004007
Bill Wendlingc677fe52009-05-10 00:10:50 +00004008 // If llvm.dbg.func.start is seen in a new block before any
4009 // llvm.dbg.stoppoint intrinsic then the location info is unknown.
4010 // FIXME : Why DebugLoc is reset at the beginning of each block ?
4011 if (PrevLoc.isUnknown())
4012 return 0;
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00004013
Bill Wendlingc677fe52009-05-10 00:10:50 +00004014 // Record the source line.
4015 unsigned Line = Subprogram.getLineNumber();
4016 setCurDebugLoc(DebugLoc::get(
Argyrios Kyrtzidisa3437642009-05-20 22:57:17 +00004017 MF.getOrCreateDebugLocID(CompileUnit.getGV(),
4018 DbgScopeTrack.getCurScope(),
4019 Line, 0)));
Bill Wendlingc677fe52009-05-10 00:10:50 +00004020
4021 if (DW && DW->ShouldEmitDwarfDebug()) {
4022 DebugLocTuple PrevLocTpl = MF.getDebugLocTuple(PrevLoc);
4023 unsigned LabelID = DW->RecordInlinedFnStart(Subprogram,
4024 DICompileUnit(PrevLocTpl.CompileUnit),
4025 PrevLocTpl.Line,
4026 PrevLocTpl.Col);
4027 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
4028 getRoot(), LabelID));
4029 }
4030 } else {
4031 // Record the source line.
4032 unsigned Line = Subprogram.getLineNumber();
4033 MF.setDefaultDebugLoc(DebugLoc::get(
Argyrios Kyrtzidisa3437642009-05-20 22:57:17 +00004034 MF.getOrCreateDebugLocID(CompileUnit.getGV(),
4035 DbgScopeTrack.getCurScope(),
4036 Line, 0)));
Bill Wendlingc677fe52009-05-10 00:10:50 +00004037 if (DW && DW->ShouldEmitDwarfDebug()) {
4038 // llvm.dbg.func_start also defines beginning of function scope.
4039 DW->RecordRegionStart(cast<GlobalVariable>(FSI.getSubprogram()));
4040 }
4041 }
4042 } else {
4043 DISubprogram Subprogram(cast<GlobalVariable>(SP));
4044
4045 std::string SPName;
4046 Subprogram.getLinkageName(SPName);
4047 if (!SPName.empty()
4048 && strcmp(SPName.c_str(), MF.getFunction()->getNameStart())) {
4049 // This is beginning of inlined function. Debugging information for
4050 // inlined function is not handled yet (only supported by FastISel).
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00004051 return 0;
Bill Wendlingc677fe52009-05-10 00:10:50 +00004052 }
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00004053
Bill Wendlingc677fe52009-05-10 00:10:50 +00004054 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
4055 // what (most?) gdb expects.
4056 DICompileUnit CompileUnit = Subprogram.getCompileUnit();
4057
4058 // Record the source line but does not create a label for the normal
4059 // function start. It will be emitted at asm emission time. However,
4060 // create a label if this is a beginning of inlined function.
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00004061 unsigned Line = Subprogram.getLineNumber();
4062 setCurDebugLoc(DebugLoc::get(
Argyrios Kyrtzidisa3437642009-05-20 22:57:17 +00004063 MF.getOrCreateDebugLocID(CompileUnit.getGV(),
4064 DbgScopeTrack.getCurScope(),
4065 Line, 0)));
Bill Wendlingc677fe52009-05-10 00:10:50 +00004066 // FIXME - Start new region because llvm.dbg.func_start also defines
4067 // beginning of function scope.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004068 }
4069
4070 return 0;
4071 }
Bill Wendling92c1e122009-02-13 02:16:35 +00004072 case Intrinsic::dbg_declare: {
Bill Wendling98a366d2009-04-29 23:29:43 +00004073 if (OptLevel == CodeGenOpt::None) {
Bill Wendling86e6cb92009-02-17 01:04:54 +00004074 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4075 Value *Variable = DI.getVariable();
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00004076 if (DIDescriptor::ValidDebugInfo(Variable, OptLevel))
Bill Wendling86e6cb92009-02-17 01:04:54 +00004077 DAG.setRoot(DAG.getNode(ISD::DECLARE, dl, MVT::Other, getRoot(),
4078 getValue(DI.getAddress()), getValue(Variable)));
4079 } else {
4080 // FIXME: Do something sensible here when we support debug declare.
4081 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004082 return 0;
Bill Wendling92c1e122009-02-13 02:16:35 +00004083 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004084 case Intrinsic::eh_exception: {
4085 if (!CurMBB->isLandingPad()) {
4086 // FIXME: Mark exception register as live in. Hack for PR1508.
4087 unsigned Reg = TLI.getExceptionAddressRegister();
4088 if (Reg) CurMBB->addLiveIn(Reg);
4089 }
4090 // Insert the EXCEPTIONADDR instruction.
4091 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4092 SDValue Ops[1];
4093 Ops[0] = DAG.getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004094 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004095 setValue(&I, Op);
4096 DAG.setRoot(Op.getValue(1));
4097 return 0;
4098 }
4099
4100 case Intrinsic::eh_selector_i32:
4101 case Intrinsic::eh_selector_i64: {
4102 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4103 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
4104 MVT::i32 : MVT::i64);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004105
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004106 if (MMI) {
4107 if (CurMBB->isLandingPad())
4108 AddCatchInfo(I, MMI, CurMBB);
4109 else {
4110#ifndef NDEBUG
4111 FuncInfo.CatchInfoLost.insert(&I);
4112#endif
4113 // FIXME: Mark exception selector register as live in. Hack for PR1508.
4114 unsigned Reg = TLI.getExceptionSelectorRegister();
4115 if (Reg) CurMBB->addLiveIn(Reg);
4116 }
4117
4118 // Insert the EHSELECTION instruction.
4119 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
4120 SDValue Ops[2];
4121 Ops[0] = getValue(I.getOperand(1));
4122 Ops[1] = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004123 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004124 setValue(&I, Op);
4125 DAG.setRoot(Op.getValue(1));
4126 } else {
4127 setValue(&I, DAG.getConstant(0, VT));
4128 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004129
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004130 return 0;
4131 }
4132
4133 case Intrinsic::eh_typeid_for_i32:
4134 case Intrinsic::eh_typeid_for_i64: {
4135 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4136 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
4137 MVT::i32 : MVT::i64);
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004138
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004139 if (MMI) {
4140 // Find the type id for the given typeinfo.
4141 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
4142
4143 unsigned TypeID = MMI->getTypeIDFor(GV);
4144 setValue(&I, DAG.getConstant(TypeID, VT));
4145 } else {
4146 // Return something different to eh_selector.
4147 setValue(&I, DAG.getConstant(1, VT));
4148 }
4149
4150 return 0;
4151 }
4152
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004153 case Intrinsic::eh_return_i32:
4154 case Intrinsic::eh_return_i64:
4155 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004156 MMI->setCallsEHReturn(true);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004157 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004158 MVT::Other,
4159 getControlRoot(),
4160 getValue(I.getOperand(1)),
4161 getValue(I.getOperand(2))));
4162 } else {
4163 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
4164 }
4165
4166 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004167 case Intrinsic::eh_unwind_init:
4168 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4169 MMI->setCallsUnwindInit(true);
4170 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004171
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004172 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004173
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004174 case Intrinsic::eh_dwarf_cfa: {
4175 MVT VT = getValue(I.getOperand(1)).getValueType();
4176 SDValue CfaArg;
4177 if (VT.bitsGT(TLI.getPointerTy()))
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004178 CfaArg = DAG.getNode(ISD::TRUNCATE, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004179 TLI.getPointerTy(), getValue(I.getOperand(1)));
4180 else
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004181 CfaArg = DAG.getNode(ISD::SIGN_EXTEND, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004182 TLI.getPointerTy(), getValue(I.getOperand(1)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004183
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004184 SDValue Offset = DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004185 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004186 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004187 TLI.getPointerTy()),
4188 CfaArg);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004189 setValue(&I, DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004190 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004191 DAG.getNode(ISD::FRAMEADDR, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004192 TLI.getPointerTy(),
4193 DAG.getConstant(0,
4194 TLI.getPointerTy())),
4195 Offset));
4196 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004197 }
4198
Mon P Wang77cdf302008-11-10 20:54:11 +00004199 case Intrinsic::convertff:
4200 case Intrinsic::convertfsi:
4201 case Intrinsic::convertfui:
4202 case Intrinsic::convertsif:
4203 case Intrinsic::convertuif:
4204 case Intrinsic::convertss:
4205 case Intrinsic::convertsu:
4206 case Intrinsic::convertus:
4207 case Intrinsic::convertuu: {
4208 ISD::CvtCode Code = ISD::CVT_INVALID;
4209 switch (Intrinsic) {
4210 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4211 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4212 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4213 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4214 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4215 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4216 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4217 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4218 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4219 }
4220 MVT DestVT = TLI.getValueType(I.getType());
4221 Value* Op1 = I.getOperand(1);
Dale Johannesena04b7572009-02-03 23:04:43 +00004222 setValue(&I, DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
Mon P Wang77cdf302008-11-10 20:54:11 +00004223 DAG.getValueType(DestVT),
4224 DAG.getValueType(getValue(Op1).getValueType()),
4225 getValue(I.getOperand(2)),
4226 getValue(I.getOperand(3)),
4227 Code));
4228 return 0;
4229 }
4230
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004231 case Intrinsic::sqrt:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004232 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004233 getValue(I.getOperand(1)).getValueType(),
4234 getValue(I.getOperand(1))));
4235 return 0;
4236 case Intrinsic::powi:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004237 setValue(&I, DAG.getNode(ISD::FPOWI, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004238 getValue(I.getOperand(1)).getValueType(),
4239 getValue(I.getOperand(1)),
4240 getValue(I.getOperand(2))));
4241 return 0;
4242 case Intrinsic::sin:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004243 setValue(&I, DAG.getNode(ISD::FSIN, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004244 getValue(I.getOperand(1)).getValueType(),
4245 getValue(I.getOperand(1))));
4246 return 0;
4247 case Intrinsic::cos:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004248 setValue(&I, DAG.getNode(ISD::FCOS, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004249 getValue(I.getOperand(1)).getValueType(),
4250 getValue(I.getOperand(1))));
4251 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004252 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004253 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004254 return 0;
4255 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004256 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004257 return 0;
4258 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004259 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004260 return 0;
4261 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004262 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004263 return 0;
4264 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00004265 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004266 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004267 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004268 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004269 return 0;
4270 case Intrinsic::pcmarker: {
4271 SDValue Tmp = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004272 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004273 return 0;
4274 }
4275 case Intrinsic::readcyclecounter: {
4276 SDValue Op = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004277 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER, dl,
Dan Gohmanfc166572009-04-09 23:54:40 +00004278 DAG.getVTList(MVT::i64, MVT::Other),
4279 &Op, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004280 setValue(&I, Tmp);
4281 DAG.setRoot(Tmp.getValue(1));
4282 return 0;
4283 }
4284 case Intrinsic::part_select: {
4285 // Currently not implemented: just abort
4286 assert(0 && "part_select intrinsic not implemented");
4287 abort();
4288 }
4289 case Intrinsic::part_set: {
4290 // Currently not implemented: just abort
4291 assert(0 && "part_set intrinsic not implemented");
4292 abort();
4293 }
4294 case Intrinsic::bswap:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004295 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004296 getValue(I.getOperand(1)).getValueType(),
4297 getValue(I.getOperand(1))));
4298 return 0;
4299 case Intrinsic::cttz: {
4300 SDValue Arg = getValue(I.getOperand(1));
4301 MVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004302 SDValue result = DAG.getNode(ISD::CTTZ, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004303 setValue(&I, result);
4304 return 0;
4305 }
4306 case Intrinsic::ctlz: {
4307 SDValue Arg = getValue(I.getOperand(1));
4308 MVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004309 SDValue result = DAG.getNode(ISD::CTLZ, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004310 setValue(&I, result);
4311 return 0;
4312 }
4313 case Intrinsic::ctpop: {
4314 SDValue Arg = getValue(I.getOperand(1));
4315 MVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004316 SDValue result = DAG.getNode(ISD::CTPOP, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004317 setValue(&I, result);
4318 return 0;
4319 }
4320 case Intrinsic::stacksave: {
4321 SDValue Op = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004322 SDValue Tmp = DAG.getNode(ISD::STACKSAVE, dl,
Dan Gohmanfc166572009-04-09 23:54:40 +00004323 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004324 setValue(&I, Tmp);
4325 DAG.setRoot(Tmp.getValue(1));
4326 return 0;
4327 }
4328 case Intrinsic::stackrestore: {
4329 SDValue Tmp = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004330 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004331 return 0;
4332 }
Bill Wendling57344502008-11-18 11:01:33 +00004333 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00004334 // Emit code into the DAG to store the stack guard onto the stack.
4335 MachineFunction &MF = DAG.getMachineFunction();
4336 MachineFrameInfo *MFI = MF.getFrameInfo();
4337 MVT PtrTy = TLI.getPointerTy();
4338
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004339 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4340 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
Bill Wendlingb2a42982008-11-06 02:29:10 +00004341
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004342 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00004343 MFI->setStackProtectorIndex(FI);
4344
4345 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4346
4347 // Store the stack protector onto the stack.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004348 SDValue Result = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
Bill Wendlingb2a42982008-11-06 02:29:10 +00004349 PseudoSourceValue::getFixedStack(FI),
4350 0, true);
4351 setValue(&I, Result);
4352 DAG.setRoot(Result);
4353 return 0;
4354 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004355 case Intrinsic::var_annotation:
4356 // Discard annotate attributes
4357 return 0;
4358
4359 case Intrinsic::init_trampoline: {
4360 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4361
4362 SDValue Ops[6];
4363 Ops[0] = getRoot();
4364 Ops[1] = getValue(I.getOperand(1));
4365 Ops[2] = getValue(I.getOperand(2));
4366 Ops[3] = getValue(I.getOperand(3));
4367 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4368 Ops[5] = DAG.getSrcValue(F);
4369
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004370 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE, dl,
Dan Gohmanfc166572009-04-09 23:54:40 +00004371 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4372 Ops, 6);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004373
4374 setValue(&I, Tmp);
4375 DAG.setRoot(Tmp.getValue(1));
4376 return 0;
4377 }
4378
4379 case Intrinsic::gcroot:
4380 if (GFI) {
4381 Value *Alloca = I.getOperand(1);
4382 Constant *TypeMap = cast<Constant>(I.getOperand(2));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004383
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004384 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4385 GFI->addStackRoot(FI->getIndex(), TypeMap);
4386 }
4387 return 0;
4388
4389 case Intrinsic::gcread:
4390 case Intrinsic::gcwrite:
4391 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
4392 return 0;
4393
4394 case Intrinsic::flt_rounds: {
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004395 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004396 return 0;
4397 }
4398
4399 case Intrinsic::trap: {
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004400 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004401 return 0;
4402 }
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004403
Bill Wendlingef375462008-11-21 02:38:44 +00004404 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00004405 return implVisitAluOverflow(I, ISD::UADDO);
4406 case Intrinsic::sadd_with_overflow:
4407 return implVisitAluOverflow(I, ISD::SADDO);
4408 case Intrinsic::usub_with_overflow:
4409 return implVisitAluOverflow(I, ISD::USUBO);
4410 case Intrinsic::ssub_with_overflow:
4411 return implVisitAluOverflow(I, ISD::SSUBO);
4412 case Intrinsic::umul_with_overflow:
4413 return implVisitAluOverflow(I, ISD::UMULO);
4414 case Intrinsic::smul_with_overflow:
4415 return implVisitAluOverflow(I, ISD::SMULO);
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004416
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004417 case Intrinsic::prefetch: {
4418 SDValue Ops[4];
4419 Ops[0] = getRoot();
4420 Ops[1] = getValue(I.getOperand(1));
4421 Ops[2] = getValue(I.getOperand(2));
4422 Ops[3] = getValue(I.getOperand(3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004423 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004424 return 0;
4425 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004426
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004427 case Intrinsic::memory_barrier: {
4428 SDValue Ops[6];
4429 Ops[0] = getRoot();
4430 for (int x = 1; x < 6; ++x)
4431 Ops[x] = getValue(I.getOperand(x));
4432
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004433 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004434 return 0;
4435 }
4436 case Intrinsic::atomic_cmp_swap: {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004437 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004438 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00004439 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004440 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4441 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004442 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004443 getValue(I.getOperand(2)),
4444 getValue(I.getOperand(3)),
4445 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004446 setValue(&I, L);
4447 DAG.setRoot(L.getValue(1));
4448 return 0;
4449 }
4450 case Intrinsic::atomic_load_add:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004451 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004452 case Intrinsic::atomic_load_sub:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004453 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004454 case Intrinsic::atomic_load_or:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004455 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004456 case Intrinsic::atomic_load_xor:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004457 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004458 case Intrinsic::atomic_load_and:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004459 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004460 case Intrinsic::atomic_load_nand:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004461 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004462 case Intrinsic::atomic_load_max:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004463 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004464 case Intrinsic::atomic_load_min:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004465 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004466 case Intrinsic::atomic_load_umin:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004467 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004468 case Intrinsic::atomic_load_umax:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004469 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004470 case Intrinsic::atomic_swap:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004471 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004472 }
4473}
4474
4475
4476void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4477 bool IsTailCall,
4478 MachineBasicBlock *LandingPad) {
4479 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4480 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4481 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4482 unsigned BeginLabel = 0, EndLabel = 0;
4483
4484 TargetLowering::ArgListTy Args;
4485 TargetLowering::ArgListEntry Entry;
4486 Args.reserve(CS.arg_size());
4487 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4488 i != e; ++i) {
4489 SDValue ArgNode = getValue(*i);
4490 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4491
4492 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00004493 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4494 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4495 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4496 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4497 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4498 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004499 Entry.Alignment = CS.getParamAlignment(attrInd);
4500 Args.push_back(Entry);
4501 }
4502
4503 if (LandingPad && MMI) {
4504 // Insert a label before the invoke call to mark the try range. This can be
4505 // used to detect deletion of the invoke via the MachineModuleInfo.
4506 BeginLabel = MMI->NextLabelID();
4507 // Both PendingLoads and PendingExports must be flushed here;
4508 // this call might not return.
4509 (void)getRoot();
Dale Johannesen8ad9b432009-02-04 01:17:06 +00004510 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4511 getControlRoot(), BeginLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004512 }
4513
4514 std::pair<SDValue,SDValue> Result =
4515 TLI.LowerCallTo(getRoot(), CS.getType(),
Devang Patel05988662008-09-25 21:00:45 +00004516 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004517 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4518 CS.paramHasAttr(0, Attribute::InReg),
4519 CS.getCallingConv(),
Dan Gohman1937e2f2008-09-16 01:42:28 +00004520 IsTailCall && PerformTailCallOpt,
Dale Johannesen66978ee2009-01-31 02:22:37 +00004521 Callee, Args, DAG, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004522 if (CS.getType() != Type::VoidTy)
4523 setValue(CS.getInstruction(), Result.first);
4524 DAG.setRoot(Result.second);
4525
4526 if (LandingPad && MMI) {
4527 // Insert a label at the end of the invoke call to mark the try range. This
4528 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4529 EndLabel = MMI->NextLabelID();
Dale Johannesen8ad9b432009-02-04 01:17:06 +00004530 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4531 getRoot(), EndLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004532
4533 // Inform MachineModuleInfo of range.
4534 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4535 }
4536}
4537
4538
4539void SelectionDAGLowering::visitCall(CallInst &I) {
4540 const char *RenameFn = 0;
4541 if (Function *F = I.getCalledFunction()) {
4542 if (F->isDeclaration()) {
Dale Johannesen49de9822009-02-05 01:49:45 +00004543 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4544 if (II) {
4545 if (unsigned IID = II->getIntrinsicID(F)) {
4546 RenameFn = visitIntrinsicCall(I, IID);
4547 if (!RenameFn)
4548 return;
4549 }
4550 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004551 if (unsigned IID = F->getIntrinsicID()) {
4552 RenameFn = visitIntrinsicCall(I, IID);
4553 if (!RenameFn)
4554 return;
4555 }
4556 }
4557
4558 // Check for well-known libc/libm calls. If the function is internal, it
4559 // can't be a library call.
4560 unsigned NameLen = F->getNameLen();
Rafael Espindolabb46f522009-01-15 20:18:42 +00004561 if (!F->hasLocalLinkage() && NameLen) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004562 const char *NameStr = F->getNameStart();
4563 if (NameStr[0] == 'c' &&
4564 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4565 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4566 if (I.getNumOperands() == 3 && // Basic sanity checks.
4567 I.getOperand(1)->getType()->isFloatingPoint() &&
4568 I.getType() == I.getOperand(1)->getType() &&
4569 I.getType() == I.getOperand(2)->getType()) {
4570 SDValue LHS = getValue(I.getOperand(1));
4571 SDValue RHS = getValue(I.getOperand(2));
Scott Michelfdc40a02009-02-17 22:15:04 +00004572 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004573 LHS.getValueType(), LHS, RHS));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004574 return;
4575 }
4576 } else if (NameStr[0] == 'f' &&
4577 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4578 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4579 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4580 if (I.getNumOperands() == 2 && // Basic sanity checks.
4581 I.getOperand(1)->getType()->isFloatingPoint() &&
4582 I.getType() == I.getOperand(1)->getType()) {
4583 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004584 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004585 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004586 return;
4587 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004588 } else if (NameStr[0] == 's' &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004589 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4590 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4591 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4592 if (I.getNumOperands() == 2 && // Basic sanity checks.
4593 I.getOperand(1)->getType()->isFloatingPoint() &&
4594 I.getType() == I.getOperand(1)->getType()) {
4595 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004596 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004597 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004598 return;
4599 }
4600 } else if (NameStr[0] == 'c' &&
4601 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4602 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4603 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4604 if (I.getNumOperands() == 2 && // Basic sanity checks.
4605 I.getOperand(1)->getType()->isFloatingPoint() &&
4606 I.getType() == I.getOperand(1)->getType()) {
4607 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004608 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004609 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004610 return;
4611 }
4612 }
4613 }
4614 } else if (isa<InlineAsm>(I.getOperand(0))) {
4615 visitInlineAsm(&I);
4616 return;
4617 }
4618
4619 SDValue Callee;
4620 if (!RenameFn)
4621 Callee = getValue(I.getOperand(0));
4622 else
Bill Wendling056292f2008-09-16 21:48:12 +00004623 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004624
4625 LowerCallTo(&I, Callee, I.isTailCall());
4626}
4627
4628
4629/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004630/// this value and returns the result as a ValueVT value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004631/// Chain/Flag as the input and updates them for the output Chain/Flag.
4632/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004633SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004634 SDValue &Chain,
4635 SDValue *Flag) const {
4636 // Assemble the legal parts into the final values.
4637 SmallVector<SDValue, 4> Values(ValueVTs.size());
4638 SmallVector<SDValue, 8> Parts;
4639 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4640 // Copy the legal parts from the registers.
4641 MVT ValueVT = ValueVTs[Value];
4642 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4643 MVT RegisterVT = RegVTs[Value];
4644
4645 Parts.resize(NumRegs);
4646 for (unsigned i = 0; i != NumRegs; ++i) {
4647 SDValue P;
4648 if (Flag == 0)
Dale Johannesena04b7572009-02-03 23:04:43 +00004649 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004650 else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004651 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004652 *Flag = P.getValue(2);
4653 }
4654 Chain = P.getValue(1);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004655
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004656 // If the source register was virtual and if we know something about it,
4657 // add an assert node.
4658 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4659 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4660 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4661 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4662 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4663 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004664
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004665 unsigned RegSize = RegisterVT.getSizeInBits();
4666 unsigned NumSignBits = LOI.NumSignBits;
4667 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004668
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004669 // FIXME: We capture more information than the dag can represent. For
4670 // now, just use the tightest assertzext/assertsext possible.
4671 bool isSExt = true;
4672 MVT FromVT(MVT::Other);
4673 if (NumSignBits == RegSize)
4674 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4675 else if (NumZeroBits >= RegSize-1)
4676 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4677 else if (NumSignBits > RegSize-8)
4678 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
Dan Gohman07c26ee2009-03-31 01:38:29 +00004679 else if (NumZeroBits >= RegSize-8)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004680 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4681 else if (NumSignBits > RegSize-16)
Bill Wendling181b6272008-10-19 20:34:04 +00004682 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
Dan Gohman07c26ee2009-03-31 01:38:29 +00004683 else if (NumZeroBits >= RegSize-16)
Bill Wendling181b6272008-10-19 20:34:04 +00004684 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004685 else if (NumSignBits > RegSize-32)
Bill Wendling181b6272008-10-19 20:34:04 +00004686 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
Dan Gohman07c26ee2009-03-31 01:38:29 +00004687 else if (NumZeroBits >= RegSize-32)
Bill Wendling181b6272008-10-19 20:34:04 +00004688 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004689
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004690 if (FromVT != MVT::Other) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00004691 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004692 RegisterVT, P, DAG.getValueType(FromVT));
4693
4694 }
4695 }
4696 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004697
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004698 Parts[i] = P;
4699 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004700
Scott Michelfdc40a02009-02-17 22:15:04 +00004701 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00004702 NumRegs, RegisterVT, ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004703 Part += NumRegs;
4704 Parts.clear();
4705 }
4706
Dale Johannesen66978ee2009-01-31 02:22:37 +00004707 return DAG.getNode(ISD::MERGE_VALUES, dl,
Duncan Sandsaaffa052008-12-01 11:41:29 +00004708 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4709 &Values[0], ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004710}
4711
4712/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004713/// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004714/// Chain/Flag as the input and updates them for the output Chain/Flag.
4715/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004716void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004717 SDValue &Chain, SDValue *Flag) const {
4718 // Get the list of the values's legal parts.
4719 unsigned NumRegs = Regs.size();
4720 SmallVector<SDValue, 8> Parts(NumRegs);
4721 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4722 MVT ValueVT = ValueVTs[Value];
4723 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4724 MVT RegisterVT = RegVTs[Value];
4725
Dale Johannesen66978ee2009-01-31 02:22:37 +00004726 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004727 &Parts[Part], NumParts, RegisterVT);
4728 Part += NumParts;
4729 }
4730
4731 // Copy the parts into the registers.
4732 SmallVector<SDValue, 8> Chains(NumRegs);
4733 for (unsigned i = 0; i != NumRegs; ++i) {
4734 SDValue Part;
4735 if (Flag == 0)
Dale Johannesena04b7572009-02-03 23:04:43 +00004736 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004737 else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004738 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004739 *Flag = Part.getValue(1);
4740 }
4741 Chains[i] = Part.getValue(0);
4742 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004743
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004744 if (NumRegs == 1 || Flag)
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004745 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004746 // flagged to it. That is the CopyToReg nodes and the user are considered
4747 // a single scheduling unit. If we create a TokenFactor and return it as
4748 // chain, then the TokenFactor is both a predecessor (operand) of the
4749 // user as well as a successor (the TF operands are flagged to the user).
4750 // c1, f1 = CopyToReg
4751 // c2, f2 = CopyToReg
4752 // c3 = TokenFactor c1, c2
4753 // ...
4754 // = op c3, ..., f2
4755 Chain = Chains[NumRegs-1];
4756 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00004757 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004758}
4759
4760/// AddInlineAsmOperands - Add this value to the specified inlineasm node
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004761/// operand list. This adds the code marker and includes the number of
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004762/// values added into it.
Evan Cheng697cbbf2009-03-20 18:03:34 +00004763void RegsForValue::AddInlineAsmOperands(unsigned Code,
4764 bool HasMatching,unsigned MatchingIdx,
4765 SelectionDAG &DAG,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004766 std::vector<SDValue> &Ops) const {
4767 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Evan Cheng697cbbf2009-03-20 18:03:34 +00004768 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
4769 unsigned Flag = Code | (Regs.size() << 3);
4770 if (HasMatching)
4771 Flag |= 0x80000000 | (MatchingIdx << 16);
4772 Ops.push_back(DAG.getTargetConstant(Flag, IntPtrTy));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004773 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4774 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4775 MVT RegisterVT = RegVTs[Value];
Chris Lattner58f15c42008-10-17 16:21:11 +00004776 for (unsigned i = 0; i != NumRegs; ++i) {
4777 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004778 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner58f15c42008-10-17 16:21:11 +00004779 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004780 }
4781}
4782
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004783/// isAllocatableRegister - If the specified register is safe to allocate,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004784/// i.e. it isn't a stack pointer or some other special register, return the
4785/// register class for the register. Otherwise, return null.
4786static const TargetRegisterClass *
4787isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4788 const TargetLowering &TLI,
4789 const TargetRegisterInfo *TRI) {
4790 MVT FoundVT = MVT::Other;
4791 const TargetRegisterClass *FoundRC = 0;
4792 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4793 E = TRI->regclass_end(); RCI != E; ++RCI) {
4794 MVT ThisVT = MVT::Other;
4795
4796 const TargetRegisterClass *RC = *RCI;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004797 // If none of the the value types for this register class are valid, we
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004798 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4799 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4800 I != E; ++I) {
4801 if (TLI.isTypeLegal(*I)) {
4802 // If we have already found this register in a different register class,
4803 // choose the one with the largest VT specified. For example, on
4804 // PowerPC, we favor f64 register classes over f32.
4805 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4806 ThisVT = *I;
4807 break;
4808 }
4809 }
4810 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004811
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004812 if (ThisVT == MVT::Other) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004813
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004814 // NOTE: This isn't ideal. In particular, this might allocate the
4815 // frame pointer in functions that need it (due to them not being taken
4816 // out of allocation, because a variable sized allocation hasn't been seen
4817 // yet). This is a slight code pessimization, but should still work.
4818 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4819 E = RC->allocation_order_end(MF); I != E; ++I)
4820 if (*I == Reg) {
4821 // We found a matching register class. Keep looking at others in case
4822 // we find one with larger registers that this physreg is also in.
4823 FoundRC = RC;
4824 FoundVT = ThisVT;
4825 break;
4826 }
4827 }
4828 return FoundRC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004829}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004830
4831
4832namespace llvm {
4833/// AsmOperandInfo - This contains information for each constraint that we are
4834/// lowering.
Cedric Venetaff9c272009-02-14 16:06:42 +00004835class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
Daniel Dunbarc0c3b9a2008-09-10 04:16:29 +00004836 public TargetLowering::AsmOperandInfo {
Cedric Venetaff9c272009-02-14 16:06:42 +00004837public:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004838 /// CallOperand - If this is the result output operand or a clobber
4839 /// this is null, otherwise it is the incoming operand to the CallInst.
4840 /// This gets modified as the asm is processed.
4841 SDValue CallOperand;
4842
4843 /// AssignedRegs - If this is a register or register class operand, this
4844 /// contains the set of register corresponding to the operand.
4845 RegsForValue AssignedRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004846
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004847 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4848 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4849 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004850
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004851 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4852 /// busy in OutputRegs/InputRegs.
4853 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004854 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004855 std::set<unsigned> &InputRegs,
4856 const TargetRegisterInfo &TRI) const {
4857 if (isOutReg) {
4858 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4859 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4860 }
4861 if (isInReg) {
4862 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4863 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4864 }
4865 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004866
Chris Lattner81249c92008-10-17 17:05:25 +00004867 /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4868 /// corresponds to. If there is no Value* for this operand, it returns
4869 /// MVT::Other.
4870 MVT getCallOperandValMVT(const TargetLowering &TLI,
4871 const TargetData *TD) const {
4872 if (CallOperandVal == 0) return MVT::Other;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004873
Chris Lattner81249c92008-10-17 17:05:25 +00004874 if (isa<BasicBlock>(CallOperandVal))
4875 return TLI.getPointerTy();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004876
Chris Lattner81249c92008-10-17 17:05:25 +00004877 const llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004878
Chris Lattner81249c92008-10-17 17:05:25 +00004879 // If this is an indirect operand, the operand is a pointer to the
4880 // accessed type.
4881 if (isIndirect)
4882 OpTy = cast<PointerType>(OpTy)->getElementType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004883
Chris Lattner81249c92008-10-17 17:05:25 +00004884 // If OpTy is not a single value, it may be a struct/union that we
4885 // can tile with integers.
4886 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4887 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4888 switch (BitSize) {
4889 default: break;
4890 case 1:
4891 case 8:
4892 case 16:
4893 case 32:
4894 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00004895 case 128:
Chris Lattner81249c92008-10-17 17:05:25 +00004896 OpTy = IntegerType::get(BitSize);
4897 break;
4898 }
4899 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004900
Chris Lattner81249c92008-10-17 17:05:25 +00004901 return TLI.getValueType(OpTy, true);
4902 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004903
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004904private:
4905 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4906 /// specified set.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004907 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004908 const TargetRegisterInfo &TRI) {
4909 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4910 Regs.insert(Reg);
4911 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4912 for (; *Aliases; ++Aliases)
4913 Regs.insert(*Aliases);
4914 }
4915};
4916} // end llvm namespace.
4917
4918
4919/// GetRegistersForValue - Assign registers (virtual or physical) for the
4920/// specified operand. We prefer to assign virtual registers, to allow the
4921/// register allocator handle the assignment process. However, if the asm uses
4922/// features that we can't model on machineinstrs, we have SDISel do the
4923/// allocation. This produces generally horrible, but correct, code.
4924///
4925/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004926/// Input and OutputRegs are the set of already allocated physical registers.
4927///
4928void SelectionDAGLowering::
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004929GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004930 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004931 std::set<unsigned> &InputRegs) {
4932 // Compute whether this value requires an input register, an output register,
4933 // or both.
4934 bool isOutReg = false;
4935 bool isInReg = false;
4936 switch (OpInfo.Type) {
4937 case InlineAsm::isOutput:
4938 isOutReg = true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004939
4940 // If there is an input constraint that matches this, we need to reserve
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004941 // the input register so no other inputs allocate to it.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004942 isInReg = OpInfo.hasMatchingInput();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004943 break;
4944 case InlineAsm::isInput:
4945 isInReg = true;
4946 isOutReg = false;
4947 break;
4948 case InlineAsm::isClobber:
4949 isOutReg = true;
4950 isInReg = true;
4951 break;
4952 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004953
4954
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004955 MachineFunction &MF = DAG.getMachineFunction();
4956 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004957
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004958 // If this is a constraint for a single physreg, or a constraint for a
4959 // register class, find it.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004960 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004961 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4962 OpInfo.ConstraintVT);
4963
4964 unsigned NumRegs = 1;
Chris Lattner01426e12008-10-21 00:45:36 +00004965 if (OpInfo.ConstraintVT != MVT::Other) {
4966 // If this is a FP input in an integer register (or visa versa) insert a bit
4967 // cast of the input value. More generally, handle any case where the input
4968 // value disagrees with the register class we plan to stick this in.
4969 if (OpInfo.Type == InlineAsm::isInput &&
4970 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4971 // Try to convert to the first MVT that the reg class contains. If the
4972 // types are identical size, use a bitcast to convert (e.g. two differing
4973 // vector types).
4974 MVT RegVT = *PhysReg.second->vt_begin();
4975 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00004976 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004977 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00004978 OpInfo.ConstraintVT = RegVT;
4979 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4980 // If the input is a FP value and we want it in FP registers, do a
4981 // bitcast to the corresponding integer type. This turns an f64 value
4982 // into i64, which can be passed with two i32 values on a 32-bit
4983 // machine.
4984 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
Dale Johannesen66978ee2009-01-31 02:22:37 +00004985 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004986 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00004987 OpInfo.ConstraintVT = RegVT;
4988 }
4989 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004990
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004991 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00004992 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004993
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004994 MVT RegVT;
4995 MVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004996
4997 // If this is a constraint for a specific physical register, like {r17},
4998 // assign it now.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004999 if (unsigned AssignedReg = PhysReg.first) {
5000 const TargetRegisterClass *RC = PhysReg.second;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005001 if (OpInfo.ConstraintVT == MVT::Other)
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005002 ValueVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005003
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005004 // Get the actual register value type. This is important, because the user
5005 // may have asked for (e.g.) the AX register in i32 type. We need to
5006 // remember that AX is actually i16 to get the right extension.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005007 RegVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005008
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005009 // This is a explicit reference to a physical register.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005010 Regs.push_back(AssignedReg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005011
5012 // If this is an expanded reference, add the rest of the regs to Regs.
5013 if (NumRegs != 1) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005014 TargetRegisterClass::iterator I = RC->begin();
5015 for (; *I != AssignedReg; ++I)
5016 assert(I != RC->end() && "Didn't find reg!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005017
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005018 // Already added the first reg.
5019 --NumRegs; ++I;
5020 for (; NumRegs; --NumRegs, ++I) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00005021 assert(I != RC->end() && "Ran out of registers to allocate!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005022 Regs.push_back(*I);
5023 }
5024 }
5025 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5026 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5027 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5028 return;
5029 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005030
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005031 // Otherwise, if this was a reference to an LLVM register class, create vregs
5032 // for this reference.
Chris Lattnerb3b44842009-03-24 15:25:07 +00005033 if (const TargetRegisterClass *RC = PhysReg.second) {
5034 RegVT = *RC->vt_begin();
Evan Chengfb112882009-03-23 08:01:15 +00005035 if (OpInfo.ConstraintVT == MVT::Other)
5036 ValueVT = RegVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005037
Evan Chengfb112882009-03-23 08:01:15 +00005038 // Create the appropriate number of virtual registers.
5039 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5040 for (; NumRegs; --NumRegs)
Chris Lattnerb3b44842009-03-24 15:25:07 +00005041 Regs.push_back(RegInfo.createVirtualRegister(RC));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005042
Evan Chengfb112882009-03-23 08:01:15 +00005043 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5044 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005045 }
Chris Lattnerfc9d1612009-03-24 15:22:11 +00005046
5047 // This is a reference to a register class that doesn't directly correspond
5048 // to an LLVM register class. Allocate NumRegs consecutive, available,
5049 // registers from the class.
5050 std::vector<unsigned> RegClassRegs
5051 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5052 OpInfo.ConstraintVT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005053
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005054 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5055 unsigned NumAllocated = 0;
5056 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5057 unsigned Reg = RegClassRegs[i];
5058 // See if this register is available.
5059 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5060 (isInReg && InputRegs.count(Reg))) { // Already used.
5061 // Make sure we find consecutive registers.
5062 NumAllocated = 0;
5063 continue;
5064 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005065
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005066 // Check to see if this register is allocatable (i.e. don't give out the
5067 // stack pointer).
Chris Lattnerfc9d1612009-03-24 15:22:11 +00005068 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5069 if (!RC) { // Couldn't allocate this register.
5070 // Reset NumAllocated to make sure we return consecutive registers.
5071 NumAllocated = 0;
5072 continue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005073 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005074
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005075 // Okay, this register is good, we can use it.
5076 ++NumAllocated;
5077
5078 // If we allocated enough consecutive registers, succeed.
5079 if (NumAllocated == NumRegs) {
5080 unsigned RegStart = (i-NumAllocated)+1;
5081 unsigned RegEnd = i+1;
5082 // Mark all of the allocated registers used.
5083 for (unsigned i = RegStart; i != RegEnd; ++i)
5084 Regs.push_back(RegClassRegs[i]);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005085
5086 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005087 OpInfo.ConstraintVT);
5088 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5089 return;
5090 }
5091 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005092
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005093 // Otherwise, we couldn't allocate enough registers for this.
5094}
5095
Evan Chengda43bcf2008-09-24 00:05:32 +00005096/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5097/// processed uses a memory 'm' constraint.
5098static bool
5099hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
Dan Gohmane9530ec2009-01-15 16:58:17 +00005100 const TargetLowering &TLI) {
Evan Chengda43bcf2008-09-24 00:05:32 +00005101 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5102 InlineAsm::ConstraintInfo &CI = CInfos[i];
5103 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5104 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5105 if (CType == TargetLowering::C_Memory)
5106 return true;
5107 }
Chris Lattner6c147292009-04-30 00:48:50 +00005108
5109 // Indirect operand accesses access memory.
5110 if (CI.isIndirect)
5111 return true;
Evan Chengda43bcf2008-09-24 00:05:32 +00005112 }
5113
5114 return false;
5115}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005116
5117/// visitInlineAsm - Handle a call to an InlineAsm object.
5118///
5119void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
5120 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5121
5122 /// ConstraintOperands - Information about all of the constraints.
5123 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005124
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005125 std::set<unsigned> OutputRegs, InputRegs;
5126
5127 // Do a prepass over the constraints, canonicalizing them, and building up the
5128 // ConstraintOperands list.
5129 std::vector<InlineAsm::ConstraintInfo>
5130 ConstraintInfos = IA->ParseConstraints();
5131
Evan Chengda43bcf2008-09-24 00:05:32 +00005132 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Chris Lattner6c147292009-04-30 00:48:50 +00005133
5134 SDValue Chain, Flag;
5135
5136 // We won't need to flush pending loads if this asm doesn't touch
5137 // memory and is nonvolatile.
5138 if (hasMemory || IA->hasSideEffects())
Dale Johannesen97d14fc2009-04-18 00:09:40 +00005139 Chain = getRoot();
Chris Lattner6c147292009-04-30 00:48:50 +00005140 else
5141 Chain = DAG.getRoot();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005142
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005143 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5144 unsigned ResNo = 0; // ResNo - The result number of the next output.
5145 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5146 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5147 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005148
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005149 MVT OpVT = MVT::Other;
5150
5151 // Compute the value type for each operand.
5152 switch (OpInfo.Type) {
5153 case InlineAsm::isOutput:
5154 // Indirect outputs just consume an argument.
5155 if (OpInfo.isIndirect) {
5156 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5157 break;
5158 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005159
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005160 // The return value of the call is this value. As such, there is no
5161 // corresponding argument.
5162 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5163 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5164 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5165 } else {
5166 assert(ResNo == 0 && "Asm only has one result!");
5167 OpVT = TLI.getValueType(CS.getType());
5168 }
5169 ++ResNo;
5170 break;
5171 case InlineAsm::isInput:
5172 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5173 break;
5174 case InlineAsm::isClobber:
5175 // Nothing to do.
5176 break;
5177 }
5178
5179 // If this is an input or an indirect output, process the call argument.
5180 // BasicBlocks are labels, currently appearing only in asm's.
5181 if (OpInfo.CallOperandVal) {
Chris Lattner81249c92008-10-17 17:05:25 +00005182 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005183 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00005184 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005185 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005186 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005187
Chris Lattner81249c92008-10-17 17:05:25 +00005188 OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005189 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005190
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005191 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005192 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005193
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005194 // Second pass over the constraints: compute which constraint option to use
5195 // and assign registers to constraints that want a specific physreg.
5196 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5197 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005198
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005199 // If this is an output operand with a matching input operand, look up the
Evan Cheng09dc9c02008-12-16 18:21:39 +00005200 // matching input. If their types mismatch, e.g. one is an integer, the
5201 // other is floating point, or their sizes are different, flag it as an
5202 // error.
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005203 if (OpInfo.hasMatchingInput()) {
5204 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5205 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Evan Cheng09dc9c02008-12-16 18:21:39 +00005206 if ((OpInfo.ConstraintVT.isInteger() !=
5207 Input.ConstraintVT.isInteger()) ||
5208 (OpInfo.ConstraintVT.getSizeInBits() !=
5209 Input.ConstraintVT.getSizeInBits())) {
Daniel Dunbar4cbb1732009-04-13 22:26:09 +00005210 cerr << "llvm: error: Unsupported asm: input constraint with a "
5211 << "matching output constraint of incompatible type!\n";
Evan Cheng09dc9c02008-12-16 18:21:39 +00005212 exit(1);
5213 }
5214 Input.ConstraintVT = OpInfo.ConstraintVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005215 }
5216 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005217
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005218 // Compute the constraint code and ConstraintType to use.
Evan Chengda43bcf2008-09-24 00:05:32 +00005219 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005220
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005221 // If this is a memory input, and if the operand is not indirect, do what we
5222 // need to to provide an address for the memory input.
5223 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5224 !OpInfo.isIndirect) {
5225 assert(OpInfo.Type == InlineAsm::isInput &&
5226 "Can only indirectify direct input operands!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005227
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005228 // Memory operands really want the address of the value. If we don't have
5229 // an indirect input, put it in the constpool if we can, otherwise spill
5230 // it to a stack slot.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005231
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005232 // If the operand is a float, integer, or vector constant, spill to a
5233 // constant pool entry to get its address.
5234 Value *OpVal = OpInfo.CallOperandVal;
5235 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5236 isa<ConstantVector>(OpVal)) {
5237 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5238 TLI.getPointerTy());
5239 } else {
5240 // Otherwise, create a stack slot and emit a store to it before the
5241 // asm.
5242 const Type *Ty = OpVal->getType();
Duncan Sands777d2302009-05-09 07:06:46 +00005243 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005244 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5245 MachineFunction &MF = DAG.getMachineFunction();
5246 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
5247 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Dale Johannesen66978ee2009-01-31 02:22:37 +00005248 Chain = DAG.getStore(Chain, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005249 OpInfo.CallOperand, StackSlot, NULL, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005250 OpInfo.CallOperand = StackSlot;
5251 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005252
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005253 // There is no longer a Value* corresponding to this operand.
5254 OpInfo.CallOperandVal = 0;
5255 // It is now an indirect operand.
5256 OpInfo.isIndirect = true;
5257 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005258
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005259 // If this constraint is for a specific register, allocate it before
5260 // anything else.
5261 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005262 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005263 }
5264 ConstraintInfos.clear();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005265
5266
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005267 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00005268 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005269 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5270 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005271
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005272 // C_Register operands have already been allocated, Other/Memory don't need
5273 // to be.
5274 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005275 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005276 }
5277
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005278 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5279 std::vector<SDValue> AsmNodeOperands;
5280 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5281 AsmNodeOperands.push_back(
Bill Wendling056292f2008-09-16 21:48:12 +00005282 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005283
5284
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005285 // Loop over all of the inputs, copying the operand values into the
5286 // appropriate registers and processing the output regs.
5287 RegsForValue RetValRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005288
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005289 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5290 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005291
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005292 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5293 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5294
5295 switch (OpInfo.Type) {
5296 case InlineAsm::isOutput: {
5297 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5298 OpInfo.ConstraintType != TargetLowering::C_Register) {
5299 // Memory output, or 'other' output (e.g. 'X' constraint).
5300 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5301
5302 // Add information to the INLINEASM node to know about this output.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005303 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5304 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005305 TLI.getPointerTy()));
5306 AsmNodeOperands.push_back(OpInfo.CallOperand);
5307 break;
5308 }
5309
5310 // Otherwise, this is a register or register class output.
5311
5312 // Copy the output from the appropriate register. Find a register that
5313 // we can use.
5314 if (OpInfo.AssignedRegs.Regs.empty()) {
Daniel Dunbar4cbb1732009-04-13 22:26:09 +00005315 cerr << "llvm: error: Couldn't allocate output reg for constraint '"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005316 << OpInfo.ConstraintCode << "'!\n";
5317 exit(1);
5318 }
5319
5320 // If this is an indirect operand, store through the pointer after the
5321 // asm.
5322 if (OpInfo.isIndirect) {
5323 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5324 OpInfo.CallOperandVal));
5325 } else {
5326 // This is the result value of the call.
5327 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5328 // Concatenate this output onto the outputs list.
5329 RetValRegs.append(OpInfo.AssignedRegs);
5330 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005331
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005332 // Add information to the INLINEASM node to know that this register is
5333 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00005334 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5335 6 /* EARLYCLOBBER REGDEF */ :
5336 2 /* REGDEF */ ,
Evan Chengfb112882009-03-23 08:01:15 +00005337 false,
5338 0,
Dale Johannesen913d3df2008-09-12 17:49:03 +00005339 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005340 break;
5341 }
5342 case InlineAsm::isInput: {
5343 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005344
Chris Lattner6bdcda32008-10-17 16:47:46 +00005345 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005346 // If this is required to match an output register we have already set,
5347 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00005348 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005349
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005350 // Scan until we find the definition we already emitted of this operand.
5351 // When we find it, create a RegsForValue operand.
5352 unsigned CurOp = 2; // The first operand.
5353 for (; OperandNo; --OperandNo) {
5354 // Advance to the next operand.
Evan Cheng697cbbf2009-03-20 18:03:34 +00005355 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005356 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005357 assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5358 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5359 (OpFlag & 7) == 4 /*MEM*/) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005360 "Skipped past definitions?");
Evan Cheng697cbbf2009-03-20 18:03:34 +00005361 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005362 }
5363
Evan Cheng697cbbf2009-03-20 18:03:34 +00005364 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005365 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005366 if ((OpFlag & 7) == 2 /*REGDEF*/
5367 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5368 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
Dan Gohmane340e842009-05-14 00:30:16 +00005369 assert(!OpInfo.isIndirect &&
5370 "Don't know how to handle tied indirect register inputs yet!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005371 RegsForValue MatchedRegs;
5372 MatchedRegs.TLI = &TLI;
5373 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
Evan Chengfb112882009-03-23 08:01:15 +00005374 MVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5375 MatchedRegs.RegVTs.push_back(RegVT);
5376 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005377 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
Evan Chengfb112882009-03-23 08:01:15 +00005378 i != e; ++i)
5379 MatchedRegs.Regs.
5380 push_back(RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005381
5382 // Use the produced MatchedRegs object to
Dale Johannesen66978ee2009-01-31 02:22:37 +00005383 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5384 Chain, &Flag);
Evan Chengfb112882009-03-23 08:01:15 +00005385 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5386 true, OpInfo.getMatchedOperand(),
Evan Cheng697cbbf2009-03-20 18:03:34 +00005387 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005388 break;
5389 } else {
Evan Cheng697cbbf2009-03-20 18:03:34 +00005390 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5391 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5392 "Unexpected number of operands");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005393 // Add information to the INLINEASM node to know about this input.
Evan Chengfb112882009-03-23 08:01:15 +00005394 // See InlineAsm.h isUseOperandTiedToDef.
5395 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
Evan Cheng697cbbf2009-03-20 18:03:34 +00005396 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005397 TLI.getPointerTy()));
5398 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5399 break;
5400 }
5401 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005402
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005403 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005404 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005405 "Don't know how to handle indirect other inputs yet!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005406
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005407 std::vector<SDValue> Ops;
5408 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Chengda43bcf2008-09-24 00:05:32 +00005409 hasMemory, Ops, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005410 if (Ops.empty()) {
Daniel Dunbar4cbb1732009-04-13 22:26:09 +00005411 cerr << "llvm: error: Invalid operand for inline asm constraint '"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005412 << OpInfo.ConstraintCode << "'!\n";
5413 exit(1);
5414 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005415
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005416 // Add information to the INLINEASM node to know about this input.
5417 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005418 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005419 TLI.getPointerTy()));
5420 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5421 break;
5422 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5423 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5424 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5425 "Memory operands expect pointer values");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005426
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005427 // Add information to the INLINEASM node to know about this input.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005428 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5429 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005430 TLI.getPointerTy()));
5431 AsmNodeOperands.push_back(InOperandVal);
5432 break;
5433 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005434
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005435 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5436 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5437 "Unknown constraint type!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005438 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005439 "Don't know how to handle indirect register inputs yet!");
5440
5441 // Copy the input into the appropriate registers.
Evan Chengaa765b82008-09-25 00:14:04 +00005442 if (OpInfo.AssignedRegs.Regs.empty()) {
Daniel Dunbar4cbb1732009-04-13 22:26:09 +00005443 cerr << "llvm: error: Couldn't allocate output reg for constraint '"
Evan Chengaa765b82008-09-25 00:14:04 +00005444 << OpInfo.ConstraintCode << "'!\n";
5445 exit(1);
5446 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005447
Dale Johannesen66978ee2009-01-31 02:22:37 +00005448 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5449 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005450
Evan Cheng697cbbf2009-03-20 18:03:34 +00005451 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
Dale Johannesen86b49f82008-09-24 01:07:17 +00005452 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005453 break;
5454 }
5455 case InlineAsm::isClobber: {
5456 // Add the clobbered value to the operand list, so that the register
5457 // allocator is aware that the physreg got clobbered.
5458 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesen91aac102008-09-17 21:13:11 +00005459 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
Evan Cheng697cbbf2009-03-20 18:03:34 +00005460 false, 0, DAG,AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005461 break;
5462 }
5463 }
5464 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005465
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005466 // Finish up input operands.
5467 AsmNodeOperands[0] = Chain;
5468 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005469
Dale Johannesen66978ee2009-01-31 02:22:37 +00005470 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00005471 DAG.getVTList(MVT::Other, MVT::Flag),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005472 &AsmNodeOperands[0], AsmNodeOperands.size());
5473 Flag = Chain.getValue(1);
5474
5475 // If this asm returns a register value, copy the result from that register
5476 // and set it as the value of the call.
5477 if (!RetValRegs.Regs.empty()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00005478 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00005479 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005480
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005481 // FIXME: Why don't we do this for inline asms with MRVs?
5482 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5483 MVT ResultType = TLI.getValueType(CS.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005484
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005485 // If any of the results of the inline asm is a vector, it may have the
5486 // wrong width/num elts. This can happen for register classes that can
5487 // contain multiple different value types. The preg or vreg allocated may
5488 // not have the same VT as was expected. Convert it to the right type
5489 // with bit_convert.
5490 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005491 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005492 ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005493
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005494 } else if (ResultType != Val.getValueType() &&
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005495 ResultType.isInteger() && Val.getValueType().isInteger()) {
5496 // If a result value was tied to an input value, the computed result may
5497 // have a wider width than the expected result. Extract the relevant
5498 // portion.
Dale Johannesen66978ee2009-01-31 02:22:37 +00005499 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005500 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005501
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005502 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00005503 }
Dan Gohman95915732008-10-18 01:03:45 +00005504
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005505 setValue(CS.getInstruction(), Val);
Dale Johannesenec65a7d2009-04-14 00:56:56 +00005506 // Don't need to use this as a chain in this case.
5507 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5508 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005509 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005510
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005511 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005512
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005513 // Process indirect outputs, first output all of the flagged copies out of
5514 // physregs.
5515 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5516 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5517 Value *Ptr = IndirectStoresToEmit[i].second;
Dale Johannesen66978ee2009-01-31 02:22:37 +00005518 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5519 Chain, &Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005520 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6c147292009-04-30 00:48:50 +00005521
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005522 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005523
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005524 // Emit the non-flagged stores from the physregs.
5525 SmallVector<SDValue, 8> OutChains;
5526 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00005527 OutChains.push_back(DAG.getStore(Chain, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005528 StoresToEmit[i].first,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005529 getValue(StoresToEmit[i].second),
5530 StoresToEmit[i].second, 0));
5531 if (!OutChains.empty())
Dale Johannesen66978ee2009-01-31 02:22:37 +00005532 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005533 &OutChains[0], OutChains.size());
5534 DAG.setRoot(Chain);
5535}
5536
5537
5538void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5539 SDValue Src = getValue(I.getOperand(0));
5540
Chris Lattner0b18e592009-03-17 19:36:00 +00005541 // Scale up by the type size in the original i32 type width. Various
5542 // mid-level optimizers may make assumptions about demanded bits etc from the
5543 // i32-ness of the optimizer: we do not want to promote to i64 and then
5544 // multiply on 64-bit targets.
5545 // FIXME: Malloc inst should go away: PR715.
Duncan Sands777d2302009-05-09 07:06:46 +00005546 uint64_t ElementSize = TD->getTypeAllocSize(I.getType()->getElementType());
Chris Lattner0b18e592009-03-17 19:36:00 +00005547 if (ElementSize != 1)
5548 Src = DAG.getNode(ISD::MUL, getCurDebugLoc(), Src.getValueType(),
5549 Src, DAG.getConstant(ElementSize, Src.getValueType()));
5550
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005551 MVT IntPtr = TLI.getPointerTy();
5552
5553 if (IntPtr.bitsLT(Src.getValueType()))
Dale Johannesen66978ee2009-01-31 02:22:37 +00005554 Src = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), IntPtr, Src);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005555 else if (IntPtr.bitsGT(Src.getValueType()))
Dale Johannesen66978ee2009-01-31 02:22:37 +00005556 Src = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), IntPtr, Src);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005557
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005558 TargetLowering::ArgListTy Args;
5559 TargetLowering::ArgListEntry Entry;
5560 Entry.Node = Src;
5561 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5562 Args.push_back(Entry);
5563
5564 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005565 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005566 CallingConv::C, PerformTailCallOpt,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005567 DAG.getExternalSymbol("malloc", IntPtr),
Dale Johannesen66978ee2009-01-31 02:22:37 +00005568 Args, DAG, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005569 setValue(&I, Result.first); // Pointers always fit in registers
5570 DAG.setRoot(Result.second);
5571}
5572
5573void SelectionDAGLowering::visitFree(FreeInst &I) {
5574 TargetLowering::ArgListTy Args;
5575 TargetLowering::ArgListEntry Entry;
5576 Entry.Node = getValue(I.getOperand(0));
5577 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5578 Args.push_back(Entry);
5579 MVT IntPtr = TLI.getPointerTy();
5580 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005581 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
Dan Gohman1937e2f2008-09-16 01:42:28 +00005582 CallingConv::C, PerformTailCallOpt,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005583 DAG.getExternalSymbol("free", IntPtr), Args, DAG,
Dale Johannesen66978ee2009-01-31 02:22:37 +00005584 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005585 DAG.setRoot(Result.second);
5586}
5587
5588void SelectionDAGLowering::visitVAStart(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005589 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005590 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005591 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005592 DAG.getSrcValue(I.getOperand(1))));
5593}
5594
5595void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Dale Johannesena04b7572009-02-03 23:04:43 +00005596 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5597 getRoot(), getValue(I.getOperand(0)),
5598 DAG.getSrcValue(I.getOperand(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005599 setValue(&I, V);
5600 DAG.setRoot(V.getValue(1));
5601}
5602
5603void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005604 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005605 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005606 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005607 DAG.getSrcValue(I.getOperand(1))));
5608}
5609
5610void SelectionDAGLowering::visitVACopy(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005611 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005612 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005613 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005614 getValue(I.getOperand(2)),
5615 DAG.getSrcValue(I.getOperand(1)),
5616 DAG.getSrcValue(I.getOperand(2))));
5617}
5618
5619/// TargetLowering::LowerArguments - This is the default LowerArguments
5620/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005621/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005622/// integrated into SDISel.
5623void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005624 SmallVectorImpl<SDValue> &ArgValues,
5625 DebugLoc dl) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005626 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5627 SmallVector<SDValue, 3+16> Ops;
5628 Ops.push_back(DAG.getRoot());
5629 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5630 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5631
5632 // Add one result value for each formal argument.
5633 SmallVector<MVT, 16> RetVals;
5634 unsigned j = 1;
5635 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5636 I != E; ++I, ++j) {
5637 SmallVector<MVT, 4> ValueVTs;
5638 ComputeValueVTs(*this, I->getType(), ValueVTs);
5639 for (unsigned Value = 0, NumValues = ValueVTs.size();
5640 Value != NumValues; ++Value) {
5641 MVT VT = ValueVTs[Value];
5642 const Type *ArgTy = VT.getTypeForMVT();
5643 ISD::ArgFlagsTy Flags;
5644 unsigned OriginalAlignment =
5645 getTargetData()->getABITypeAlignment(ArgTy);
5646
Devang Patel05988662008-09-25 21:00:45 +00005647 if (F.paramHasAttr(j, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005648 Flags.setZExt();
Devang Patel05988662008-09-25 21:00:45 +00005649 if (F.paramHasAttr(j, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005650 Flags.setSExt();
Devang Patel05988662008-09-25 21:00:45 +00005651 if (F.paramHasAttr(j, Attribute::InReg))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005652 Flags.setInReg();
Devang Patel05988662008-09-25 21:00:45 +00005653 if (F.paramHasAttr(j, Attribute::StructRet))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005654 Flags.setSRet();
Devang Patel05988662008-09-25 21:00:45 +00005655 if (F.paramHasAttr(j, Attribute::ByVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005656 Flags.setByVal();
5657 const PointerType *Ty = cast<PointerType>(I->getType());
5658 const Type *ElementTy = Ty->getElementType();
5659 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sands777d2302009-05-09 07:06:46 +00005660 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005661 // For ByVal, alignment should be passed from FE. BE will guess if
5662 // this info is not there but there are cases it cannot get right.
5663 if (F.getParamAlignment(j))
5664 FrameAlign = F.getParamAlignment(j);
5665 Flags.setByValAlign(FrameAlign);
5666 Flags.setByValSize(FrameSize);
5667 }
Devang Patel05988662008-09-25 21:00:45 +00005668 if (F.paramHasAttr(j, Attribute::Nest))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005669 Flags.setNest();
5670 Flags.setOrigAlign(OriginalAlignment);
5671
5672 MVT RegisterVT = getRegisterType(VT);
5673 unsigned NumRegs = getNumRegisters(VT);
5674 for (unsigned i = 0; i != NumRegs; ++i) {
5675 RetVals.push_back(RegisterVT);
5676 ISD::ArgFlagsTy MyFlags = Flags;
5677 if (NumRegs > 1 && i == 0)
5678 MyFlags.setSplit();
5679 // if it isn't first piece, alignment must be 1
5680 else if (i > 0)
5681 MyFlags.setOrigAlign(1);
5682 Ops.push_back(DAG.getArgFlags(MyFlags));
5683 }
5684 }
5685 }
5686
5687 RetVals.push_back(MVT::Other);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005688
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005689 // Create the node.
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005690 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005691 DAG.getVTList(&RetVals[0], RetVals.size()),
5692 &Ops[0], Ops.size()).getNode();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005693
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005694 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5695 // allows exposing the loads that may be part of the argument access to the
5696 // first DAGCombiner pass.
5697 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005698
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005699 // The number of results should match up, except that the lowered one may have
5700 // an extra flag result.
5701 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5702 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5703 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5704 && "Lowering produced unexpected number of results!");
5705
5706 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5707 if (Result != TmpRes.getNode() && Result->use_empty()) {
5708 HandleSDNode Dummy(DAG.getRoot());
5709 DAG.RemoveDeadNode(Result);
5710 }
5711
5712 Result = TmpRes.getNode();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005713
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005714 unsigned NumArgRegs = Result->getNumValues() - 1;
5715 DAG.setRoot(SDValue(Result, NumArgRegs));
5716
5717 // Set up the return result vector.
5718 unsigned i = 0;
5719 unsigned Idx = 1;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005720 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005721 ++I, ++Idx) {
5722 SmallVector<MVT, 4> ValueVTs;
5723 ComputeValueVTs(*this, I->getType(), ValueVTs);
5724 for (unsigned Value = 0, NumValues = ValueVTs.size();
5725 Value != NumValues; ++Value) {
5726 MVT VT = ValueVTs[Value];
5727 MVT PartVT = getRegisterType(VT);
5728
5729 unsigned NumParts = getNumRegisters(VT);
5730 SmallVector<SDValue, 4> Parts(NumParts);
5731 for (unsigned j = 0; j != NumParts; ++j)
5732 Parts[j] = SDValue(Result, i++);
5733
5734 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Devang Patel05988662008-09-25 21:00:45 +00005735 if (F.paramHasAttr(Idx, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005736 AssertOp = ISD::AssertSext;
Devang Patel05988662008-09-25 21:00:45 +00005737 else if (F.paramHasAttr(Idx, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005738 AssertOp = ISD::AssertZext;
5739
Dale Johannesen66978ee2009-01-31 02:22:37 +00005740 ArgValues.push_back(getCopyFromParts(DAG, dl, &Parts[0], NumParts,
5741 PartVT, VT, AssertOp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005742 }
5743 }
5744 assert(i == NumArgRegs && "Argument register count mismatch!");
5745}
5746
5747
5748/// TargetLowering::LowerCallTo - This is the default LowerCallTo
5749/// implementation, which just inserts an ISD::CALL node, which is later custom
5750/// lowered by the target to something concrete. FIXME: When all targets are
5751/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5752std::pair<SDValue, SDValue>
5753TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5754 bool RetSExt, bool RetZExt, bool isVarArg,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005755 bool isInreg,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005756 unsigned CallingConv, bool isTailCall,
5757 SDValue Callee,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005758 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
Dan Gohman1937e2f2008-09-16 01:42:28 +00005759 assert((!isTailCall || PerformTailCallOpt) &&
5760 "isTailCall set when tail-call optimizations are disabled!");
5761
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005762 SmallVector<SDValue, 32> Ops;
5763 Ops.push_back(Chain); // Op#0 - Chain
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005764 Ops.push_back(Callee);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005765
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005766 // Handle all of the outgoing arguments.
5767 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5768 SmallVector<MVT, 4> ValueVTs;
5769 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5770 for (unsigned Value = 0, NumValues = ValueVTs.size();
5771 Value != NumValues; ++Value) {
5772 MVT VT = ValueVTs[Value];
5773 const Type *ArgTy = VT.getTypeForMVT();
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005774 SDValue Op = SDValue(Args[i].Node.getNode(),
5775 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005776 ISD::ArgFlagsTy Flags;
5777 unsigned OriginalAlignment =
5778 getTargetData()->getABITypeAlignment(ArgTy);
5779
5780 if (Args[i].isZExt)
5781 Flags.setZExt();
5782 if (Args[i].isSExt)
5783 Flags.setSExt();
5784 if (Args[i].isInReg)
5785 Flags.setInReg();
5786 if (Args[i].isSRet)
5787 Flags.setSRet();
5788 if (Args[i].isByVal) {
5789 Flags.setByVal();
5790 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5791 const Type *ElementTy = Ty->getElementType();
5792 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sands777d2302009-05-09 07:06:46 +00005793 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005794 // For ByVal, alignment should come from FE. BE will guess if this
5795 // info is not there but there are cases it cannot get right.
5796 if (Args[i].Alignment)
5797 FrameAlign = Args[i].Alignment;
5798 Flags.setByValAlign(FrameAlign);
5799 Flags.setByValSize(FrameSize);
5800 }
5801 if (Args[i].isNest)
5802 Flags.setNest();
5803 Flags.setOrigAlign(OriginalAlignment);
5804
5805 MVT PartVT = getRegisterType(VT);
5806 unsigned NumParts = getNumRegisters(VT);
5807 SmallVector<SDValue, 4> Parts(NumParts);
5808 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5809
5810 if (Args[i].isSExt)
5811 ExtendKind = ISD::SIGN_EXTEND;
5812 else if (Args[i].isZExt)
5813 ExtendKind = ISD::ZERO_EXTEND;
5814
Dale Johannesen66978ee2009-01-31 02:22:37 +00005815 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, PartVT, ExtendKind);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005816
5817 for (unsigned i = 0; i != NumParts; ++i) {
5818 // if it isn't first piece, alignment must be 1
5819 ISD::ArgFlagsTy MyFlags = Flags;
5820 if (NumParts > 1 && i == 0)
5821 MyFlags.setSplit();
5822 else if (i != 0)
5823 MyFlags.setOrigAlign(1);
5824
5825 Ops.push_back(Parts[i]);
5826 Ops.push_back(DAG.getArgFlags(MyFlags));
5827 }
5828 }
5829 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005830
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005831 // Figure out the result value types. We start by making a list of
5832 // the potentially illegal return value types.
5833 SmallVector<MVT, 4> LoweredRetTys;
5834 SmallVector<MVT, 4> RetTys;
5835 ComputeValueVTs(*this, RetTy, RetTys);
5836
5837 // Then we translate that to a list of legal types.
5838 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5839 MVT VT = RetTys[I];
5840 MVT RegisterVT = getRegisterType(VT);
5841 unsigned NumRegs = getNumRegisters(VT);
5842 for (unsigned i = 0; i != NumRegs; ++i)
5843 LoweredRetTys.push_back(RegisterVT);
5844 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005845
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005846 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005847
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005848 // Create the CALL node.
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005849 SDValue Res = DAG.getCall(CallingConv, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005850 isVarArg, isTailCall, isInreg,
Dan Gohman095cc292008-09-13 01:54:27 +00005851 DAG.getVTList(&LoweredRetTys[0],
5852 LoweredRetTys.size()),
Dale Johannesen86098bd2008-09-26 19:31:26 +00005853 &Ops[0], Ops.size()
5854 );
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005855 Chain = Res.getValue(LoweredRetTys.size() - 1);
5856
5857 // Gather up the call result into a single value.
Dan Gohmanb5cc34d2008-10-07 00:12:37 +00005858 if (RetTy != Type::VoidTy && !RetTys.empty()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005859 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5860
5861 if (RetSExt)
5862 AssertOp = ISD::AssertSext;
5863 else if (RetZExt)
5864 AssertOp = ISD::AssertZext;
5865
5866 SmallVector<SDValue, 4> ReturnValues;
5867 unsigned RegNo = 0;
5868 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5869 MVT VT = RetTys[I];
5870 MVT RegisterVT = getRegisterType(VT);
5871 unsigned NumRegs = getNumRegisters(VT);
5872 unsigned RegNoEnd = NumRegs + RegNo;
5873 SmallVector<SDValue, 4> Results;
5874 for (; RegNo != RegNoEnd; ++RegNo)
5875 Results.push_back(Res.getValue(RegNo));
5876 SDValue ReturnValue =
Dale Johannesen66978ee2009-01-31 02:22:37 +00005877 getCopyFromParts(DAG, dl, &Results[0], NumRegs, RegisterVT, VT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005878 AssertOp);
5879 ReturnValues.push_back(ReturnValue);
5880 }
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005881 Res = DAG.getNode(ISD::MERGE_VALUES, dl,
Duncan Sandsaaffa052008-12-01 11:41:29 +00005882 DAG.getVTList(&RetTys[0], RetTys.size()),
5883 &ReturnValues[0], ReturnValues.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005884 }
5885
5886 return std::make_pair(Res, Chain);
5887}
5888
Duncan Sands9fbc7e22009-01-21 09:00:29 +00005889void TargetLowering::LowerOperationWrapper(SDNode *N,
5890 SmallVectorImpl<SDValue> &Results,
5891 SelectionDAG &DAG) {
5892 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptabb326bb2009-01-21 04:48:39 +00005893 if (Res.getNode())
5894 Results.push_back(Res);
5895}
5896
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005897SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5898 assert(0 && "LowerOperation not implemented for this target!");
5899 abort();
5900 return SDValue();
5901}
5902
5903
5904void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5905 SDValue Op = getValue(V);
5906 assert((Op.getOpcode() != ISD::CopyFromReg ||
5907 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5908 "Copy from a reg to the same reg!");
5909 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5910
5911 RegsForValue RFV(TLI, Reg, V->getType());
5912 SDValue Chain = DAG.getEntryNode();
Dale Johannesen66978ee2009-01-31 02:22:37 +00005913 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005914 PendingExports.push_back(Chain);
5915}
5916
5917#include "llvm/CodeGen/SelectionDAGISel.h"
5918
5919void SelectionDAGISel::
5920LowerArguments(BasicBlock *LLVMBB) {
5921 // If this is the entry block, emit arguments.
5922 Function &F = *LLVMBB->getParent();
5923 SDValue OldRoot = SDL->DAG.getRoot();
5924 SmallVector<SDValue, 16> Args;
Dale Johannesen66978ee2009-01-31 02:22:37 +00005925 TLI.LowerArguments(F, SDL->DAG, Args, SDL->getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005926
5927 unsigned a = 0;
5928 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5929 AI != E; ++AI) {
5930 SmallVector<MVT, 4> ValueVTs;
5931 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5932 unsigned NumValues = ValueVTs.size();
5933 if (!AI->use_empty()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00005934 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues,
Dale Johannesen4be0bdf2009-02-05 00:20:09 +00005935 SDL->getCurDebugLoc()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005936 // If this argument is live outside of the entry block, insert a copy from
5937 // whereever we got it to the vreg that other BB's will reference it as.
Dan Gohmanad62f532009-04-23 23:13:24 +00005938 SDL->CopyToExportRegsIfNeeded(AI);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005939 }
5940 a += NumValues;
5941 }
5942
5943 // Finally, if the target has anything special to do, allow it to do so.
5944 // FIXME: this should insert code into the DAG!
5945 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5946}
5947
5948/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5949/// ensure constants are generated when needed. Remember the virtual registers
5950/// that need to be added to the Machine PHI nodes as input. We cannot just
5951/// directly add them, because expansion might result in multiple MBB's for one
5952/// BB. As such, the start of the BB might correspond to a different MBB than
5953/// the end.
5954///
5955void
5956SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5957 TerminatorInst *TI = LLVMBB->getTerminator();
5958
5959 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5960
5961 // Check successor nodes' PHI nodes that expect a constant to be available
5962 // from this block.
5963 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5964 BasicBlock *SuccBB = TI->getSuccessor(succ);
5965 if (!isa<PHINode>(SuccBB->begin())) continue;
5966 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005967
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005968 // If this terminator has multiple identical successors (common for
5969 // switches), only handle each succ once.
5970 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005971
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005972 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5973 PHINode *PN;
5974
5975 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5976 // nodes and Machine PHI nodes, but the incoming operands have not been
5977 // emitted yet.
5978 for (BasicBlock::iterator I = SuccBB->begin();
5979 (PN = dyn_cast<PHINode>(I)); ++I) {
5980 // Ignore dead phi's.
5981 if (PN->use_empty()) continue;
5982
5983 unsigned Reg;
5984 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5985
5986 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5987 unsigned &RegOut = SDL->ConstantsOut[C];
5988 if (RegOut == 0) {
5989 RegOut = FuncInfo->CreateRegForValue(C);
5990 SDL->CopyValueToVirtualRegister(C, RegOut);
5991 }
5992 Reg = RegOut;
5993 } else {
5994 Reg = FuncInfo->ValueMap[PHIOp];
5995 if (Reg == 0) {
5996 assert(isa<AllocaInst>(PHIOp) &&
5997 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5998 "Didn't codegen value into a register!??");
5999 Reg = FuncInfo->CreateRegForValue(PHIOp);
6000 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
6001 }
6002 }
6003
6004 // Remember that this register needs to added to the machine PHI node as
6005 // the input for this MBB.
6006 SmallVector<MVT, 4> ValueVTs;
6007 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6008 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
6009 MVT VT = ValueVTs[vti];
6010 unsigned NumRegisters = TLI.getNumRegisters(VT);
6011 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
6012 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
6013 Reg += NumRegisters;
6014 }
6015 }
6016 }
6017 SDL->ConstantsOut.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006018}
6019
Dan Gohman3df24e62008-09-03 23:12:08 +00006020/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
6021/// supports legal types, and it emits MachineInstrs directly instead of
6022/// creating SelectionDAG nodes.
6023///
6024bool
6025SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
6026 FastISel *F) {
6027 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00006028
Dan Gohman3df24e62008-09-03 23:12:08 +00006029 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6030 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
6031
6032 // Check successor nodes' PHI nodes that expect a constant to be available
6033 // from this block.
6034 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6035 BasicBlock *SuccBB = TI->getSuccessor(succ);
6036 if (!isa<PHINode>(SuccBB->begin())) continue;
6037 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006038
Dan Gohman3df24e62008-09-03 23:12:08 +00006039 // If this terminator has multiple identical successors (common for
6040 // switches), only handle each succ once.
6041 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00006042
Dan Gohman3df24e62008-09-03 23:12:08 +00006043 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6044 PHINode *PN;
6045
6046 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6047 // nodes and Machine PHI nodes, but the incoming operands have not been
6048 // emitted yet.
6049 for (BasicBlock::iterator I = SuccBB->begin();
6050 (PN = dyn_cast<PHINode>(I)); ++I) {
6051 // Ignore dead phi's.
6052 if (PN->use_empty()) continue;
6053
6054 // Only handle legal types. Two interesting things to note here. First,
6055 // by bailing out early, we may leave behind some dead instructions,
6056 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
6057 // own moves. Second, this check is necessary becuase FastISel doesn't
6058 // use CreateRegForValue to create registers, so it always creates
6059 // exactly one register for each non-void instruction.
6060 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
6061 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
Dan Gohman74321ab2008-09-10 21:01:31 +00006062 // Promote MVT::i1.
6063 if (VT == MVT::i1)
6064 VT = TLI.getTypeToTransformTo(VT);
6065 else {
6066 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6067 return false;
6068 }
Dan Gohman3df24e62008-09-03 23:12:08 +00006069 }
6070
6071 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6072
6073 unsigned Reg = F->getRegForValue(PHIOp);
6074 if (Reg == 0) {
6075 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6076 return false;
6077 }
6078 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
6079 }
6080 }
6081
6082 return true;
6083}