blob: a5fe32b8535efc460892d4a236c08992eea20694 [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
315 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
316 // also creates the initial PHI MachineInstrs, though none of the input
317 // operands are populated.
318 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
319 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
320 MBBMap[BB] = MBB;
321 MF->push_back(MBB);
322
323 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
324 // appropriate.
325 PHINode *PN;
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000326 DebugLoc DL;
327 for (BasicBlock::iterator
328 I = BB->begin(), E = BB->end(); I != E; ++I) {
329 if (CallInst *CI = dyn_cast<CallInst>(I)) {
330 if (Function *F = CI->getCalledFunction()) {
331 switch (F->getIntrinsicID()) {
332 default: break;
333 case Intrinsic::dbg_stoppoint: {
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000334 DbgStopPointInst *SPI = cast<DbgStopPointInst>(I);
335
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +0000336 if (DIDescriptor::ValidDebugInfo(SPI->getContext(),
337 CodeGenOpt::Default)) {
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000338 DICompileUnit CU(cast<GlobalVariable>(SPI->getContext()));
Argyrios Kyrtzidisa26eae62009-04-30 23:22:31 +0000339 unsigned idx = MF->getOrCreateDebugLocID(CU.getGV(),
Scott Michelfdc40a02009-02-17 22:15:04 +0000340 SPI->getLine(),
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000341 SPI->getColumn());
342 DL = DebugLoc::get(idx);
343 }
344
345 break;
346 }
347 case Intrinsic::dbg_func_start: {
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +0000348 DbgFuncStartInst *FSI = cast<DbgFuncStartInst>(I);
349 Value *SP = FSI->getSubprogram();
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000350
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +0000351 if (DIDescriptor::ValidDebugInfo(SP, CodeGenOpt::Default)) {
352 DISubprogram Subprogram(cast<GlobalVariable>(SP));
353 DICompileUnit CU(Subprogram.getCompileUnit());
354 unsigned Line = Subprogram.getLineNumber();
Bill Wendlingdf7d5d32009-05-21 00:04:55 +0000355 DL = DebugLoc::get(MF->getOrCreateDebugLocID(CU.getGV(),
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +0000356 Line, 0));
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000357 }
Scott Michelfdc40a02009-02-17 22:15:04 +0000358
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000359 break;
360 }
361 }
362 }
363 }
364
365 PN = dyn_cast<PHINode>(I);
366 if (!PN || PN->use_empty()) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000367
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000368 unsigned PHIReg = ValueMap[PN];
369 assert(PHIReg && "PHI node does not have an assigned virtual register!");
370
371 SmallVector<MVT, 4> ValueVTs;
372 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
373 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
374 MVT VT = ValueVTs[vti];
375 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohman6448d912008-09-04 15:39:15 +0000376 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000377 for (unsigned i = 0; i != NumRegisters; ++i)
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000378 BuildMI(MBB, DL, TII->get(TargetInstrInfo::PHI), PHIReg + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000379 PHIReg += NumRegisters;
380 }
381 }
382 }
383}
384
385unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
386 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
387}
388
389/// CreateRegForValue - Allocate the appropriate number of virtual registers of
390/// the correctly promoted or expanded types. Assign these registers
391/// consecutive vreg numbers and return the first assigned number.
392///
393/// In the case that the given value has struct or array type, this function
394/// will assign registers for each member or element.
395///
396unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
397 SmallVector<MVT, 4> ValueVTs;
398 ComputeValueVTs(TLI, V->getType(), ValueVTs);
399
400 unsigned FirstReg = 0;
401 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
402 MVT ValueVT = ValueVTs[Value];
403 MVT RegisterVT = TLI.getRegisterType(ValueVT);
404
405 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
406 for (unsigned i = 0; i != NumRegs; ++i) {
407 unsigned R = MakeReg(RegisterVT);
408 if (!FirstReg) FirstReg = R;
409 }
410 }
411 return FirstReg;
412}
413
414/// getCopyFromParts - Create a value that contains the specified legal parts
415/// combined into the value they represent. If the parts combine to a type
416/// larger then ValueVT then AssertOp can be used to specify whether the extra
417/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
418/// (ISD::AssertSext).
Dale Johannesen66978ee2009-01-31 02:22:37 +0000419static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
420 const SDValue *Parts,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000421 unsigned NumParts, MVT PartVT, MVT ValueVT,
422 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000423 assert(NumParts > 0 && "No parts to assemble!");
Dan Gohmane9530ec2009-01-15 16:58:17 +0000424 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000425 SDValue Val = Parts[0];
426
427 if (NumParts > 1) {
428 // Assemble the value from multiple parts.
Eli Friedman2ac8b322009-05-20 06:02:09 +0000429 if (!ValueVT.isVector() && ValueVT.isInteger()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000430 unsigned PartBits = PartVT.getSizeInBits();
431 unsigned ValueBits = ValueVT.getSizeInBits();
432
433 // Assemble the power of 2 part.
434 unsigned RoundParts = NumParts & (NumParts - 1) ?
435 1 << Log2_32(NumParts) : NumParts;
436 unsigned RoundBits = PartBits * RoundParts;
437 MVT RoundVT = RoundBits == ValueBits ?
438 ValueVT : MVT::getIntegerVT(RoundBits);
439 SDValue Lo, Hi;
440
Eli Friedman2ac8b322009-05-20 06:02:09 +0000441 MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000442
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000443 if (RoundParts > 2) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000444 Lo = getCopyFromParts(DAG, dl, Parts, RoundParts/2, PartVT, HalfVT);
445 Hi = getCopyFromParts(DAG, dl, Parts+RoundParts/2, RoundParts/2,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000446 PartVT, HalfVT);
447 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000448 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
449 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000450 }
451 if (TLI.isBigEndian())
452 std::swap(Lo, Hi);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000453 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000454
455 if (RoundParts < NumParts) {
456 // Assemble the trailing non-power-of-2 part.
457 unsigned OddParts = NumParts - RoundParts;
458 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
Scott Michelfdc40a02009-02-17 22:15:04 +0000459 Hi = getCopyFromParts(DAG, dl,
Dale Johannesen66978ee2009-01-31 02:22:37 +0000460 Parts+RoundParts, OddParts, PartVT, OddVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000461
462 // Combine the round and odd parts.
463 Lo = Val;
464 if (TLI.isBigEndian())
465 std::swap(Lo, Hi);
466 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000467 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
468 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000469 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands92abc622009-01-31 15:50:11 +0000470 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000471 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
472 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000473 }
Eli Friedman2ac8b322009-05-20 06:02:09 +0000474 } else if (ValueVT.isVector()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000475 // Handle a multi-element vector.
476 MVT IntermediateVT, RegisterVT;
477 unsigned NumIntermediates;
478 unsigned NumRegs =
479 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
480 RegisterVT);
481 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
482 NumParts = NumRegs; // Silence a compiler warning.
483 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
484 assert(RegisterVT == Parts[0].getValueType() &&
485 "Part type doesn't match part!");
486
487 // Assemble the parts into intermediate operands.
488 SmallVector<SDValue, 8> Ops(NumIntermediates);
489 if (NumIntermediates == NumParts) {
490 // If the register was not expanded, truncate or copy the value,
491 // as appropriate.
492 for (unsigned i = 0; i != NumParts; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000493 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000494 PartVT, IntermediateVT);
495 } else if (NumParts > 0) {
496 // If the intermediate type was expanded, build the intermediate operands
497 // from the parts.
498 assert(NumParts % NumIntermediates == 0 &&
499 "Must expand into a divisible number of parts!");
500 unsigned Factor = NumParts / NumIntermediates;
501 for (unsigned i = 0; i != NumIntermediates; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000502 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000503 PartVT, IntermediateVT);
504 }
505
506 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
507 // operands.
508 Val = DAG.getNode(IntermediateVT.isVector() ?
Dale Johannesen66978ee2009-01-31 02:22:37 +0000509 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000510 ValueVT, &Ops[0], NumIntermediates);
Eli Friedman2ac8b322009-05-20 06:02:09 +0000511 } else if (PartVT.isFloatingPoint()) {
512 // FP split into multiple FP parts (for ppcf128)
513 assert(ValueVT == MVT(MVT::ppcf128) && PartVT == MVT(MVT::f64) &&
514 "Unexpected split");
515 SDValue Lo, Hi;
516 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, MVT(MVT::f64), Parts[0]);
517 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, MVT(MVT::f64), Parts[1]);
518 if (TLI.isBigEndian())
519 std::swap(Lo, Hi);
520 Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi);
521 } else {
522 // FP split into integer parts (soft fp)
523 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
524 !PartVT.isVector() && "Unexpected split");
525 MVT IntVT = MVT::getIntegerVT(ValueVT.getSizeInBits());
526 Val = getCopyFromParts(DAG, dl, Parts, NumParts, PartVT, IntVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000527 }
528 }
529
530 // There is now one part, held in Val. Correct it to match ValueVT.
531 PartVT = Val.getValueType();
532
533 if (PartVT == ValueVT)
534 return Val;
535
536 if (PartVT.isVector()) {
537 assert(ValueVT.isVector() && "Unknown vector conversion!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000538 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000539 }
540
541 if (ValueVT.isVector()) {
542 assert(ValueVT.getVectorElementType() == PartVT &&
543 ValueVT.getVectorNumElements() == 1 &&
544 "Only trivial scalar-to-vector conversions should get here!");
Evan Chenga87008d2009-02-25 22:49:59 +0000545 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000546 }
547
548 if (PartVT.isInteger() &&
549 ValueVT.isInteger()) {
550 if (ValueVT.bitsLT(PartVT)) {
551 // For a truncate, see if we have any information to
552 // indicate whether the truncated bits will always be
553 // zero or sign-extension.
554 if (AssertOp != ISD::DELETED_NODE)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000555 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000556 DAG.getValueType(ValueVT));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000557 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000558 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000559 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000560 }
561 }
562
563 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
564 if (ValueVT.bitsLT(Val.getValueType()))
565 // FP_ROUND's are always exact here.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000566 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000567 DAG.getIntPtrConstant(1));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000568 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000569 }
570
571 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
Dale Johannesen66978ee2009-01-31 02:22:37 +0000572 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000573
574 assert(0 && "Unknown mismatch!");
575 return SDValue();
576}
577
578/// getCopyToParts - Create a series of nodes that contain the specified value
579/// split into legal parts. If the parts contain more bits than Val, then, for
580/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000581static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, SDValue Val,
Chris Lattner01426e12008-10-21 00:45:36 +0000582 SDValue *Parts, unsigned NumParts, MVT PartVT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000583 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohmane9530ec2009-01-15 16:58:17 +0000584 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000585 MVT PtrVT = TLI.getPointerTy();
586 MVT ValueVT = Val.getValueType();
587 unsigned PartBits = PartVT.getSizeInBits();
Dale Johannesen8a36f502009-02-25 22:39:13 +0000588 unsigned OrigNumParts = NumParts;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000589 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
590
591 if (!NumParts)
592 return;
593
594 if (!ValueVT.isVector()) {
595 if (PartVT == ValueVT) {
596 assert(NumParts == 1 && "No-op copy with multiple parts!");
597 Parts[0] = Val;
598 return;
599 }
600
601 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
602 // If the parts cover more bits than the value has, promote the value.
603 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
604 assert(NumParts == 1 && "Do not know what to promote to!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000605 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000606 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
607 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000608 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000609 } else {
610 assert(0 && "Unknown mismatch!");
611 }
612 } else if (PartBits == ValueVT.getSizeInBits()) {
613 // Different types of the same size.
614 assert(NumParts == 1 && PartVT != ValueVT);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000615 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000616 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
617 // If the parts cover less bits than value has, truncate the value.
618 if (PartVT.isInteger() && ValueVT.isInteger()) {
619 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000620 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000621 } else {
622 assert(0 && "Unknown mismatch!");
623 }
624 }
625
626 // The value may have changed - recompute ValueVT.
627 ValueVT = Val.getValueType();
628 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
629 "Failed to tile the value with PartVT!");
630
631 if (NumParts == 1) {
632 assert(PartVT == ValueVT && "Type conversion failed!");
633 Parts[0] = Val;
634 return;
635 }
636
637 // Expand the value into multiple parts.
638 if (NumParts & (NumParts - 1)) {
639 // The number of parts is not a power of 2. Split off and copy the tail.
640 assert(PartVT.isInteger() && ValueVT.isInteger() &&
641 "Do not know what to expand to!");
642 unsigned RoundParts = 1 << Log2_32(NumParts);
643 unsigned RoundBits = RoundParts * PartBits;
644 unsigned OddParts = NumParts - RoundParts;
Dale Johannesen66978ee2009-01-31 02:22:37 +0000645 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000646 DAG.getConstant(RoundBits,
Duncan Sands92abc622009-01-31 15:50:11 +0000647 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000648 getCopyToParts(DAG, dl, OddVal, Parts + RoundParts, OddParts, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000649 if (TLI.isBigEndian())
650 // The odd parts were reversed by getCopyToParts - unreverse them.
651 std::reverse(Parts + RoundParts, Parts + NumParts);
652 NumParts = RoundParts;
653 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000654 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000655 }
656
657 // The number of parts is a power of 2. Repeatedly bisect the value using
658 // EXTRACT_ELEMENT.
Scott Michelfdc40a02009-02-17 22:15:04 +0000659 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000660 MVT::getIntegerVT(ValueVT.getSizeInBits()),
661 Val);
662 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
663 for (unsigned i = 0; i < NumParts; i += StepSize) {
664 unsigned ThisBits = StepSize * PartBits / 2;
665 MVT ThisVT = MVT::getIntegerVT (ThisBits);
666 SDValue &Part0 = Parts[i];
667 SDValue &Part1 = Parts[i+StepSize/2];
668
Scott Michelfdc40a02009-02-17 22:15:04 +0000669 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000670 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000671 DAG.getConstant(1, PtrVT));
Scott Michelfdc40a02009-02-17 22:15:04 +0000672 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000673 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000674 DAG.getConstant(0, PtrVT));
675
676 if (ThisBits == PartBits && ThisVT != PartVT) {
Scott Michelfdc40a02009-02-17 22:15:04 +0000677 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000678 PartVT, Part0);
Scott Michelfdc40a02009-02-17 22:15:04 +0000679 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000680 PartVT, Part1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000681 }
682 }
683 }
684
685 if (TLI.isBigEndian())
Dale Johannesen8a36f502009-02-25 22:39:13 +0000686 std::reverse(Parts, Parts + OrigNumParts);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000687
688 return;
689 }
690
691 // Vector ValueVT.
692 if (NumParts == 1) {
693 if (PartVT != ValueVT) {
694 if (PartVT.isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000695 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000696 } else {
697 assert(ValueVT.getVectorElementType() == PartVT &&
698 ValueVT.getVectorNumElements() == 1 &&
699 "Only trivial vector-to-scalar conversions should get here!");
Scott Michelfdc40a02009-02-17 22:15:04 +0000700 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000701 PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000702 DAG.getConstant(0, PtrVT));
703 }
704 }
705
706 Parts[0] = Val;
707 return;
708 }
709
710 // Handle a multi-element vector.
711 MVT IntermediateVT, RegisterVT;
712 unsigned NumIntermediates;
Dan Gohmane9530ec2009-01-15 16:58:17 +0000713 unsigned NumRegs = TLI
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000714 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
715 RegisterVT);
716 unsigned NumElements = ValueVT.getVectorNumElements();
717
718 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
719 NumParts = NumRegs; // Silence a compiler warning.
720 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
721
722 // Split the vector into intermediate operands.
723 SmallVector<SDValue, 8> Ops(NumIntermediates);
724 for (unsigned i = 0; i != NumIntermediates; ++i)
725 if (IntermediateVT.isVector())
Scott Michelfdc40a02009-02-17 22:15:04 +0000726 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000727 IntermediateVT, Val,
728 DAG.getConstant(i * (NumElements / NumIntermediates),
729 PtrVT));
730 else
Scott Michelfdc40a02009-02-17 22:15:04 +0000731 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000732 IntermediateVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000733 DAG.getConstant(i, PtrVT));
734
735 // Split the intermediate operands into legal parts.
736 if (NumParts == NumIntermediates) {
737 // If the register was not expanded, promote or copy the value,
738 // as appropriate.
739 for (unsigned i = 0; i != NumParts; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000740 getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000741 } else if (NumParts > 0) {
742 // If the intermediate type was expanded, split each the value into
743 // legal parts.
744 assert(NumParts % NumIntermediates == 0 &&
745 "Must expand into a divisible number of parts!");
746 unsigned Factor = NumParts / NumIntermediates;
747 for (unsigned i = 0; i != NumIntermediates; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000748 getCopyToParts(DAG, dl, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000749 }
750}
751
752
753void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
754 AA = &aa;
755 GFI = gfi;
756 TD = DAG.getTarget().getTargetData();
757}
758
759/// clear - Clear out the curret SelectionDAG and the associated
760/// state and prepare this SelectionDAGLowering object to be used
761/// for a new block. This doesn't clear out information about
762/// additional blocks that are needed to complete switch lowering
763/// or PHI node updating; that information is cleared out as it is
764/// consumed.
765void SelectionDAGLowering::clear() {
766 NodeMap.clear();
767 PendingLoads.clear();
768 PendingExports.clear();
769 DAG.clear();
Bill Wendling8fcf1702009-02-06 21:36:23 +0000770 CurDebugLoc = DebugLoc::getUnknownLoc();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000771}
772
773/// getRoot - Return the current virtual root of the Selection DAG,
774/// flushing any PendingLoad items. This must be done before emitting
775/// a store or any other node that may need to be ordered after any
776/// prior load instructions.
777///
778SDValue SelectionDAGLowering::getRoot() {
779 if (PendingLoads.empty())
780 return DAG.getRoot();
781
782 if (PendingLoads.size() == 1) {
783 SDValue Root = PendingLoads[0];
784 DAG.setRoot(Root);
785 PendingLoads.clear();
786 return Root;
787 }
788
789 // Otherwise, we have to make a token factor node.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000790 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000791 &PendingLoads[0], PendingLoads.size());
792 PendingLoads.clear();
793 DAG.setRoot(Root);
794 return Root;
795}
796
797/// getControlRoot - Similar to getRoot, but instead of flushing all the
798/// PendingLoad items, flush all the PendingExports items. It is necessary
799/// to do this before emitting a terminator instruction.
800///
801SDValue SelectionDAGLowering::getControlRoot() {
802 SDValue Root = DAG.getRoot();
803
804 if (PendingExports.empty())
805 return Root;
806
807 // Turn all of the CopyToReg chains into one factored node.
808 if (Root.getOpcode() != ISD::EntryToken) {
809 unsigned i = 0, e = PendingExports.size();
810 for (; i != e; ++i) {
811 assert(PendingExports[i].getNode()->getNumOperands() > 1);
812 if (PendingExports[i].getNode()->getOperand(0) == Root)
813 break; // Don't add the root if we already indirectly depend on it.
814 }
815
816 if (i == e)
817 PendingExports.push_back(Root);
818 }
819
Dale Johannesen66978ee2009-01-31 02:22:37 +0000820 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000821 &PendingExports[0],
822 PendingExports.size());
823 PendingExports.clear();
824 DAG.setRoot(Root);
825 return Root;
826}
827
828void SelectionDAGLowering::visit(Instruction &I) {
829 visit(I.getOpcode(), I);
830}
831
832void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
833 // Note: this doesn't use InstVisitor, because it has to work with
834 // ConstantExpr's in addition to instructions.
835 switch (Opcode) {
836 default: assert(0 && "Unknown instruction type encountered!");
837 abort();
838 // Build the switch statement using the Instruction.def file.
839#define HANDLE_INST(NUM, OPCODE, CLASS) \
840 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
841#include "llvm/Instruction.def"
842 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000843}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000844
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000845SDValue SelectionDAGLowering::getValue(const Value *V) {
846 SDValue &N = NodeMap[V];
847 if (N.getNode()) return N;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000848
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000849 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
850 MVT VT = TLI.getValueType(V->getType(), true);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000851
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000852 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000853 return N = DAG.getConstant(*CI, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000854
855 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
856 return N = DAG.getGlobalAddress(GV, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000857
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000858 if (isa<ConstantPointerNull>(C))
859 return N = DAG.getConstant(0, TLI.getPointerTy());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000860
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000861 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000862 return N = DAG.getConstantFP(*CFP, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000863
Nate Begeman9008ca62009-04-27 18:41:29 +0000864 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
Dale Johannesene8d72302009-02-06 23:05:02 +0000865 return N = DAG.getUNDEF(VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000866
867 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
868 visit(CE->getOpcode(), *CE);
869 SDValue N1 = NodeMap[V];
870 assert(N1.getNode() && "visit didn't populate the ValueMap!");
871 return N1;
872 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000873
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000874 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
875 SmallVector<SDValue, 4> Constants;
876 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
877 OI != OE; ++OI) {
878 SDNode *Val = getValue(*OI).getNode();
879 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
880 Constants.push_back(SDValue(Val, i));
881 }
Dale Johannesen4be0bdf2009-02-05 00:20:09 +0000882 return DAG.getMergeValues(&Constants[0], Constants.size(),
883 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000884 }
885
886 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
887 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
888 "Unknown struct or array constant!");
889
890 SmallVector<MVT, 4> ValueVTs;
891 ComputeValueVTs(TLI, C->getType(), ValueVTs);
892 unsigned NumElts = ValueVTs.size();
893 if (NumElts == 0)
894 return SDValue(); // empty struct
895 SmallVector<SDValue, 4> Constants(NumElts);
896 for (unsigned i = 0; i != NumElts; ++i) {
897 MVT EltVT = ValueVTs[i];
898 if (isa<UndefValue>(C))
Dale Johannesene8d72302009-02-06 23:05:02 +0000899 Constants[i] = DAG.getUNDEF(EltVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000900 else if (EltVT.isFloatingPoint())
901 Constants[i] = DAG.getConstantFP(0, EltVT);
902 else
903 Constants[i] = DAG.getConstant(0, EltVT);
904 }
Dale Johannesen4be0bdf2009-02-05 00:20:09 +0000905 return DAG.getMergeValues(&Constants[0], NumElts, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000906 }
907
908 const VectorType *VecTy = cast<VectorType>(V->getType());
909 unsigned NumElements = VecTy->getNumElements();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000910
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000911 // Now that we know the number and type of the elements, get that number of
912 // elements into the Ops array based on what kind of constant it is.
913 SmallVector<SDValue, 16> Ops;
914 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
915 for (unsigned i = 0; i != NumElements; ++i)
916 Ops.push_back(getValue(CP->getOperand(i)));
917 } else {
Nate Begeman9008ca62009-04-27 18:41:29 +0000918 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000919 MVT EltVT = TLI.getValueType(VecTy->getElementType());
920
921 SDValue Op;
Nate Begeman9008ca62009-04-27 18:41:29 +0000922 if (EltVT.isFloatingPoint())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000923 Op = DAG.getConstantFP(0, EltVT);
924 else
925 Op = DAG.getConstant(0, EltVT);
926 Ops.assign(NumElements, Op);
927 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000928
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000929 // Create a BUILD_VECTOR node.
Evan Chenga87008d2009-02-25 22:49:59 +0000930 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
931 VT, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000932 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000933
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000934 // If this is a static alloca, generate it as the frameindex instead of
935 // computation.
936 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
937 DenseMap<const AllocaInst*, int>::iterator SI =
938 FuncInfo.StaticAllocaMap.find(AI);
939 if (SI != FuncInfo.StaticAllocaMap.end())
940 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
941 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000942
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000943 unsigned InReg = FuncInfo.ValueMap[V];
944 assert(InReg && "Value not in map!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000945
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000946 RegsForValue RFV(TLI, InReg, V->getType());
947 SDValue Chain = DAG.getEntryNode();
Dale Johannesen66978ee2009-01-31 02:22:37 +0000948 return RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000949}
950
951
952void SelectionDAGLowering::visitRet(ReturnInst &I) {
953 if (I.getNumOperands() == 0) {
Scott Michelfdc40a02009-02-17 22:15:04 +0000954 DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000955 MVT::Other, getControlRoot()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000956 return;
957 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000958
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000959 SmallVector<SDValue, 8> NewValues;
960 NewValues.push_back(getControlRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000961 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000962 SmallVector<MVT, 4> ValueVTs;
963 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
Dan Gohman7ea1ca62008-10-21 20:00:42 +0000964 unsigned NumValues = ValueVTs.size();
965 if (NumValues == 0) continue;
966
967 SDValue RetOp = getValue(I.getOperand(i));
968 for (unsigned j = 0, f = NumValues; j != f; ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000969 MVT VT = ValueVTs[j];
970
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000971 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000972
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000973 const Function *F = I.getParent()->getParent();
Devang Patel05988662008-09-25 21:00:45 +0000974 if (F->paramHasAttr(0, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000975 ExtendKind = ISD::SIGN_EXTEND;
Devang Patel05988662008-09-25 21:00:45 +0000976 else if (F->paramHasAttr(0, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000977 ExtendKind = ISD::ZERO_EXTEND;
978
Evan Cheng3927f432009-03-25 20:20:11 +0000979 // FIXME: C calling convention requires the return type to be promoted to
980 // at least 32-bit. But this is not necessary for non-C calling
981 // conventions. The frontend should mark functions whose return values
982 // require promoting with signext or zeroext attributes.
983 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
984 MVT MinVT = TLI.getRegisterType(MVT::i32);
985 if (VT.bitsLT(MinVT))
986 VT = MinVT;
987 }
988
989 unsigned NumParts = TLI.getNumRegisters(VT);
990 MVT PartVT = TLI.getRegisterType(VT);
991 SmallVector<SDValue, 4> Parts(NumParts);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000992 getCopyToParts(DAG, getCurDebugLoc(),
993 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000994 &Parts[0], NumParts, PartVT, ExtendKind);
995
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000996 // 'inreg' on function refers to return value
997 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Devang Patel05988662008-09-25 21:00:45 +0000998 if (F->paramHasAttr(0, Attribute::InReg))
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000999 Flags.setInReg();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001000 for (unsigned i = 0; i < NumParts; ++i) {
1001 NewValues.push_back(Parts[i]);
Dale Johannesenc9c6da62008-09-25 20:47:45 +00001002 NewValues.push_back(DAG.getArgFlags(Flags));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001003 }
1004 }
1005 }
Dale Johannesen66978ee2009-01-31 02:22:37 +00001006 DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001007 &NewValues[0], NewValues.size()));
1008}
1009
Dan Gohmanad62f532009-04-23 23:13:24 +00001010/// CopyToExportRegsIfNeeded - If the given value has virtual registers
1011/// created for it, emit nodes to copy the value into the virtual
1012/// registers.
1013void SelectionDAGLowering::CopyToExportRegsIfNeeded(Value *V) {
1014 if (!V->use_empty()) {
1015 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1016 if (VMI != FuncInfo.ValueMap.end())
1017 CopyValueToVirtualRegister(V, VMI->second);
1018 }
1019}
1020
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001021/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1022/// the current basic block, add it to ValueMap now so that we'll get a
1023/// CopyTo/FromReg.
1024void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1025 // No need to export constants.
1026 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001027
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001028 // Already exported?
1029 if (FuncInfo.isExportedInst(V)) return;
1030
1031 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1032 CopyValueToVirtualRegister(V, Reg);
1033}
1034
1035bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1036 const BasicBlock *FromBB) {
1037 // The operands of the setcc have to be in this block. We don't know
1038 // how to export them from some other block.
1039 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1040 // Can export from current BB.
1041 if (VI->getParent() == FromBB)
1042 return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001043
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001044 // Is already exported, noop.
1045 return FuncInfo.isExportedInst(V);
1046 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001047
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001048 // If this is an argument, we can export it if the BB is the entry block or
1049 // if it is already exported.
1050 if (isa<Argument>(V)) {
1051 if (FromBB == &FromBB->getParent()->getEntryBlock())
1052 return true;
1053
1054 // Otherwise, can only export this if it is already exported.
1055 return FuncInfo.isExportedInst(V);
1056 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001057
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001058 // Otherwise, constants can always be exported.
1059 return true;
1060}
1061
1062static bool InBlock(const Value *V, const BasicBlock *BB) {
1063 if (const Instruction *I = dyn_cast<Instruction>(V))
1064 return I->getParent() == BB;
1065 return true;
1066}
1067
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001068/// getFCmpCondCode - Return the ISD condition code corresponding to
1069/// the given LLVM IR floating-point condition code. This includes
1070/// consideration of global floating-point math flags.
1071///
1072static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1073 ISD::CondCode FPC, FOC;
1074 switch (Pred) {
1075 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1076 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1077 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1078 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1079 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1080 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1081 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1082 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1083 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1084 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1085 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1086 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1087 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1088 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1089 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1090 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1091 default:
1092 assert(0 && "Invalid FCmp predicate opcode!");
1093 FOC = FPC = ISD::SETFALSE;
1094 break;
1095 }
1096 if (FiniteOnlyFPMath())
1097 return FOC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001098 else
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001099 return FPC;
1100}
1101
1102/// getICmpCondCode - Return the ISD condition code corresponding to
1103/// the given LLVM IR integer condition code.
1104///
1105static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1106 switch (Pred) {
1107 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1108 case ICmpInst::ICMP_NE: return ISD::SETNE;
1109 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1110 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1111 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1112 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1113 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1114 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1115 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1116 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1117 default:
1118 assert(0 && "Invalid ICmp predicate opcode!");
1119 return ISD::SETNE;
1120 }
1121}
1122
Dan Gohmanc2277342008-10-17 21:16:08 +00001123/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1124/// This function emits a branch and is used at the leaves of an OR or an
1125/// AND operator tree.
1126///
1127void
1128SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1129 MachineBasicBlock *TBB,
1130 MachineBasicBlock *FBB,
1131 MachineBasicBlock *CurBB) {
1132 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001133
Dan Gohmanc2277342008-10-17 21:16:08 +00001134 // If the leaf of the tree is a comparison, merge the condition into
1135 // the caseblock.
1136 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1137 // The operands of the cmp have to be in this block. We don't know
1138 // how to export them from some other block. If this is the first block
1139 // of the sequence, no exporting is needed.
1140 if (CurBB == CurMBB ||
1141 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1142 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001143 ISD::CondCode Condition;
1144 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001145 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001146 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001147 Condition = getFCmpCondCode(FC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001148 } else {
1149 Condition = ISD::SETEQ; // silence warning.
1150 assert(0 && "Unknown compare instruction");
1151 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001152
1153 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001154 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1155 SwitchCases.push_back(CB);
1156 return;
1157 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001158 }
1159
1160 // Create a CaseBlock record representing this branch.
1161 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1162 NULL, TBB, FBB, CurBB);
1163 SwitchCases.push_back(CB);
1164}
1165
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001166/// FindMergedConditions - If Cond is an expression like
Dan Gohmanc2277342008-10-17 21:16:08 +00001167void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1168 MachineBasicBlock *TBB,
1169 MachineBasicBlock *FBB,
1170 MachineBasicBlock *CurBB,
1171 unsigned Opc) {
1172 // If this node is not part of the or/and tree, emit it as a branch.
1173 Instruction *BOp = dyn_cast<Instruction>(Cond);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001174 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohmanc2277342008-10-17 21:16:08 +00001175 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1176 BOp->getParent() != CurBB->getBasicBlock() ||
1177 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1178 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1179 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001180 return;
1181 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001182
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001183 // Create TmpBB after CurBB.
1184 MachineFunction::iterator BBI = CurBB;
1185 MachineFunction &MF = DAG.getMachineFunction();
1186 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1187 CurBB->getParent()->insert(++BBI, TmpBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001188
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001189 if (Opc == Instruction::Or) {
1190 // Codegen X | Y as:
1191 // jmp_if_X TBB
1192 // jmp TmpBB
1193 // TmpBB:
1194 // jmp_if_Y TBB
1195 // jmp FBB
1196 //
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001197
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001198 // Emit the LHS condition.
1199 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001200
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001201 // Emit the RHS condition into TmpBB.
1202 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1203 } else {
1204 assert(Opc == Instruction::And && "Unknown merge op!");
1205 // Codegen X & Y as:
1206 // jmp_if_X TmpBB
1207 // jmp FBB
1208 // TmpBB:
1209 // jmp_if_Y TBB
1210 // jmp FBB
1211 //
1212 // This requires creation of TmpBB after CurBB.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001213
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001214 // Emit the LHS condition.
1215 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001216
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001217 // Emit the RHS condition into TmpBB.
1218 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1219 }
1220}
1221
1222/// If the set of cases should be emitted as a series of branches, return true.
1223/// If we should emit this as a bunch of and/or'd together conditions, return
1224/// false.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001225bool
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001226SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1227 if (Cases.size() != 2) return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001228
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001229 // If this is two comparisons of the same values or'd or and'd together, they
1230 // will get folded into a single comparison, so don't emit two blocks.
1231 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1232 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1233 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1234 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1235 return false;
1236 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001237
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001238 return true;
1239}
1240
1241void SelectionDAGLowering::visitBr(BranchInst &I) {
1242 // Update machine-CFG edges.
1243 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1244
1245 // Figure out which block is immediately after the current one.
1246 MachineBasicBlock *NextBlock = 0;
1247 MachineFunction::iterator BBI = CurMBB;
1248 if (++BBI != CurMBB->getParent()->end())
1249 NextBlock = BBI;
1250
1251 if (I.isUnconditional()) {
1252 // Update machine-CFG edges.
1253 CurMBB->addSuccessor(Succ0MBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001254
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001255 // If this is not a fall-through branch, emit the branch.
1256 if (Succ0MBB != NextBlock)
Scott Michelfdc40a02009-02-17 22:15:04 +00001257 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001258 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001259 DAG.getBasicBlock(Succ0MBB)));
1260 return;
1261 }
1262
1263 // If this condition is one of the special cases we handle, do special stuff
1264 // now.
1265 Value *CondVal = I.getCondition();
1266 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1267
1268 // If this is a series of conditions that are or'd or and'd together, emit
1269 // this as a sequence of branches instead of setcc's with and/or operations.
1270 // For example, instead of something like:
1271 // cmp A, B
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001272 // C = seteq
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001273 // cmp D, E
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001274 // F = setle
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001275 // or C, F
1276 // jnz foo
1277 // Emit:
1278 // cmp A, B
1279 // je foo
1280 // cmp D, E
1281 // jle foo
1282 //
1283 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001284 if (BOp->hasOneUse() &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001285 (BOp->getOpcode() == Instruction::And ||
1286 BOp->getOpcode() == Instruction::Or)) {
1287 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1288 // If the compares in later blocks need to use values not currently
1289 // exported from this block, export them now. This block should always
1290 // be the first entry.
1291 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001292
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001293 // Allow some cases to be rejected.
1294 if (ShouldEmitAsBranches(SwitchCases)) {
1295 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1296 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1297 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1298 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001299
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001300 // Emit the branch for this block.
1301 visitSwitchCase(SwitchCases[0]);
1302 SwitchCases.erase(SwitchCases.begin());
1303 return;
1304 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001305
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001306 // Okay, we decided not to do this, remove any inserted MBB's and clear
1307 // SwitchCases.
1308 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1309 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001310
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001311 SwitchCases.clear();
1312 }
1313 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001314
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001315 // Create a CaseBlock record representing this branch.
1316 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1317 NULL, Succ0MBB, Succ1MBB, CurMBB);
1318 // Use visitSwitchCase to actually insert the fast branch sequence for this
1319 // cond branch.
1320 visitSwitchCase(CB);
1321}
1322
1323/// visitSwitchCase - Emits the necessary code to represent a single node in
1324/// the binary search tree resulting from lowering a switch instruction.
1325void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1326 SDValue Cond;
1327 SDValue CondLHS = getValue(CB.CmpLHS);
Dale Johannesenf5d97892009-02-04 01:48:28 +00001328 DebugLoc dl = getCurDebugLoc();
Anton Korobeynikov23218582008-12-23 22:25:27 +00001329
1330 // Build the setcc now.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001331 if (CB.CmpMHS == NULL) {
1332 // Fold "(X == true)" to X and "(X == false)" to !X to
1333 // handle common cases produced by branch lowering.
1334 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1335 Cond = CondLHS;
1336 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1337 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001338 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001339 } else
Dale Johannesenf5d97892009-02-04 01:48:28 +00001340 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001341 } else {
1342 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1343
Anton Korobeynikov23218582008-12-23 22:25:27 +00001344 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1345 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001346
1347 SDValue CmpOp = getValue(CB.CmpMHS);
1348 MVT VT = CmpOp.getValueType();
1349
1350 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
Scott Michelfdc40a02009-02-17 22:15:04 +00001351 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
Dale Johannesenf5d97892009-02-04 01:48:28 +00001352 ISD::SETLE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001353 } else {
Dale Johannesenf5d97892009-02-04 01:48:28 +00001354 SDValue SUB = DAG.getNode(ISD::SUB, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001355 VT, CmpOp, DAG.getConstant(Low, VT));
Dale Johannesenf5d97892009-02-04 01:48:28 +00001356 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001357 DAG.getConstant(High-Low, VT), ISD::SETULE);
1358 }
1359 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001360
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001361 // Update successor info
1362 CurMBB->addSuccessor(CB.TrueBB);
1363 CurMBB->addSuccessor(CB.FalseBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001364
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001365 // Set NextBlock to be the MBB immediately after the current one, if any.
1366 // This is used to avoid emitting unnecessary branches to the next block.
1367 MachineBasicBlock *NextBlock = 0;
1368 MachineFunction::iterator BBI = CurMBB;
1369 if (++BBI != CurMBB->getParent()->end())
1370 NextBlock = BBI;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001371
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001372 // If the lhs block is the next block, invert the condition so that we can
1373 // fall through to the lhs instead of the rhs block.
1374 if (CB.TrueBB == NextBlock) {
1375 std::swap(CB.TrueBB, CB.FalseBB);
1376 SDValue True = DAG.getConstant(1, Cond.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001377 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001378 }
Dale Johannesenf5d97892009-02-04 01:48:28 +00001379 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001380 MVT::Other, getControlRoot(), Cond,
1381 DAG.getBasicBlock(CB.TrueBB));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001382
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001383 // If the branch was constant folded, fix up the CFG.
1384 if (BrCond.getOpcode() == ISD::BR) {
1385 CurMBB->removeSuccessor(CB.FalseBB);
1386 DAG.setRoot(BrCond);
1387 } else {
1388 // Otherwise, go ahead and insert the false branch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001389 if (BrCond == getControlRoot())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001390 CurMBB->removeSuccessor(CB.TrueBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001391
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001392 if (CB.FalseBB == NextBlock)
1393 DAG.setRoot(BrCond);
1394 else
Dale Johannesenf5d97892009-02-04 01:48:28 +00001395 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001396 DAG.getBasicBlock(CB.FalseBB)));
1397 }
1398}
1399
1400/// visitJumpTable - Emit JumpTable node in the current MBB
1401void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1402 // Emit the code for the jump table
1403 assert(JT.Reg != -1U && "Should lower JT Header first!");
1404 MVT PTy = TLI.getPointerTy();
Dale Johannesena04b7572009-02-03 23:04:43 +00001405 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1406 JT.Reg, PTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001407 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Scott Michelfdc40a02009-02-17 22:15:04 +00001408 DAG.setRoot(DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001409 MVT::Other, Index.getValue(1),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001410 Table, Index));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001411}
1412
1413/// visitJumpTableHeader - This function emits necessary code to produce index
1414/// in the JumpTable from switch case.
1415void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1416 JumpTableHeader &JTH) {
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001417 // Subtract the lowest switch case value from the value being switched on and
1418 // conditional branch to default mbb if the result is greater than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001419 // difference between smallest and largest cases.
1420 SDValue SwitchOp = getValue(JTH.SValue);
1421 MVT VT = SwitchOp.getValueType();
Dale Johannesen66978ee2009-01-31 02:22:37 +00001422 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001423 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001424
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001425 // The SDNode we just created, which holds the value being switched on minus
1426 // the the smallest case value, needs to be copied to a virtual register so it
1427 // can be used as an index into the jump table in a subsequent basic block.
1428 // This value may be smaller or larger than the target's pointer type, and
1429 // therefore require extension or truncating.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001430 if (VT.bitsGT(TLI.getPointerTy()))
Scott Michelfdc40a02009-02-17 22:15:04 +00001431 SwitchOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001432 TLI.getPointerTy(), SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001433 else
Scott Michelfdc40a02009-02-17 22:15:04 +00001434 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001435 TLI.getPointerTy(), SUB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001436
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001437 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001438 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1439 JumpTableReg, SwitchOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001440 JT.Reg = JumpTableReg;
1441
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001442 // Emit the range check for the jump table, and branch to the default block
1443 // for the switch statement if the value being switched on exceeds the largest
1444 // case in the switch.
Dale Johannesenf5d97892009-02-04 01:48:28 +00001445 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1446 TLI.getSetCCResultType(SUB.getValueType()), SUB,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001447 DAG.getConstant(JTH.Last-JTH.First,VT),
1448 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001449
1450 // Set NextBlock to be the MBB immediately after the current one, if any.
1451 // This is used to avoid emitting unnecessary branches to the next block.
1452 MachineBasicBlock *NextBlock = 0;
1453 MachineFunction::iterator BBI = CurMBB;
1454 if (++BBI != CurMBB->getParent()->end())
1455 NextBlock = BBI;
1456
Dale Johannesen66978ee2009-01-31 02:22:37 +00001457 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001458 MVT::Other, CopyTo, CMP,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001459 DAG.getBasicBlock(JT.Default));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001460
1461 if (JT.MBB == NextBlock)
1462 DAG.setRoot(BrCond);
1463 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001464 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001465 DAG.getBasicBlock(JT.MBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001466}
1467
1468/// visitBitTestHeader - This function emits necessary code to produce value
1469/// suitable for "bit tests"
1470void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1471 // Subtract the minimum value
1472 SDValue SwitchOp = getValue(B.SValue);
1473 MVT VT = SwitchOp.getValueType();
Dale Johannesen66978ee2009-01-31 02:22:37 +00001474 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001475 DAG.getConstant(B.First, VT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001476
1477 // Check range
Dale Johannesenf5d97892009-02-04 01:48:28 +00001478 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1479 TLI.getSetCCResultType(SUB.getValueType()),
1480 SUB, DAG.getConstant(B.Range, VT),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001481 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001482
1483 SDValue ShiftOp;
Duncan Sands92abc622009-01-31 15:50:11 +00001484 if (VT.bitsGT(TLI.getPointerTy()))
Scott Michelfdc40a02009-02-17 22:15:04 +00001485 ShiftOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00001486 TLI.getPointerTy(), SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001487 else
Scott Michelfdc40a02009-02-17 22:15:04 +00001488 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00001489 TLI.getPointerTy(), SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001490
Duncan Sands92abc622009-01-31 15:50:11 +00001491 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001492 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1493 B.Reg, ShiftOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001494
1495 // Set NextBlock to be the MBB immediately after the current one, if any.
1496 // This is used to avoid emitting unnecessary branches to the next block.
1497 MachineBasicBlock *NextBlock = 0;
1498 MachineFunction::iterator BBI = CurMBB;
1499 if (++BBI != CurMBB->getParent()->end())
1500 NextBlock = BBI;
1501
1502 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1503
1504 CurMBB->addSuccessor(B.Default);
1505 CurMBB->addSuccessor(MBB);
1506
Dale Johannesen66978ee2009-01-31 02:22:37 +00001507 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001508 MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001509 DAG.getBasicBlock(B.Default));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001510
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001511 if (MBB == NextBlock)
1512 DAG.setRoot(BrRange);
1513 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001514 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001515 DAG.getBasicBlock(MBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001516}
1517
1518/// visitBitTestCase - this function produces one "bit test"
1519void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1520 unsigned Reg,
1521 BitTestCase &B) {
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001522 // Make desired shift
Dale Johannesena04b7572009-02-03 23:04:43 +00001523 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
Duncan Sands92abc622009-01-31 15:50:11 +00001524 TLI.getPointerTy());
Scott Michelfdc40a02009-02-17 22:15:04 +00001525 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001526 TLI.getPointerTy(),
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001527 DAG.getConstant(1, TLI.getPointerTy()),
1528 ShiftOp);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001529
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001530 // Emit bit tests and jumps
Scott Michelfdc40a02009-02-17 22:15:04 +00001531 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001532 TLI.getPointerTy(), SwitchVal,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001533 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Dale Johannesenf5d97892009-02-04 01:48:28 +00001534 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1535 TLI.getSetCCResultType(AndOp.getValueType()),
Duncan Sands5480c042009-01-01 15:52:00 +00001536 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001537 ISD::SETNE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001538
1539 CurMBB->addSuccessor(B.TargetBB);
1540 CurMBB->addSuccessor(NextMBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001541
Dale Johannesen66978ee2009-01-31 02:22:37 +00001542 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001543 MVT::Other, getControlRoot(),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001544 AndCmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001545
1546 // Set NextBlock to be the MBB immediately after the current one, if any.
1547 // This is used to avoid emitting unnecessary branches to the next block.
1548 MachineBasicBlock *NextBlock = 0;
1549 MachineFunction::iterator BBI = CurMBB;
1550 if (++BBI != CurMBB->getParent()->end())
1551 NextBlock = BBI;
1552
1553 if (NextMBB == NextBlock)
1554 DAG.setRoot(BrAnd);
1555 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001556 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001557 DAG.getBasicBlock(NextMBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001558}
1559
1560void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1561 // Retrieve successors.
1562 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1563 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1564
Gabor Greifb67e6b32009-01-15 11:10:44 +00001565 const Value *Callee(I.getCalledValue());
1566 if (isa<InlineAsm>(Callee))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001567 visitInlineAsm(&I);
1568 else
Gabor Greifb67e6b32009-01-15 11:10:44 +00001569 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001570
1571 // If the value of the invoke is used outside of its defining block, make it
1572 // available as a virtual register.
Dan Gohmanad62f532009-04-23 23:13:24 +00001573 CopyToExportRegsIfNeeded(&I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001574
1575 // Update successor info
1576 CurMBB->addSuccessor(Return);
1577 CurMBB->addSuccessor(LandingPad);
1578
1579 // Drop into normal successor.
Scott Michelfdc40a02009-02-17 22:15:04 +00001580 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001581 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001582 DAG.getBasicBlock(Return)));
1583}
1584
1585void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1586}
1587
1588/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1589/// small case ranges).
1590bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1591 CaseRecVector& WorkList,
1592 Value* SV,
1593 MachineBasicBlock* Default) {
1594 Case& BackCase = *(CR.Range.second-1);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001595
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001596 // Size is the number of Cases represented by this range.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001597 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001598 if (Size > 3)
Anton Korobeynikov23218582008-12-23 22:25:27 +00001599 return false;
1600
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001601 // Get the MachineFunction which holds the current MBB. This is used when
1602 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001603 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001604
1605 // Figure out which block is immediately after the current one.
1606 MachineBasicBlock *NextBlock = 0;
1607 MachineFunction::iterator BBI = CR.CaseBB;
1608
1609 if (++BBI != CurMBB->getParent()->end())
1610 NextBlock = BBI;
1611
1612 // TODO: If any two of the cases has the same destination, and if one value
1613 // is the same as the other, but has one bit unset that the other has set,
1614 // use bit manipulation to do two compares at once. For example:
1615 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Anton Korobeynikov23218582008-12-23 22:25:27 +00001616
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001617 // Rearrange the case blocks so that the last one falls through if possible.
1618 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1619 // The last case block won't fall through into 'NextBlock' if we emit the
1620 // branches in this order. See if rearranging a case value would help.
1621 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1622 if (I->BB == NextBlock) {
1623 std::swap(*I, BackCase);
1624 break;
1625 }
1626 }
1627 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001628
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001629 // Create a CaseBlock record representing a conditional branch to
1630 // the Case's target mbb if the value being switched on SV is equal
1631 // to C.
1632 MachineBasicBlock *CurBlock = CR.CaseBB;
1633 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1634 MachineBasicBlock *FallThrough;
1635 if (I != E-1) {
1636 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1637 CurMF->insert(BBI, FallThrough);
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001638
1639 // Put SV in a virtual register to make it available from the new blocks.
1640 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001641 } else {
1642 // If the last case doesn't match, go to the default block.
1643 FallThrough = Default;
1644 }
1645
1646 Value *RHS, *LHS, *MHS;
1647 ISD::CondCode CC;
1648 if (I->High == I->Low) {
1649 // This is just small small case range :) containing exactly 1 case
1650 CC = ISD::SETEQ;
1651 LHS = SV; RHS = I->High; MHS = NULL;
1652 } else {
1653 CC = ISD::SETLE;
1654 LHS = I->Low; MHS = SV; RHS = I->High;
1655 }
1656 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001657
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001658 // If emitting the first comparison, just call visitSwitchCase to emit the
1659 // code into the current block. Otherwise, push the CaseBlock onto the
1660 // vector to be later processed by SDISel, and insert the node's MBB
1661 // before the next MBB.
1662 if (CurBlock == CurMBB)
1663 visitSwitchCase(CB);
1664 else
1665 SwitchCases.push_back(CB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001666
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001667 CurBlock = FallThrough;
1668 }
1669
1670 return true;
1671}
1672
1673static inline bool areJTsAllowed(const TargetLowering &TLI) {
1674 return !DisableJumpTables &&
Dan Gohmanf560ffa2009-01-28 17:46:25 +00001675 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1676 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001677}
Anton Korobeynikov23218582008-12-23 22:25:27 +00001678
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001679static APInt ComputeRange(const APInt &First, const APInt &Last) {
1680 APInt LastExt(Last), FirstExt(First);
1681 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1682 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1683 return (LastExt - FirstExt + 1ULL);
1684}
1685
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001686/// handleJTSwitchCase - Emit jumptable for current switch case range
1687bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1688 CaseRecVector& WorkList,
1689 Value* SV,
1690 MachineBasicBlock* Default) {
1691 Case& FrontCase = *CR.Range.first;
1692 Case& BackCase = *(CR.Range.second-1);
1693
Anton Korobeynikov23218582008-12-23 22:25:27 +00001694 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1695 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001696
Anton Korobeynikov23218582008-12-23 22:25:27 +00001697 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001698 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1699 I!=E; ++I)
1700 TSize += I->size();
1701
1702 if (!areJTsAllowed(TLI) || TSize <= 3)
1703 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001704
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001705 APInt Range = ComputeRange(First, Last);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001706 double Density = (double)TSize / Range.roundToDouble();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001707 if (Density < 0.4)
1708 return false;
1709
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001710 DEBUG(errs() << "Lowering jump table\n"
1711 << "First entry: " << First << ". Last entry: " << Last << '\n'
1712 << "Range: " << Range
1713 << "Size: " << TSize << ". Density: " << Density << "\n\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001714
1715 // Get the MachineFunction which holds the current MBB. This is used when
1716 // inserting any additional MBBs necessary to represent the switch.
1717 MachineFunction *CurMF = CurMBB->getParent();
1718
1719 // Figure out which block is immediately after the current one.
1720 MachineBasicBlock *NextBlock = 0;
1721 MachineFunction::iterator BBI = CR.CaseBB;
1722
1723 if (++BBI != CurMBB->getParent()->end())
1724 NextBlock = BBI;
1725
1726 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1727
1728 // Create a new basic block to hold the code for loading the address
1729 // of the jump table, and jumping to it. Update successor information;
1730 // we will either branch to the default case for the switch, or the jump
1731 // table.
1732 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1733 CurMF->insert(BBI, JumpTableBB);
1734 CR.CaseBB->addSuccessor(Default);
1735 CR.CaseBB->addSuccessor(JumpTableBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001736
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001737 // Build a vector of destination BBs, corresponding to each target
1738 // of the jump table. If the value of the jump table slot corresponds to
1739 // a case statement, push the case's BB onto the vector, otherwise, push
1740 // the default BB.
1741 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001742 APInt TEI = First;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001743 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001744 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1745 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1746
1747 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001748 DestBBs.push_back(I->BB);
1749 if (TEI==High)
1750 ++I;
1751 } else {
1752 DestBBs.push_back(Default);
1753 }
1754 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001755
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001756 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001757 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1758 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001759 E = DestBBs.end(); I != E; ++I) {
1760 if (!SuccsHandled[(*I)->getNumber()]) {
1761 SuccsHandled[(*I)->getNumber()] = true;
1762 JumpTableBB->addSuccessor(*I);
1763 }
1764 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001765
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001766 // Create a jump table index for this jump table, or return an existing
1767 // one.
1768 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001769
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001770 // Set the jump table information so that we can codegen it as a second
1771 // MachineBasicBlock
1772 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1773 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1774 if (CR.CaseBB == CurMBB)
1775 visitJumpTableHeader(JT, JTH);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001776
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001777 JTCases.push_back(JumpTableBlock(JTH, JT));
1778
1779 return true;
1780}
1781
1782/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1783/// 2 subtrees.
1784bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1785 CaseRecVector& WorkList,
1786 Value* SV,
1787 MachineBasicBlock* Default) {
1788 // Get the MachineFunction which holds the current MBB. This is used when
1789 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001790 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001791
1792 // Figure out which block is immediately after the current one.
1793 MachineBasicBlock *NextBlock = 0;
1794 MachineFunction::iterator BBI = CR.CaseBB;
1795
1796 if (++BBI != CurMBB->getParent()->end())
1797 NextBlock = BBI;
1798
1799 Case& FrontCase = *CR.Range.first;
1800 Case& BackCase = *(CR.Range.second-1);
1801 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1802
1803 // Size is the number of Cases represented by this range.
1804 unsigned Size = CR.Range.second - CR.Range.first;
1805
Anton Korobeynikov23218582008-12-23 22:25:27 +00001806 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1807 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001808 double FMetric = 0;
1809 CaseItr Pivot = CR.Range.first + Size/2;
1810
1811 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1812 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001813 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001814 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1815 I!=E; ++I)
1816 TSize += I->size();
1817
Anton Korobeynikov23218582008-12-23 22:25:27 +00001818 size_t LSize = FrontCase.size();
1819 size_t RSize = TSize-LSize;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001820 DEBUG(errs() << "Selecting best pivot: \n"
1821 << "First: " << First << ", Last: " << Last <<'\n'
1822 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001823 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1824 J!=E; ++I, ++J) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001825 const APInt& LEnd = cast<ConstantInt>(I->High)->getValue();
1826 const APInt& RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001827 APInt Range = ComputeRange(LEnd, RBegin);
1828 assert((Range - 2ULL).isNonNegative() &&
1829 "Invalid case distance");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001830 double LDensity = (double)LSize / (LEnd - First + 1ULL).roundToDouble();
1831 double RDensity = (double)RSize / (Last - RBegin + 1ULL).roundToDouble();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001832 double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001833 // Should always split in some non-trivial place
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001834 DEBUG(errs() <<"=>Step\n"
1835 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1836 << "LDensity: " << LDensity
1837 << ", RDensity: " << RDensity << '\n'
1838 << "Metric: " << Metric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001839 if (FMetric < Metric) {
1840 Pivot = J;
1841 FMetric = Metric;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001842 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001843 }
1844
1845 LSize += J->size();
1846 RSize -= J->size();
1847 }
1848 if (areJTsAllowed(TLI)) {
1849 // If our case is dense we *really* should handle it earlier!
1850 assert((FMetric > 0) && "Should handle dense range earlier!");
1851 } else {
1852 Pivot = CR.Range.first + Size/2;
1853 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001854
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001855 CaseRange LHSR(CR.Range.first, Pivot);
1856 CaseRange RHSR(Pivot, CR.Range.second);
1857 Constant *C = Pivot->Low;
1858 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001859
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001860 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001861 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001862 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001863 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001864 // Pivot's Value, then we can branch directly to the LHS's Target,
1865 // rather than creating a leaf node for it.
1866 if ((LHSR.second - LHSR.first) == 1 &&
1867 LHSR.first->High == CR.GE &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001868 cast<ConstantInt>(C)->getValue() ==
1869 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001870 TrueBB = LHSR.first->BB;
1871 } else {
1872 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1873 CurMF->insert(BBI, TrueBB);
1874 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001875
1876 // Put SV in a virtual register to make it available from the new blocks.
1877 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001878 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001879
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001880 // Similar to the optimization above, if the Value being switched on is
1881 // known to be less than the Constant CR.LT, and the current Case Value
1882 // is CR.LT - 1, then we can branch directly to the target block for
1883 // the current Case Value, rather than emitting a RHS leaf node for it.
1884 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001885 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1886 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001887 FalseBB = RHSR.first->BB;
1888 } else {
1889 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1890 CurMF->insert(BBI, FalseBB);
1891 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001892
1893 // Put SV in a virtual register to make it available from the new blocks.
1894 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001895 }
1896
1897 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001898 // the LHS node if the value being switched on SV is less than C.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001899 // Otherwise, branch to LHS.
1900 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1901
1902 if (CR.CaseBB == CurMBB)
1903 visitSwitchCase(CB);
1904 else
1905 SwitchCases.push_back(CB);
1906
1907 return true;
1908}
1909
1910/// handleBitTestsSwitchCase - if current case range has few destination and
1911/// range span less, than machine word bitwidth, encode case range into series
1912/// of masks and emit bit tests with these masks.
1913bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1914 CaseRecVector& WorkList,
1915 Value* SV,
1916 MachineBasicBlock* Default){
1917 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1918
1919 Case& FrontCase = *CR.Range.first;
1920 Case& BackCase = *(CR.Range.second-1);
1921
1922 // Get the MachineFunction which holds the current MBB. This is used when
1923 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001924 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001925
Anton Korobeynikovd34167a2009-05-08 18:51:34 +00001926 // If target does not have legal shift left, do not emit bit tests at all.
1927 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
1928 return false;
1929
Anton Korobeynikov23218582008-12-23 22:25:27 +00001930 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001931 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1932 I!=E; ++I) {
1933 // Single case counts one, case range - two.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001934 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001935 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001936
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001937 // Count unique destinations
1938 SmallSet<MachineBasicBlock*, 4> Dests;
1939 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1940 Dests.insert(I->BB);
1941 if (Dests.size() > 3)
1942 // Don't bother the code below, if there are too much unique destinations
1943 return false;
1944 }
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001945 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1946 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001947
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001948 // Compute span of values.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001949 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1950 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001951 APInt cmpRange = maxValue - minValue;
1952
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001953 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1954 << "Low bound: " << minValue << '\n'
1955 << "High bound: " << maxValue << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001956
1957 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001958 (!(Dests.size() == 1 && numCmps >= 3) &&
1959 !(Dests.size() == 2 && numCmps >= 5) &&
1960 !(Dests.size() >= 3 && numCmps >= 6)))
1961 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001962
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001963 DEBUG(errs() << "Emitting bit tests\n");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001964 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1965
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001966 // Optimize the case where all the case values fit in a
1967 // word without having to subtract minValue. In this case,
1968 // we can optimize away the subtraction.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001969 if (minValue.isNonNegative() &&
1970 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1971 cmpRange = maxValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001972 } else {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001973 lowBound = minValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001974 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001975
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001976 CaseBitsVector CasesBits;
1977 unsigned i, count = 0;
1978
1979 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1980 MachineBasicBlock* Dest = I->BB;
1981 for (i = 0; i < count; ++i)
1982 if (Dest == CasesBits[i].BB)
1983 break;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001984
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001985 if (i == count) {
1986 assert((count < 3) && "Too much destinations to test!");
1987 CasesBits.push_back(CaseBits(0, Dest, 0));
1988 count++;
1989 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001990
1991 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1992 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1993
1994 uint64_t lo = (lowValue - lowBound).getZExtValue();
1995 uint64_t hi = (highValue - lowBound).getZExtValue();
1996
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001997 for (uint64_t j = lo; j <= hi; j++) {
1998 CasesBits[i].Mask |= 1ULL << j;
1999 CasesBits[i].Bits++;
2000 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002001
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002002 }
2003 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov23218582008-12-23 22:25:27 +00002004
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002005 BitTestInfo BTC;
2006
2007 // Figure out which block is immediately after the current one.
2008 MachineFunction::iterator BBI = CR.CaseBB;
2009 ++BBI;
2010
2011 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2012
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002013 DEBUG(errs() << "Cases:\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002014 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002015 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
2016 << ", Bits: " << CasesBits[i].Bits
2017 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002018
2019 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2020 CurMF->insert(BBI, CaseBB);
2021 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2022 CaseBB,
2023 CasesBits[i].BB));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00002024
2025 // Put SV in a virtual register to make it available from the new blocks.
2026 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002027 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002028
2029 BitTestBlock BTB(lowBound, cmpRange, SV,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002030 -1U, (CR.CaseBB == CurMBB),
2031 CR.CaseBB, Default, BTC);
2032
2033 if (CR.CaseBB == CurMBB)
2034 visitBitTestHeader(BTB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002035
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002036 BitTestCases.push_back(BTB);
2037
2038 return true;
2039}
2040
2041
2042/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov23218582008-12-23 22:25:27 +00002043size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002044 const SwitchInst& SI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00002045 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002046
2047 // Start with "simple" cases
Anton Korobeynikov23218582008-12-23 22:25:27 +00002048 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002049 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2050 Cases.push_back(Case(SI.getSuccessorValue(i),
2051 SI.getSuccessorValue(i),
2052 SMBB));
2053 }
2054 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2055
2056 // Merge case into clusters
Anton Korobeynikov23218582008-12-23 22:25:27 +00002057 if (Cases.size() >= 2)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002058 // Must recompute end() each iteration because it may be
2059 // invalidated by erase if we hold on to it
Anton Korobeynikov23218582008-12-23 22:25:27 +00002060 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
2061 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2062 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002063 MachineBasicBlock* nextBB = J->BB;
2064 MachineBasicBlock* currentBB = I->BB;
2065
2066 // If the two neighboring cases go to the same destination, merge them
2067 // into a single case.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002068 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002069 I->High = J->High;
2070 J = Cases.erase(J);
2071 } else {
2072 I = J++;
2073 }
2074 }
2075
2076 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2077 if (I->Low != I->High)
2078 // A range counts double, since it requires two compares.
2079 ++numCmps;
2080 }
2081
2082 return numCmps;
2083}
2084
Anton Korobeynikov23218582008-12-23 22:25:27 +00002085void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002086 // Figure out which block is immediately after the current one.
2087 MachineBasicBlock *NextBlock = 0;
2088 MachineFunction::iterator BBI = CurMBB;
2089
2090 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2091
2092 // If there is only the default destination, branch to it if it is not the
2093 // next basic block. Otherwise, just fall through.
2094 if (SI.getNumOperands() == 2) {
2095 // Update machine-CFG edges.
2096
2097 // If this is not a fall-through branch, emit the branch.
2098 CurMBB->addSuccessor(Default);
2099 if (Default != NextBlock)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002100 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002101 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002102 DAG.getBasicBlock(Default)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002103 return;
2104 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002105
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002106 // If there are any non-default case statements, create a vector of Cases
2107 // representing each one, and sort the vector so that we can efficiently
2108 // create a binary search tree from them.
2109 CaseVector Cases;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002110 size_t numCmps = Clusterify(Cases, SI);
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002111 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2112 << ". Total compares: " << numCmps << '\n');
Devang Patel8a84e442009-01-05 17:31:22 +00002113 numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002114
2115 // Get the Value to be switched on and default basic blocks, which will be
2116 // inserted into CaseBlock records, representing basic blocks in the binary
2117 // search tree.
2118 Value *SV = SI.getOperand(0);
2119
2120 // Push the initial CaseRec onto the worklist
2121 CaseRecVector WorkList;
2122 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2123
2124 while (!WorkList.empty()) {
2125 // Grab a record representing a case range to process off the worklist
2126 CaseRec CR = WorkList.back();
2127 WorkList.pop_back();
2128
2129 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2130 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002131
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002132 // If the range has few cases (two or less) emit a series of specific
2133 // tests.
2134 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2135 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002136
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002137 // If the switch has more than 5 blocks, and at least 40% dense, and the
2138 // target supports indirect branches, then emit a jump table rather than
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002139 // lowering the switch to a binary tree of conditional branches.
2140 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2141 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002142
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002143 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2144 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2145 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2146 }
2147}
2148
2149
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002150void SelectionDAGLowering::visitFSub(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002151 // -0.0 - X --> fneg
2152 const Type *Ty = I.getType();
2153 if (isa<VectorType>(Ty)) {
2154 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2155 const VectorType *DestTy = cast<VectorType>(I.getType());
2156 const Type *ElTy = DestTy->getElementType();
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002157 unsigned VL = DestTy->getNumElements();
2158 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2159 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2160 if (CV == CNZ) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002161 SDValue Op2 = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002162 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002163 Op2.getValueType(), Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002164 return;
2165 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002166 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002167 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002168 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2169 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2170 SDValue Op2 = getValue(I.getOperand(1));
2171 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2172 Op2.getValueType(), Op2));
2173 return;
2174 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002175
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002176 visitBinary(I, ISD::FSUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002177}
2178
2179void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2180 SDValue Op1 = getValue(I.getOperand(0));
2181 SDValue Op2 = getValue(I.getOperand(1));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002182
Scott Michelfdc40a02009-02-17 22:15:04 +00002183 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002184 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002185}
2186
2187void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2188 SDValue Op1 = getValue(I.getOperand(0));
2189 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman57fc82d2009-04-09 03:51:29 +00002190 if (!isa<VectorType>(I.getType()) &&
2191 Op2.getValueType() != TLI.getShiftAmountTy()) {
2192 // If the operand is smaller than the shift count type, promote it.
2193 if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2194 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2195 TLI.getShiftAmountTy(), Op2);
2196 // If the operand is larger than the shift count type but the shift
2197 // count type has enough bits to represent any shift value, truncate
2198 // it now. This is a common case and it exposes the truncate to
2199 // optimization early.
2200 else if (TLI.getShiftAmountTy().getSizeInBits() >=
2201 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2202 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2203 TLI.getShiftAmountTy(), Op2);
2204 // Otherwise we'll need to temporarily settle for some other
2205 // convenient type; type legalization will make adjustments as
2206 // needed.
2207 else if (TLI.getPointerTy().bitsLT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002208 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002209 TLI.getPointerTy(), Op2);
2210 else if (TLI.getPointerTy().bitsGT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002211 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002212 TLI.getPointerTy(), Op2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002213 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002214
Scott Michelfdc40a02009-02-17 22:15:04 +00002215 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002216 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002217}
2218
2219void SelectionDAGLowering::visitICmp(User &I) {
2220 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2221 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2222 predicate = IC->getPredicate();
2223 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2224 predicate = ICmpInst::Predicate(IC->getPredicate());
2225 SDValue Op1 = getValue(I.getOperand(0));
2226 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002227 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dale Johannesenf5d97892009-02-04 01:48:28 +00002228 setValue(&I, DAG.getSetCC(getCurDebugLoc(),MVT::i1, Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002229}
2230
2231void SelectionDAGLowering::visitFCmp(User &I) {
2232 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2233 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2234 predicate = FC->getPredicate();
2235 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2236 predicate = FCmpInst::Predicate(FC->getPredicate());
2237 SDValue Op1 = getValue(I.getOperand(0));
2238 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002239 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dale Johannesenf5d97892009-02-04 01:48:28 +00002240 setValue(&I, DAG.getSetCC(getCurDebugLoc(), MVT::i1, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002241}
2242
2243void SelectionDAGLowering::visitVICmp(User &I) {
2244 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2245 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2246 predicate = IC->getPredicate();
2247 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2248 predicate = ICmpInst::Predicate(IC->getPredicate());
2249 SDValue Op1 = getValue(I.getOperand(0));
2250 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002251 ISD::CondCode Opcode = getICmpCondCode(predicate);
Scott Michelfdc40a02009-02-17 22:15:04 +00002252 setValue(&I, DAG.getVSetCC(getCurDebugLoc(), Op1.getValueType(),
Dale Johannesenf5d97892009-02-04 01:48:28 +00002253 Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002254}
2255
2256void SelectionDAGLowering::visitVFCmp(User &I) {
2257 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2258 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2259 predicate = FC->getPredicate();
2260 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2261 predicate = FCmpInst::Predicate(FC->getPredicate());
2262 SDValue Op1 = getValue(I.getOperand(0));
2263 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002264 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002265 MVT DestVT = TLI.getValueType(I.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002266
Dale Johannesenf5d97892009-02-04 01:48:28 +00002267 setValue(&I, DAG.getVSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002268}
2269
2270void SelectionDAGLowering::visitSelect(User &I) {
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002271 SmallVector<MVT, 4> ValueVTs;
2272 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2273 unsigned NumValues = ValueVTs.size();
2274 if (NumValues != 0) {
2275 SmallVector<SDValue, 4> Values(NumValues);
2276 SDValue Cond = getValue(I.getOperand(0));
2277 SDValue TrueVal = getValue(I.getOperand(1));
2278 SDValue FalseVal = getValue(I.getOperand(2));
2279
2280 for (unsigned i = 0; i != NumValues; ++i)
Scott Michelfdc40a02009-02-17 22:15:04 +00002281 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002282 TrueVal.getValueType(), Cond,
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002283 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2284 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2285
Scott Michelfdc40a02009-02-17 22:15:04 +00002286 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002287 DAG.getVTList(&ValueVTs[0], NumValues),
2288 &Values[0], NumValues));
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002289 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002290}
2291
2292
2293void SelectionDAGLowering::visitTrunc(User &I) {
2294 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2295 SDValue N = getValue(I.getOperand(0));
2296 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002297 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002298}
2299
2300void SelectionDAGLowering::visitZExt(User &I) {
2301 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2302 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2303 SDValue N = getValue(I.getOperand(0));
2304 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002305 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002306}
2307
2308void SelectionDAGLowering::visitSExt(User &I) {
2309 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2310 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2311 SDValue N = getValue(I.getOperand(0));
2312 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002313 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002314}
2315
2316void SelectionDAGLowering::visitFPTrunc(User &I) {
2317 // FPTrunc is never a no-op cast, no need to check
2318 SDValue N = getValue(I.getOperand(0));
2319 MVT DestVT = TLI.getValueType(I.getType());
Scott Michelfdc40a02009-02-17 22:15:04 +00002320 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002321 DestVT, N, DAG.getIntPtrConstant(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002322}
2323
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002324void SelectionDAGLowering::visitFPExt(User &I){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002325 // FPTrunc is never a no-op cast, no need to check
2326 SDValue N = getValue(I.getOperand(0));
2327 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002328 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002329}
2330
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002331void SelectionDAGLowering::visitFPToUI(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002332 // FPToUI is never a no-op cast, no need to check
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::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002336}
2337
2338void SelectionDAGLowering::visitFPToSI(User &I) {
2339 // FPToSI is never a no-op cast, no need to check
2340 SDValue N = getValue(I.getOperand(0));
2341 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002342 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002343}
2344
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002345void SelectionDAGLowering::visitUIToFP(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002346 // UIToFP is never a no-op cast, no need to check
2347 SDValue N = getValue(I.getOperand(0));
2348 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002349 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002350}
2351
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002352void SelectionDAGLowering::visitSIToFP(User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002353 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002354 SDValue N = getValue(I.getOperand(0));
2355 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002356 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002357}
2358
2359void SelectionDAGLowering::visitPtrToInt(User &I) {
2360 // What to do depends on the size of the integer and the size of the pointer.
2361 // We can either truncate, zero extend, or no-op, accordingly.
2362 SDValue N = getValue(I.getOperand(0));
2363 MVT SrcVT = N.getValueType();
2364 MVT DestVT = TLI.getValueType(I.getType());
2365 SDValue Result;
2366 if (DestVT.bitsLT(SrcVT))
Dale Johannesen66978ee2009-01-31 02:22:37 +00002367 Result = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002368 else
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002369 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
Dale Johannesen66978ee2009-01-31 02:22:37 +00002370 Result = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002371 setValue(&I, Result);
2372}
2373
2374void SelectionDAGLowering::visitIntToPtr(User &I) {
2375 // What to do depends on the size of the integer and the size of the pointer.
2376 // We can either truncate, zero extend, or no-op, accordingly.
2377 SDValue N = getValue(I.getOperand(0));
2378 MVT SrcVT = N.getValueType();
2379 MVT DestVT = TLI.getValueType(I.getType());
2380 if (DestVT.bitsLT(SrcVT))
Dale Johannesen66978ee2009-01-31 02:22:37 +00002381 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002382 else
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002383 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
Scott Michelfdc40a02009-02-17 22:15:04 +00002384 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002385 DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002386}
2387
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002388void SelectionDAGLowering::visitBitCast(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002389 SDValue N = getValue(I.getOperand(0));
2390 MVT DestVT = TLI.getValueType(I.getType());
2391
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002392 // BitCast assures us that source and destination are the same size so this
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002393 // is either a BIT_CONVERT or a no-op.
2394 if (DestVT != N.getValueType())
Scott Michelfdc40a02009-02-17 22:15:04 +00002395 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002396 DestVT, N)); // convert types
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002397 else
2398 setValue(&I, N); // noop cast.
2399}
2400
2401void SelectionDAGLowering::visitInsertElement(User &I) {
2402 SDValue InVec = getValue(I.getOperand(0));
2403 SDValue InVal = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002404 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002405 TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002406 getValue(I.getOperand(2)));
2407
Scott Michelfdc40a02009-02-17 22:15:04 +00002408 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002409 TLI.getValueType(I.getType()),
2410 InVec, InVal, InIdx));
2411}
2412
2413void SelectionDAGLowering::visitExtractElement(User &I) {
2414 SDValue InVec = getValue(I.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00002415 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002416 TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002417 getValue(I.getOperand(1)));
Dale Johannesen66978ee2009-01-31 02:22:37 +00002418 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002419 TLI.getValueType(I.getType()), InVec, InIdx));
2420}
2421
Mon P Wangaeb06d22008-11-10 04:46:22 +00002422
2423// Utility for visitShuffleVector - Returns true if the mask is mask starting
2424// from SIndx and increasing to the element length (undefs are allowed).
Nate Begeman5a5ca152009-04-29 05:20:52 +00002425static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2426 unsigned MaskNumElts = Mask.size();
2427 for (unsigned i = 0; i != MaskNumElts; ++i)
2428 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
Nate Begeman9008ca62009-04-27 18:41:29 +00002429 return false;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002430 return true;
2431}
2432
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002433void SelectionDAGLowering::visitShuffleVector(User &I) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002434 SmallVector<int, 8> Mask;
Mon P Wang230e4fa2008-11-21 04:25:21 +00002435 SDValue Src1 = getValue(I.getOperand(0));
2436 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002437
Nate Begeman9008ca62009-04-27 18:41:29 +00002438 // Convert the ConstantVector mask operand into an array of ints, with -1
2439 // representing undef values.
2440 SmallVector<Constant*, 8> MaskElts;
2441 cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
Nate Begeman5a5ca152009-04-29 05:20:52 +00002442 unsigned MaskNumElts = MaskElts.size();
2443 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002444 if (isa<UndefValue>(MaskElts[i]))
2445 Mask.push_back(-1);
2446 else
2447 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2448 }
2449
Mon P Wangaeb06d22008-11-10 04:46:22 +00002450 MVT VT = TLI.getValueType(I.getType());
Mon P Wang230e4fa2008-11-21 04:25:21 +00002451 MVT SrcVT = Src1.getValueType();
Nate Begeman5a5ca152009-04-29 05:20:52 +00002452 unsigned SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002453
Mon P Wangc7849c22008-11-16 05:06:27 +00002454 if (SrcNumElts == MaskNumElts) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002455 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2456 &Mask[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002457 return;
2458 }
2459
2460 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002461 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2462 // Mask is longer than the source vectors and is a multiple of the source
2463 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang230e4fa2008-11-21 04:25:21 +00002464 // lengths match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002465 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2466 // The shuffle is concatenating two vectors together.
Scott Michelfdc40a02009-02-17 22:15:04 +00002467 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002468 VT, Src1, Src2));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002469 return;
2470 }
2471
Mon P Wangc7849c22008-11-16 05:06:27 +00002472 // Pad both vectors with undefs to make them the same length as the mask.
2473 unsigned NumConcat = MaskNumElts / SrcNumElts;
Nate Begeman9008ca62009-04-27 18:41:29 +00002474 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2475 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
Dale Johannesene8d72302009-02-06 23:05:02 +00002476 SDValue UndefVal = DAG.getUNDEF(SrcVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002477
Nate Begeman9008ca62009-04-27 18:41:29 +00002478 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2479 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002480 MOps1[0] = Src1;
2481 MOps2[0] = Src2;
Nate Begeman9008ca62009-04-27 18:41:29 +00002482
2483 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2484 getCurDebugLoc(), VT,
2485 &MOps1[0], NumConcat);
2486 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2487 getCurDebugLoc(), VT,
2488 &MOps2[0], NumConcat);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002489
Mon P Wangaeb06d22008-11-10 04:46:22 +00002490 // Readjust mask for new input vector length.
Nate Begeman9008ca62009-04-27 18:41:29 +00002491 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002492 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002493 int Idx = Mask[i];
Nate Begeman5a5ca152009-04-29 05:20:52 +00002494 if (Idx < (int)SrcNumElts)
Nate Begeman9008ca62009-04-27 18:41:29 +00002495 MappedOps.push_back(Idx);
2496 else
2497 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002498 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002499 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2500 &MappedOps[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002501 return;
2502 }
2503
Mon P Wangc7849c22008-11-16 05:06:27 +00002504 if (SrcNumElts > MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002505 // Analyze the access pattern of the vector to see if we can extract
2506 // two subvectors and do the shuffle. The analysis is done by calculating
2507 // the range of elements the mask access on both vectors.
2508 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2509 int MaxRange[2] = {-1, -1};
2510
Nate Begeman5a5ca152009-04-29 05:20:52 +00002511 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002512 int Idx = Mask[i];
2513 int Input = 0;
2514 if (Idx < 0)
2515 continue;
2516
Nate Begeman5a5ca152009-04-29 05:20:52 +00002517 if (Idx >= (int)SrcNumElts) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002518 Input = 1;
2519 Idx -= SrcNumElts;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002520 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002521 if (Idx > MaxRange[Input])
2522 MaxRange[Input] = Idx;
2523 if (Idx < MinRange[Input])
2524 MinRange[Input] = Idx;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002525 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002526
Mon P Wangc7849c22008-11-16 05:06:27 +00002527 // Check if the access is smaller than the vector size and can we find
2528 // a reasonable extract index.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002529 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
Mon P Wangc7849c22008-11-16 05:06:27 +00002530 int StartIdx[2]; // StartIdx to extract from
2531 for (int Input=0; Input < 2; ++Input) {
Nate Begeman5a5ca152009-04-29 05:20:52 +00002532 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002533 RangeUse[Input] = 0; // Unused
2534 StartIdx[Input] = 0;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002535 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002536 // Fits within range but we should see if we can find a good
Mon P Wang230e4fa2008-11-21 04:25:21 +00002537 // start index that is a multiple of the mask length.
Nate Begeman5a5ca152009-04-29 05:20:52 +00002538 if (MaxRange[Input] < (int)MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002539 RangeUse[Input] = 1; // Extract from beginning of the vector
2540 StartIdx[Input] = 0;
2541 } else {
2542 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002543 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002544 StartIdx[Input] + MaskNumElts < SrcNumElts)
Mon P Wangc7849c22008-11-16 05:06:27 +00002545 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002546 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002547 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002548 }
2549
2550 if (RangeUse[0] == 0 && RangeUse[0] == 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002551 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
Mon P Wangc7849c22008-11-16 05:06:27 +00002552 return;
2553 }
2554 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2555 // Extract appropriate subvector and generate a vector shuffle
2556 for (int Input=0; Input < 2; ++Input) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002557 SDValue& Src = Input == 0 ? Src1 : Src2;
Mon P Wangc7849c22008-11-16 05:06:27 +00002558 if (RangeUse[Input] == 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002559 Src = DAG.getUNDEF(VT);
Mon P Wangc7849c22008-11-16 05:06:27 +00002560 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002561 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002562 Src, DAG.getIntPtrConstant(StartIdx[Input]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002563 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002564 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002565 // Calculate new mask.
Nate Begeman9008ca62009-04-27 18:41:29 +00002566 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002567 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002568 int Idx = Mask[i];
2569 if (Idx < 0)
2570 MappedOps.push_back(Idx);
Nate Begeman5a5ca152009-04-29 05:20:52 +00002571 else if (Idx < (int)SrcNumElts)
Nate Begeman9008ca62009-04-27 18:41:29 +00002572 MappedOps.push_back(Idx - StartIdx[0]);
2573 else
2574 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
Mon P Wangc7849c22008-11-16 05:06:27 +00002575 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002576 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2577 &MappedOps[0]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002578 return;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002579 }
2580 }
2581
Mon P Wangc7849c22008-11-16 05:06:27 +00002582 // We can't use either concat vectors or extract subvectors so fall back to
2583 // replacing the shuffle with extract and build vector.
2584 // to insert and build vector.
Mon P Wangaeb06d22008-11-10 04:46:22 +00002585 MVT EltVT = VT.getVectorElementType();
2586 MVT PtrVT = TLI.getPointerTy();
2587 SmallVector<SDValue,8> Ops;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002588 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002589 if (Mask[i] < 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002590 Ops.push_back(DAG.getUNDEF(EltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002591 } else {
Nate Begeman9008ca62009-04-27 18:41:29 +00002592 int Idx = Mask[i];
Nate Begeman5a5ca152009-04-29 05:20:52 +00002593 if (Idx < (int)SrcNumElts)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002594 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002595 EltVT, Src1, DAG.getConstant(Idx, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002596 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00002597 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Scott Michelfdc40a02009-02-17 22:15:04 +00002598 EltVT, Src2,
Mon P Wangc7849c22008-11-16 05:06:27 +00002599 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002600 }
2601 }
Evan Chenga87008d2009-02-25 22:49:59 +00002602 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2603 VT, &Ops[0], Ops.size()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002604}
2605
2606void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2607 const Value *Op0 = I.getOperand(0);
2608 const Value *Op1 = I.getOperand(1);
2609 const Type *AggTy = I.getType();
2610 const Type *ValTy = Op1->getType();
2611 bool IntoUndef = isa<UndefValue>(Op0);
2612 bool FromUndef = isa<UndefValue>(Op1);
2613
2614 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2615 I.idx_begin(), I.idx_end());
2616
2617 SmallVector<MVT, 4> AggValueVTs;
2618 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2619 SmallVector<MVT, 4> ValValueVTs;
2620 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2621
2622 unsigned NumAggValues = AggValueVTs.size();
2623 unsigned NumValValues = ValValueVTs.size();
2624 SmallVector<SDValue, 4> Values(NumAggValues);
2625
2626 SDValue Agg = getValue(Op0);
2627 SDValue Val = getValue(Op1);
2628 unsigned i = 0;
2629 // Copy the beginning value(s) from the original aggregate.
2630 for (; i != LinearIndex; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002631 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002632 SDValue(Agg.getNode(), Agg.getResNo() + i);
2633 // Copy values from the inserted value(s).
2634 for (; i != LinearIndex + NumValValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002635 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002636 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2637 // Copy remaining value(s) from the original aggregate.
2638 for (; i != NumAggValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002639 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002640 SDValue(Agg.getNode(), Agg.getResNo() + i);
2641
Scott Michelfdc40a02009-02-17 22:15:04 +00002642 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002643 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2644 &Values[0], NumAggValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002645}
2646
2647void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2648 const Value *Op0 = I.getOperand(0);
2649 const Type *AggTy = Op0->getType();
2650 const Type *ValTy = I.getType();
2651 bool OutOfUndef = isa<UndefValue>(Op0);
2652
2653 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2654 I.idx_begin(), I.idx_end());
2655
2656 SmallVector<MVT, 4> ValValueVTs;
2657 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2658
2659 unsigned NumValValues = ValValueVTs.size();
2660 SmallVector<SDValue, 4> Values(NumValValues);
2661
2662 SDValue Agg = getValue(Op0);
2663 // Copy out the selected value(s).
2664 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2665 Values[i - LinearIndex] =
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002666 OutOfUndef ?
Dale Johannesene8d72302009-02-06 23:05:02 +00002667 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002668 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002669
Scott Michelfdc40a02009-02-17 22:15:04 +00002670 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002671 DAG.getVTList(&ValValueVTs[0], NumValValues),
2672 &Values[0], NumValValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002673}
2674
2675
2676void SelectionDAGLowering::visitGetElementPtr(User &I) {
2677 SDValue N = getValue(I.getOperand(0));
2678 const Type *Ty = I.getOperand(0)->getType();
2679
2680 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2681 OI != E; ++OI) {
2682 Value *Idx = *OI;
2683 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2684 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2685 if (Field) {
2686 // N = N + Offset
2687 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002688 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002689 DAG.getIntPtrConstant(Offset));
2690 }
2691 Ty = StTy->getElementType(Field);
2692 } else {
2693 Ty = cast<SequentialType>(Ty)->getElementType();
2694
2695 // If this is a constant subscript, handle it quickly.
2696 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2697 if (CI->getZExtValue() == 0) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002698 uint64_t Offs =
Duncan Sands777d2302009-05-09 07:06:46 +00002699 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Evan Cheng65b52df2009-02-09 21:01:06 +00002700 SDValue OffsVal;
Evan Chengb1032a82009-02-09 20:54:38 +00002701 unsigned PtrBits = TLI.getPointerTy().getSizeInBits();
Evan Cheng65b52df2009-02-09 21:01:06 +00002702 if (PtrBits < 64) {
2703 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2704 TLI.getPointerTy(),
2705 DAG.getConstant(Offs, MVT::i64));
2706 } else
Evan Chengb1032a82009-02-09 20:54:38 +00002707 OffsVal = DAG.getIntPtrConstant(Offs);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002708 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Evan Chengb1032a82009-02-09 20:54:38 +00002709 OffsVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002710 continue;
2711 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002712
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002713 // N = N + Idx * ElementSize;
Duncan Sands777d2302009-05-09 07:06:46 +00002714 uint64_t ElementSize = TD->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002715 SDValue IdxN = getValue(Idx);
2716
2717 // If the index is smaller or larger than intptr_t, truncate or extend
2718 // it.
2719 if (IdxN.getValueType().bitsLT(N.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002720 IdxN = DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002721 N.getValueType(), IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002722 else if (IdxN.getValueType().bitsGT(N.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002723 IdxN = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002724 N.getValueType(), IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002725
2726 // If this is a multiply by a power of two, turn it into a shl
2727 // immediately. This is a very common case.
2728 if (ElementSize != 1) {
2729 if (isPowerOf2_64(ElementSize)) {
2730 unsigned Amt = Log2_64(ElementSize);
Scott Michelfdc40a02009-02-17 22:15:04 +00002731 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002732 N.getValueType(), IdxN,
Duncan Sands92abc622009-01-31 15:50:11 +00002733 DAG.getConstant(Amt, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002734 } else {
2735 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
Scott Michelfdc40a02009-02-17 22:15:04 +00002736 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002737 N.getValueType(), IdxN, Scale);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002738 }
2739 }
2740
Scott Michelfdc40a02009-02-17 22:15:04 +00002741 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002742 N.getValueType(), N, IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002743 }
2744 }
2745 setValue(&I, N);
2746}
2747
2748void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2749 // If this is a fixed sized alloca in the entry block of the function,
2750 // allocate it statically on the stack.
2751 if (FuncInfo.StaticAllocaMap.count(&I))
2752 return; // getValue will auto-populate this.
2753
2754 const Type *Ty = I.getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002755 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002756 unsigned Align =
2757 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2758 I.getAlignment());
2759
2760 SDValue AllocSize = getValue(I.getArraySize());
Chris Lattner0b18e592009-03-17 19:36:00 +00002761
2762 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2763 AllocSize,
2764 DAG.getConstant(TySize, AllocSize.getValueType()));
2765
2766
2767
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002768 MVT IntPtr = TLI.getPointerTy();
2769 if (IntPtr.bitsLT(AllocSize.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002770 AllocSize = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002771 IntPtr, AllocSize);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002772 else if (IntPtr.bitsGT(AllocSize.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002773 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002774 IntPtr, AllocSize);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002775
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002776 // Handle alignment. If the requested alignment is less than or equal to
2777 // the stack alignment, ignore it. If the size is greater than or equal to
2778 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2779 unsigned StackAlign =
2780 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2781 if (Align <= StackAlign)
2782 Align = 0;
2783
2784 // Round the size of the allocation up to the stack alignment size
2785 // by add SA-1 to the size.
Scott Michelfdc40a02009-02-17 22:15:04 +00002786 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002787 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002788 DAG.getIntPtrConstant(StackAlign-1));
2789 // Mask out the low bits for alignment purposes.
Scott Michelfdc40a02009-02-17 22:15:04 +00002790 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002791 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002792 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2793
2794 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Dan Gohmanfc166572009-04-09 23:54:40 +00002795 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
Scott Michelfdc40a02009-02-17 22:15:04 +00002796 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002797 VTs, Ops, 3);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002798 setValue(&I, DSA);
2799 DAG.setRoot(DSA.getValue(1));
2800
2801 // Inform the Frame Information that we have just allocated a variable-sized
2802 // object.
2803 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2804}
2805
2806void SelectionDAGLowering::visitLoad(LoadInst &I) {
2807 const Value *SV = I.getOperand(0);
2808 SDValue Ptr = getValue(SV);
2809
2810 const Type *Ty = I.getType();
2811 bool isVolatile = I.isVolatile();
2812 unsigned Alignment = I.getAlignment();
2813
2814 SmallVector<MVT, 4> ValueVTs;
2815 SmallVector<uint64_t, 4> Offsets;
2816 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2817 unsigned NumValues = ValueVTs.size();
2818 if (NumValues == 0)
2819 return;
2820
2821 SDValue Root;
2822 bool ConstantMemory = false;
2823 if (I.isVolatile())
2824 // Serialize volatile loads with other side effects.
2825 Root = getRoot();
2826 else if (AA->pointsToConstantMemory(SV)) {
2827 // Do not serialize (non-volatile) loads of constant memory with anything.
2828 Root = DAG.getEntryNode();
2829 ConstantMemory = true;
2830 } else {
2831 // Do not serialize non-volatile loads against each other.
2832 Root = DAG.getRoot();
2833 }
2834
2835 SmallVector<SDValue, 4> Values(NumValues);
2836 SmallVector<SDValue, 4> Chains(NumValues);
2837 MVT PtrVT = Ptr.getValueType();
2838 for (unsigned i = 0; i != NumValues; ++i) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002839 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
Scott Michelfdc40a02009-02-17 22:15:04 +00002840 DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002841 PtrVT, Ptr,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002842 DAG.getConstant(Offsets[i], PtrVT)),
2843 SV, Offsets[i],
2844 isVolatile, Alignment);
2845 Values[i] = L;
2846 Chains[i] = L.getValue(1);
2847 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002848
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002849 if (!ConstantMemory) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002850 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002851 MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002852 &Chains[0], NumValues);
2853 if (isVolatile)
2854 DAG.setRoot(Chain);
2855 else
2856 PendingLoads.push_back(Chain);
2857 }
2858
Scott Michelfdc40a02009-02-17 22:15:04 +00002859 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002860 DAG.getVTList(&ValueVTs[0], NumValues),
2861 &Values[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002862}
2863
2864
2865void SelectionDAGLowering::visitStore(StoreInst &I) {
2866 Value *SrcV = I.getOperand(0);
2867 Value *PtrV = I.getOperand(1);
2868
2869 SmallVector<MVT, 4> ValueVTs;
2870 SmallVector<uint64_t, 4> Offsets;
2871 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2872 unsigned NumValues = ValueVTs.size();
2873 if (NumValues == 0)
2874 return;
2875
2876 // Get the lowered operands. Note that we do this after
2877 // checking if NumResults is zero, because with zero results
2878 // the operands won't have values in the map.
2879 SDValue Src = getValue(SrcV);
2880 SDValue Ptr = getValue(PtrV);
2881
2882 SDValue Root = getRoot();
2883 SmallVector<SDValue, 4> Chains(NumValues);
2884 MVT PtrVT = Ptr.getValueType();
2885 bool isVolatile = I.isVolatile();
2886 unsigned Alignment = I.getAlignment();
2887 for (unsigned i = 0; i != NumValues; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002888 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002889 SDValue(Src.getNode(), Src.getResNo() + i),
Scott Michelfdc40a02009-02-17 22:15:04 +00002890 DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002891 PtrVT, Ptr,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002892 DAG.getConstant(Offsets[i], PtrVT)),
2893 PtrV, Offsets[i],
2894 isVolatile, Alignment);
2895
Scott Michelfdc40a02009-02-17 22:15:04 +00002896 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002897 MVT::Other, &Chains[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002898}
2899
2900/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2901/// node.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002902void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002903 unsigned Intrinsic) {
2904 bool HasChain = !I.doesNotAccessMemory();
2905 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2906
2907 // Build the operand list.
2908 SmallVector<SDValue, 8> Ops;
2909 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2910 if (OnlyLoad) {
2911 // We don't need to serialize loads against other loads.
2912 Ops.push_back(DAG.getRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002913 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002914 Ops.push_back(getRoot());
2915 }
2916 }
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002917
2918 // Info is set by getTgtMemInstrinsic
2919 TargetLowering::IntrinsicInfo Info;
2920 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2921
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002922 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002923 if (!IsTgtIntrinsic)
2924 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002925
2926 // Add all operands of the call to the operand list.
2927 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2928 SDValue Op = getValue(I.getOperand(i));
2929 assert(TLI.isTypeLegal(Op.getValueType()) &&
2930 "Intrinsic uses a non-legal type?");
2931 Ops.push_back(Op);
2932 }
2933
Dan Gohmanfc166572009-04-09 23:54:40 +00002934 std::vector<MVT> VTArray;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002935 if (I.getType() != Type::VoidTy) {
2936 MVT VT = TLI.getValueType(I.getType());
2937 if (VT.isVector()) {
2938 const VectorType *DestTy = cast<VectorType>(I.getType());
2939 MVT EltVT = TLI.getValueType(DestTy->getElementType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002940
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002941 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2942 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2943 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002944
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002945 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
Dan Gohmanfc166572009-04-09 23:54:40 +00002946 VTArray.push_back(VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002947 }
2948 if (HasChain)
Dan Gohmanfc166572009-04-09 23:54:40 +00002949 VTArray.push_back(MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002950
Dan Gohmanfc166572009-04-09 23:54:40 +00002951 SDVTList VTs = DAG.getVTList(&VTArray[0], VTArray.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002952
2953 // Create the node.
2954 SDValue Result;
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002955 if (IsTgtIntrinsic) {
2956 // This is target intrinsic that touches memory
Dale Johannesen66978ee2009-01-31 02:22:37 +00002957 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002958 VTs, &Ops[0], Ops.size(),
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002959 Info.memVT, Info.ptrVal, Info.offset,
2960 Info.align, Info.vol,
2961 Info.readMem, Info.writeMem);
2962 }
2963 else if (!HasChain)
Scott Michelfdc40a02009-02-17 22:15:04 +00002964 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002965 VTs, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002966 else if (I.getType() != Type::VoidTy)
Scott Michelfdc40a02009-02-17 22:15:04 +00002967 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002968 VTs, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002969 else
Scott Michelfdc40a02009-02-17 22:15:04 +00002970 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002971 VTs, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002972
2973 if (HasChain) {
2974 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2975 if (OnlyLoad)
2976 PendingLoads.push_back(Chain);
2977 else
2978 DAG.setRoot(Chain);
2979 }
2980 if (I.getType() != Type::VoidTy) {
2981 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2982 MVT VT = TLI.getValueType(PTy);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002983 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002984 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002985 setValue(&I, Result);
2986 }
2987}
2988
2989/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2990static GlobalVariable *ExtractTypeInfo(Value *V) {
2991 V = V->stripPointerCasts();
2992 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2993 assert ((GV || isa<ConstantPointerNull>(V)) &&
2994 "TypeInfo must be a global variable or NULL");
2995 return GV;
2996}
2997
2998namespace llvm {
2999
3000/// AddCatchInfo - Extract the personality and type infos from an eh.selector
3001/// call, and add them to the specified machine basic block.
3002void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3003 MachineBasicBlock *MBB) {
3004 // Inform the MachineModuleInfo of the personality for this landing pad.
3005 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3006 assert(CE->getOpcode() == Instruction::BitCast &&
3007 isa<Function>(CE->getOperand(0)) &&
3008 "Personality should be a function");
3009 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3010
3011 // Gather all the type infos for this landing pad and pass them along to
3012 // MachineModuleInfo.
3013 std::vector<GlobalVariable *> TyInfo;
3014 unsigned N = I.getNumOperands();
3015
3016 for (unsigned i = N - 1; i > 2; --i) {
3017 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3018 unsigned FilterLength = CI->getZExtValue();
3019 unsigned FirstCatch = i + FilterLength + !FilterLength;
3020 assert (FirstCatch <= N && "Invalid filter length");
3021
3022 if (FirstCatch < N) {
3023 TyInfo.reserve(N - FirstCatch);
3024 for (unsigned j = FirstCatch; j < N; ++j)
3025 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3026 MMI->addCatchTypeInfo(MBB, TyInfo);
3027 TyInfo.clear();
3028 }
3029
3030 if (!FilterLength) {
3031 // Cleanup.
3032 MMI->addCleanup(MBB);
3033 } else {
3034 // Filter.
3035 TyInfo.reserve(FilterLength - 1);
3036 for (unsigned j = i + 1; j < FirstCatch; ++j)
3037 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3038 MMI->addFilterTypeInfo(MBB, TyInfo);
3039 TyInfo.clear();
3040 }
3041
3042 N = i;
3043 }
3044 }
3045
3046 if (N > 3) {
3047 TyInfo.reserve(N - 3);
3048 for (unsigned j = 3; j < N; ++j)
3049 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3050 MMI->addCatchTypeInfo(MBB, TyInfo);
3051 }
3052}
3053
3054}
3055
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003056/// GetSignificand - Get the significand and build it into a floating-point
3057/// number with exponent of 1:
3058///
3059/// Op = (Op & 0x007fffff) | 0x3f800000;
3060///
3061/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003062static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003063GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
3064 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003065 DAG.getConstant(0x007fffff, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003066 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003067 DAG.getConstant(0x3f800000, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003068 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003069}
3070
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003071/// GetExponent - Get the exponent:
3072///
Bill Wendlinge9a72862009-01-20 21:17:57 +00003073/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003074///
3075/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003076static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003077GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3078 DebugLoc dl) {
3079 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003080 DAG.getConstant(0x7f800000, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003081 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
Duncan Sands92abc622009-01-31 15:50:11 +00003082 DAG.getConstant(23, TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003083 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003084 DAG.getConstant(127, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003085 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003086}
3087
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003088/// getF32Constant - Get 32-bit floating point constant.
3089static SDValue
3090getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3091 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3092}
3093
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003094/// Inlined utility function to implement binary input atomic intrinsics for
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003095/// visitIntrinsicCall: I is a call instruction
3096/// Op is the associated NodeType for I
3097const char *
3098SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003099 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003100 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00003101 DAG.getAtomic(Op, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003102 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003103 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003104 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003105 getValue(I.getOperand(2)),
3106 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003107 setValue(&I, L);
3108 DAG.setRoot(L.getValue(1));
3109 return 0;
3110}
3111
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003112// implVisitAluOverflow - Lower arithmetic overflow instrinsics.
Bill Wendling74c37652008-12-09 22:08:41 +00003113const char *
3114SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003115 SDValue Op1 = getValue(I.getOperand(1));
3116 SDValue Op2 = getValue(I.getOperand(2));
Bill Wendling74c37652008-12-09 22:08:41 +00003117
Dan Gohmanfc166572009-04-09 23:54:40 +00003118 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
3119 SDValue Result = DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2);
Bill Wendling74c37652008-12-09 22:08:41 +00003120
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003121 setValue(&I, Result);
3122 return 0;
3123}
Bill Wendling74c37652008-12-09 22:08:41 +00003124
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003125/// visitExp - Lower an exp intrinsic. Handles the special sequences for
3126/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003127void
3128SelectionDAGLowering::visitExp(CallInst &I) {
3129 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003130 DebugLoc dl = getCurDebugLoc();
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003131
3132 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3133 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3134 SDValue Op = getValue(I.getOperand(1));
3135
3136 // Put the exponent in the right bit position for later addition to the
3137 // final result:
3138 //
3139 // #define LOG2OFe 1.4426950f
3140 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003141 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003142 getF32Constant(DAG, 0x3fb8aa3b));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003143 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003144
3145 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003146 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3147 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003148
3149 // IntegerPartOfX <<= 23;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003150 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003151 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003152
3153 if (LimitFloatPrecision <= 6) {
3154 // For floating-point precision of 6:
3155 //
3156 // TwoToFractionalPartOfX =
3157 // 0.997535578f +
3158 // (0.735607626f + 0.252464424f * x) * x;
3159 //
3160 // error 0.0144103317, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003161 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003162 getF32Constant(DAG, 0x3e814304));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003163 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003164 getF32Constant(DAG, 0x3f3c50c8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003165 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3166 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003167 getF32Constant(DAG, 0x3f7f5e7e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003168 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003169
3170 // Add the exponent into the result in integer domain.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003171 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003172 TwoToFracPartOfX, IntegerPartOfX);
3173
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003174 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003175 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3176 // For floating-point precision of 12:
3177 //
3178 // TwoToFractionalPartOfX =
3179 // 0.999892986f +
3180 // (0.696457318f +
3181 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3182 //
3183 // 0.000107046256 error, which is 13 to 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003184 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003185 getF32Constant(DAG, 0x3da235e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003186 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003187 getF32Constant(DAG, 0x3e65b8f3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003188 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3189 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003190 getF32Constant(DAG, 0x3f324b07));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003191 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3192 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003193 getF32Constant(DAG, 0x3f7ff8fd));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003194 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003195
3196 // Add the exponent into the result in integer domain.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003197 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003198 TwoToFracPartOfX, IntegerPartOfX);
3199
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003200 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003201 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3202 // For floating-point precision of 18:
3203 //
3204 // TwoToFractionalPartOfX =
3205 // 0.999999982f +
3206 // (0.693148872f +
3207 // (0.240227044f +
3208 // (0.554906021e-1f +
3209 // (0.961591928e-2f +
3210 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3211 //
3212 // error 2.47208000*10^(-7), which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003213 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003214 getF32Constant(DAG, 0x3924b03e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003215 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003216 getF32Constant(DAG, 0x3ab24b87));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003217 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3218 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003219 getF32Constant(DAG, 0x3c1d8c17));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003220 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3221 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003222 getF32Constant(DAG, 0x3d634a1d));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003223 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3224 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003225 getF32Constant(DAG, 0x3e75fe14));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003226 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3227 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003228 getF32Constant(DAG, 0x3f317234));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003229 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3230 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003231 getF32Constant(DAG, 0x3f800000));
Scott Michelfdc40a02009-02-17 22:15:04 +00003232 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003233 MVT::i32, t13);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003234
3235 // Add the exponent into the result in integer domain.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003236 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003237 TwoToFracPartOfX, IntegerPartOfX);
3238
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003239 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003240 }
3241 } else {
3242 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003243 result = DAG.getNode(ISD::FEXP, dl,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003244 getValue(I.getOperand(1)).getValueType(),
3245 getValue(I.getOperand(1)));
3246 }
3247
Dale Johannesen59e577f2008-09-05 18:38:42 +00003248 setValue(&I, result);
3249}
3250
Bill Wendling39150252008-09-09 20:39:27 +00003251/// visitLog - Lower a log intrinsic. Handles the special sequences for
3252/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003253void
3254SelectionDAGLowering::visitLog(CallInst &I) {
3255 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003256 DebugLoc dl = getCurDebugLoc();
Bill Wendling39150252008-09-09 20:39:27 +00003257
3258 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3259 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3260 SDValue Op = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003261 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling39150252008-09-09 20:39:27 +00003262
3263 // Scale the exponent by log(2) [0.69314718f].
Dale Johannesen66978ee2009-01-31 02:22:37 +00003264 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003265 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003266 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003267
3268 // Get the significand and build it into a floating-point number with
3269 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003270 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling39150252008-09-09 20:39:27 +00003271
3272 if (LimitFloatPrecision <= 6) {
3273 // For floating-point precision of 6:
3274 //
3275 // LogofMantissa =
3276 // -1.1609546f +
3277 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003278 //
Bill Wendling39150252008-09-09 20:39:27 +00003279 // error 0.0034276066, which is better than 8 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003280 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003281 getF32Constant(DAG, 0xbe74c456));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003282 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003283 getF32Constant(DAG, 0x3fb3a2b1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003284 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3285 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003286 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00003287
Scott Michelfdc40a02009-02-17 22:15:04 +00003288 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003289 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003290 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3291 // For floating-point precision of 12:
3292 //
3293 // LogOfMantissa =
3294 // -1.7417939f +
3295 // (2.8212026f +
3296 // (-1.4699568f +
3297 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3298 //
3299 // error 0.000061011436, which is 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003300 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003301 getF32Constant(DAG, 0xbd67b6d6));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003302 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003303 getF32Constant(DAG, 0x3ee4f4b8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003304 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3305 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003306 getF32Constant(DAG, 0x3fbc278b));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003307 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3308 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003309 getF32Constant(DAG, 0x40348e95));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003310 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3311 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003312 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00003313
Scott Michelfdc40a02009-02-17 22:15:04 +00003314 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003315 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003316 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3317 // For floating-point precision of 18:
3318 //
3319 // LogOfMantissa =
3320 // -2.1072184f +
3321 // (4.2372794f +
3322 // (-3.7029485f +
3323 // (2.2781945f +
3324 // (-0.87823314f +
3325 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3326 //
3327 // error 0.0000023660568, which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003328 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003329 getF32Constant(DAG, 0xbc91e5ac));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003330 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003331 getF32Constant(DAG, 0x3e4350aa));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003332 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3333 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003334 getF32Constant(DAG, 0x3f60d3e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003335 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3336 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003337 getF32Constant(DAG, 0x4011cdf0));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003338 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3339 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003340 getF32Constant(DAG, 0x406cfd1c));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003341 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3342 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003343 getF32Constant(DAG, 0x408797cb));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003344 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3345 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003346 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003347
Scott Michelfdc40a02009-02-17 22:15:04 +00003348 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003349 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003350 }
3351 } else {
3352 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003353 result = DAG.getNode(ISD::FLOG, dl,
Bill Wendling39150252008-09-09 20:39:27 +00003354 getValue(I.getOperand(1)).getValueType(),
3355 getValue(I.getOperand(1)));
3356 }
3357
Dale Johannesen59e577f2008-09-05 18:38:42 +00003358 setValue(&I, result);
3359}
3360
Bill Wendling3eb59402008-09-09 00:28:24 +00003361/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3362/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003363void
3364SelectionDAGLowering::visitLog2(CallInst &I) {
3365 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003366 DebugLoc dl = getCurDebugLoc();
Bill Wendling3eb59402008-09-09 00:28:24 +00003367
Dale Johannesen853244f2008-09-05 23:49:37 +00003368 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003369 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3370 SDValue Op = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003371 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003372
Bill Wendling39150252008-09-09 20:39:27 +00003373 // Get the exponent.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003374 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00003375
3376 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003377 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003378 SDValue X = GetSignificand(DAG, Op1, dl);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003379
Bill Wendling3eb59402008-09-09 00:28:24 +00003380 // Different possible minimax approximations of significand in
3381 // floating-point for various degrees of accuracy over [1,2].
3382 if (LimitFloatPrecision <= 6) {
3383 // For floating-point precision of 6:
3384 //
3385 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3386 //
3387 // error 0.0049451742, which is more than 7 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003388 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003389 getF32Constant(DAG, 0xbeb08fe0));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003390 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003391 getF32Constant(DAG, 0x40019463));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003392 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3393 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003394 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003395
Scott Michelfdc40a02009-02-17 22:15:04 +00003396 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003397 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003398 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3399 // For floating-point precision of 12:
3400 //
3401 // Log2ofMantissa =
3402 // -2.51285454f +
3403 // (4.07009056f +
3404 // (-2.12067489f +
3405 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003406 //
Bill Wendling3eb59402008-09-09 00:28:24 +00003407 // error 0.0000876136000, which is better than 13 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003408 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003409 getF32Constant(DAG, 0xbda7262e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003410 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003411 getF32Constant(DAG, 0x3f25280b));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003412 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3413 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003414 getF32Constant(DAG, 0x4007b923));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003415 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3416 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003417 getF32Constant(DAG, 0x40823e2f));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003418 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3419 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003420 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003421
Scott Michelfdc40a02009-02-17 22:15:04 +00003422 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003423 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003424 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3425 // For floating-point precision of 18:
3426 //
3427 // Log2ofMantissa =
3428 // -3.0400495f +
3429 // (6.1129976f +
3430 // (-5.3420409f +
3431 // (3.2865683f +
3432 // (-1.2669343f +
3433 // (0.27515199f -
3434 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3435 //
3436 // error 0.0000018516, which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003437 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003438 getF32Constant(DAG, 0xbcd2769e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003439 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003440 getF32Constant(DAG, 0x3e8ce0b9));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003441 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3442 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003443 getF32Constant(DAG, 0x3fa22ae7));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003444 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3445 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003446 getF32Constant(DAG, 0x40525723));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003447 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3448 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003449 getF32Constant(DAG, 0x40aaf200));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003450 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3451 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003452 getF32Constant(DAG, 0x40c39dad));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003453 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3454 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003455 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003456
Scott Michelfdc40a02009-02-17 22:15:04 +00003457 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003458 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003459 }
Dale Johannesen853244f2008-09-05 23:49:37 +00003460 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003461 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003462 result = DAG.getNode(ISD::FLOG2, dl,
Dale Johannesen853244f2008-09-05 23:49:37 +00003463 getValue(I.getOperand(1)).getValueType(),
3464 getValue(I.getOperand(1)));
3465 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003466
Dale Johannesen59e577f2008-09-05 18:38:42 +00003467 setValue(&I, result);
3468}
3469
Bill Wendling3eb59402008-09-09 00:28:24 +00003470/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3471/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003472void
3473SelectionDAGLowering::visitLog10(CallInst &I) {
3474 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003475 DebugLoc dl = getCurDebugLoc();
Bill Wendling181b6272008-10-19 20:34:04 +00003476
Dale Johannesen852680a2008-09-05 21:27:19 +00003477 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003478 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3479 SDValue Op = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003480 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003481
Bill Wendling39150252008-09-09 20:39:27 +00003482 // Scale the exponent by log10(2) [0.30102999f].
Dale Johannesen66978ee2009-01-31 02:22:37 +00003483 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003484 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003485 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003486
3487 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003488 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003489 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00003490
3491 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003492 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003493 //
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003494 // Log10ofMantissa =
3495 // -0.50419619f +
3496 // (0.60948995f - 0.10380950f * x) * x;
3497 //
3498 // error 0.0014886165, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003499 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003500 getF32Constant(DAG, 0xbdd49a13));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003501 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003502 getF32Constant(DAG, 0x3f1c0789));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003503 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3504 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003505 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003506
Scott Michelfdc40a02009-02-17 22:15:04 +00003507 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003508 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003509 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3510 // For floating-point precision of 12:
3511 //
3512 // Log10ofMantissa =
3513 // -0.64831180f +
3514 // (0.91751397f +
3515 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3516 //
3517 // error 0.00019228036, which is better than 12 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003518 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003519 getF32Constant(DAG, 0x3d431f31));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003520 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003521 getF32Constant(DAG, 0x3ea21fb2));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003522 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3523 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003524 getF32Constant(DAG, 0x3f6ae232));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003525 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3526 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003527 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00003528
Scott Michelfdc40a02009-02-17 22:15:04 +00003529 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003530 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003531 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003532 // For floating-point precision of 18:
3533 //
3534 // Log10ofMantissa =
3535 // -0.84299375f +
3536 // (1.5327582f +
3537 // (-1.0688956f +
3538 // (0.49102474f +
3539 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3540 //
3541 // error 0.0000037995730, which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003542 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003543 getF32Constant(DAG, 0x3c5d51ce));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003544 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003545 getF32Constant(DAG, 0x3e00685a));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003546 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3547 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003548 getF32Constant(DAG, 0x3efb6798));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003549 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3550 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003551 getF32Constant(DAG, 0x3f88d192));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003552 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3553 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003554 getF32Constant(DAG, 0x3fc4316c));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003555 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3556 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003557 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +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 }
Dale Johannesen852680a2008-09-05 21:27:19 +00003562 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003563 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003564 result = DAG.getNode(ISD::FLOG10, dl,
Dale Johannesen852680a2008-09-05 21:27:19 +00003565 getValue(I.getOperand(1)).getValueType(),
3566 getValue(I.getOperand(1)));
3567 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003568
Dale Johannesen59e577f2008-09-05 18:38:42 +00003569 setValue(&I, result);
3570}
3571
Bill Wendlinge10c8142008-09-09 22:39:21 +00003572/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3573/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003574void
3575SelectionDAGLowering::visitExp2(CallInst &I) {
3576 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003577 DebugLoc dl = getCurDebugLoc();
Bill Wendlinge10c8142008-09-09 22:39:21 +00003578
Dale Johannesen601d3c02008-09-05 01:48:15 +00003579 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00003580 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3581 SDValue Op = getValue(I.getOperand(1));
3582
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003583 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003584
3585 // FractionalPartOfX = x - (float)IntegerPartOfX;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003586 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3587 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003588
3589 // IntegerPartOfX <<= 23;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003590 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003591 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003592
3593 if (LimitFloatPrecision <= 6) {
3594 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003595 //
Bill Wendlinge10c8142008-09-09 22:39:21 +00003596 // TwoToFractionalPartOfX =
3597 // 0.997535578f +
3598 // (0.735607626f + 0.252464424f * x) * x;
3599 //
3600 // error 0.0144103317, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003601 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003602 getF32Constant(DAG, 0x3e814304));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003603 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003604 getF32Constant(DAG, 0x3f3c50c8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003605 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3606 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003607 getF32Constant(DAG, 0x3f7f5e7e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003608 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003609 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003610 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003611
Scott Michelfdc40a02009-02-17 22:15:04 +00003612 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003613 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003614 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3615 // For floating-point precision of 12:
3616 //
3617 // TwoToFractionalPartOfX =
3618 // 0.999892986f +
3619 // (0.696457318f +
3620 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3621 //
3622 // error 0.000107046256, which is 13 to 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003623 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003624 getF32Constant(DAG, 0x3da235e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003625 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003626 getF32Constant(DAG, 0x3e65b8f3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003627 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3628 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003629 getF32Constant(DAG, 0x3f324b07));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003630 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3631 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003632 getF32Constant(DAG, 0x3f7ff8fd));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003633 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003634 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003635 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003636
Scott Michelfdc40a02009-02-17 22:15:04 +00003637 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003638 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003639 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3640 // For floating-point precision of 18:
3641 //
3642 // TwoToFractionalPartOfX =
3643 // 0.999999982f +
3644 // (0.693148872f +
3645 // (0.240227044f +
3646 // (0.554906021e-1f +
3647 // (0.961591928e-2f +
3648 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3649 // error 2.47208000*10^(-7), which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003650 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003651 getF32Constant(DAG, 0x3924b03e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003652 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003653 getF32Constant(DAG, 0x3ab24b87));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003654 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3655 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003656 getF32Constant(DAG, 0x3c1d8c17));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003657 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3658 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003659 getF32Constant(DAG, 0x3d634a1d));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003660 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3661 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003662 getF32Constant(DAG, 0x3e75fe14));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003663 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3664 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003665 getF32Constant(DAG, 0x3f317234));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003666 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3667 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003668 getF32Constant(DAG, 0x3f800000));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003669 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003670 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003671 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003672
Scott Michelfdc40a02009-02-17 22:15:04 +00003673 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003674 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003675 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00003676 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003677 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003678 result = DAG.getNode(ISD::FEXP2, dl,
Dale Johannesen601d3c02008-09-05 01:48:15 +00003679 getValue(I.getOperand(1)).getValueType(),
3680 getValue(I.getOperand(1)));
3681 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00003682
Dale Johannesen601d3c02008-09-05 01:48:15 +00003683 setValue(&I, result);
3684}
3685
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003686/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3687/// limited-precision mode with x == 10.0f.
3688void
3689SelectionDAGLowering::visitPow(CallInst &I) {
3690 SDValue result;
3691 Value *Val = I.getOperand(1);
Dale Johannesen66978ee2009-01-31 02:22:37 +00003692 DebugLoc dl = getCurDebugLoc();
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003693 bool IsExp10 = false;
3694
3695 if (getValue(Val).getValueType() == MVT::f32 &&
Bill Wendling277fc242008-09-10 00:24:59 +00003696 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003697 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3698 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3699 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3700 APFloat Ten(10.0f);
3701 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3702 }
3703 }
3704 }
3705
3706 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3707 SDValue Op = getValue(I.getOperand(2));
3708
3709 // Put the exponent in the right bit position for later addition to the
3710 // final result:
3711 //
3712 // #define LOG2OF10 3.3219281f
3713 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003714 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003715 getF32Constant(DAG, 0x40549a78));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003716 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003717
3718 // FractionalPartOfX = x - (float)IntegerPartOfX;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003719 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3720 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003721
3722 // IntegerPartOfX <<= 23;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003723 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003724 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003725
3726 if (LimitFloatPrecision <= 6) {
3727 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003728 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003729 // twoToFractionalPartOfX =
3730 // 0.997535578f +
3731 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003732 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003733 // error 0.0144103317, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003734 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003735 getF32Constant(DAG, 0x3e814304));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003736 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003737 getF32Constant(DAG, 0x3f3c50c8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003738 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3739 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003740 getF32Constant(DAG, 0x3f7f5e7e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003741 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003742 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003743 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003744
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003745 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3746 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003747 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3748 // For floating-point precision of 12:
3749 //
3750 // TwoToFractionalPartOfX =
3751 // 0.999892986f +
3752 // (0.696457318f +
3753 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3754 //
3755 // error 0.000107046256, which is 13 to 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003756 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003757 getF32Constant(DAG, 0x3da235e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003758 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003759 getF32Constant(DAG, 0x3e65b8f3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003760 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3761 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003762 getF32Constant(DAG, 0x3f324b07));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003763 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3764 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003765 getF32Constant(DAG, 0x3f7ff8fd));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003766 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003767 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003768 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003769
Scott Michelfdc40a02009-02-17 22:15:04 +00003770 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003771 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003772 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3773 // For floating-point precision of 18:
3774 //
3775 // TwoToFractionalPartOfX =
3776 // 0.999999982f +
3777 // (0.693148872f +
3778 // (0.240227044f +
3779 // (0.554906021e-1f +
3780 // (0.961591928e-2f +
3781 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3782 // error 2.47208000*10^(-7), which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003783 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003784 getF32Constant(DAG, 0x3924b03e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003785 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003786 getF32Constant(DAG, 0x3ab24b87));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003787 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3788 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003789 getF32Constant(DAG, 0x3c1d8c17));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003790 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3791 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003792 getF32Constant(DAG, 0x3d634a1d));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003793 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3794 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003795 getF32Constant(DAG, 0x3e75fe14));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003796 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3797 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003798 getF32Constant(DAG, 0x3f317234));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003799 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3800 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003801 getF32Constant(DAG, 0x3f800000));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003802 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003803 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003804 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003805
Scott Michelfdc40a02009-02-17 22:15:04 +00003806 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003807 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003808 }
3809 } else {
3810 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003811 result = DAG.getNode(ISD::FPOW, dl,
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003812 getValue(I.getOperand(1)).getValueType(),
3813 getValue(I.getOperand(1)),
3814 getValue(I.getOperand(2)));
3815 }
3816
3817 setValue(&I, result);
3818}
3819
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003820/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3821/// we want to emit this as a call to a named external function, return the name
3822/// otherwise lower it and return null.
3823const char *
3824SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00003825 DebugLoc dl = getCurDebugLoc();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003826 switch (Intrinsic) {
3827 default:
3828 // By default, turn this into a target intrinsic node.
3829 visitTargetIntrinsic(I, Intrinsic);
3830 return 0;
3831 case Intrinsic::vastart: visitVAStart(I); return 0;
3832 case Intrinsic::vaend: visitVAEnd(I); return 0;
3833 case Intrinsic::vacopy: visitVACopy(I); return 0;
3834 case Intrinsic::returnaddress:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003835 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003836 getValue(I.getOperand(1))));
3837 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00003838 case Intrinsic::frameaddress:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003839 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003840 getValue(I.getOperand(1))));
3841 return 0;
3842 case Intrinsic::setjmp:
3843 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3844 break;
3845 case Intrinsic::longjmp:
3846 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3847 break;
Chris Lattner824b9582008-11-21 16:42:48 +00003848 case Intrinsic::memcpy: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003849 SDValue Op1 = getValue(I.getOperand(1));
3850 SDValue Op2 = getValue(I.getOperand(2));
3851 SDValue Op3 = getValue(I.getOperand(3));
3852 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Dale Johannesena04b7572009-02-03 23:04:43 +00003853 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003854 I.getOperand(1), 0, I.getOperand(2), 0));
3855 return 0;
3856 }
Chris Lattner824b9582008-11-21 16:42:48 +00003857 case Intrinsic::memset: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003858 SDValue Op1 = getValue(I.getOperand(1));
3859 SDValue Op2 = getValue(I.getOperand(2));
3860 SDValue Op3 = getValue(I.getOperand(3));
3861 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Dale Johannesena04b7572009-02-03 23:04:43 +00003862 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003863 I.getOperand(1), 0));
3864 return 0;
3865 }
Chris Lattner824b9582008-11-21 16:42:48 +00003866 case Intrinsic::memmove: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003867 SDValue Op1 = getValue(I.getOperand(1));
3868 SDValue Op2 = getValue(I.getOperand(2));
3869 SDValue Op3 = getValue(I.getOperand(3));
3870 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3871
3872 // If the source and destination are known to not be aliases, we can
3873 // lower memmove as memcpy.
3874 uint64_t Size = -1ULL;
3875 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003876 Size = C->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003877 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3878 AliasAnalysis::NoAlias) {
Dale Johannesena04b7572009-02-03 23:04:43 +00003879 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003880 I.getOperand(1), 0, I.getOperand(2), 0));
3881 return 0;
3882 }
3883
Dale Johannesena04b7572009-02-03 23:04:43 +00003884 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003885 I.getOperand(1), 0, I.getOperand(2), 0));
3886 return 0;
3887 }
3888 case Intrinsic::dbg_stoppoint: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003889 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00003890 if (DIDescriptor::ValidDebugInfo(SPI.getContext(), OptLevel)) {
Evan Chenge3d42322009-02-25 07:04:34 +00003891 MachineFunction &MF = DAG.getMachineFunction();
Chris Lattneraf29a522009-05-04 22:10:05 +00003892 DICompileUnit CU(cast<GlobalVariable>(SPI.getContext()));
3893 DebugLoc Loc = DebugLoc::get(MF.getOrCreateDebugLocID(CU.getGV(),
Bill Wendlingdf7d5d32009-05-21 00:04:55 +00003894 SPI.getLine(), SPI.getColumn()));
Chris Lattneraf29a522009-05-04 22:10:05 +00003895 setCurDebugLoc(Loc);
3896
Bill Wendling98a366d2009-04-29 23:29:43 +00003897 if (OptLevel == CodeGenOpt::None)
Chris Lattneraf29a522009-05-04 22:10:05 +00003898 DAG.setRoot(DAG.getDbgStopPoint(Loc, getRoot(),
Dale Johannesenbeaec4c2009-03-25 17:36:08 +00003899 SPI.getLine(),
3900 SPI.getColumn(),
3901 SPI.getContext()));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003902 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003903 return 0;
3904 }
3905 case Intrinsic::dbg_region_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003906 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003907 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +00003908
Bill Wendlingdf7d5d32009-05-21 00:04:55 +00003909 if (DIDescriptor::ValidDebugInfo(RSI.getContext(), OptLevel) &&
3910 DW && DW->ShouldEmitDwarfDebug()) {
3911 unsigned LabelID =
3912 DW->RecordRegionStart(cast<GlobalVariable>(RSI.getContext()));
Devang Patel48c7fa22009-04-13 18:13:16 +00003913 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3914 getRoot(), LabelID));
Bill Wendling92c1e122009-02-13 02:16:35 +00003915 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003916
3917 return 0;
3918 }
3919 case Intrinsic::dbg_region_end: {
Devang Patel83489bb2009-01-13 00:35:13 +00003920 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003921 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Devang Patel0f7fef32009-04-13 17:02:03 +00003922
Bill Wendlingdf7d5d32009-05-21 00:04:55 +00003923 if (DIDescriptor::ValidDebugInfo(REI.getContext(), OptLevel) &&
3924 DW && DW->ShouldEmitDwarfDebug()) {
3925 MachineFunction &MF = DAG.getMachineFunction();
3926 DISubprogram Subprogram(cast<GlobalVariable>(REI.getContext()));
Bill Wendling6c4311d2009-05-08 21:14:49 +00003927
Bill Wendling805da892009-05-18 18:21:03 +00003928 if (Subprogram.isNull() || Subprogram.describes(MF.getFunction())) {
Bill Wendling6c4311d2009-05-08 21:14:49 +00003929 unsigned LabelID =
3930 DW->RecordRegionEnd(cast<GlobalVariable>(REI.getContext()));
3931 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3932 getRoot(), LabelID));
3933 } else {
3934 // This is end of inlined function. Debugging information for inlined
3935 // function is not handled yet (only supported by FastISel).
Bill Wendling98a366d2009-04-29 23:29:43 +00003936 if (OptLevel == CodeGenOpt::None) {
Devang Patel16f2ffd2009-04-16 02:33:41 +00003937 unsigned ID = DW->RecordInlinedFnEnd(Subprogram);
3938 if (ID != 0)
Devang Patel02f8c412009-04-16 17:55:30 +00003939 // Returned ID is 0 if this is unbalanced "end of inlined
Bill Wendling6c4311d2009-05-08 21:14:49 +00003940 // scope". This could happen if optimizer eats dbg intrinsics or
3941 // "beginning of inlined scope" is not recoginized due to missing
3942 // location info. In such cases, do ignore this region.end.
Devang Patel16f2ffd2009-04-16 02:33:41 +00003943 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3944 getRoot(), ID));
3945 }
Devang Patel0f7fef32009-04-13 17:02:03 +00003946 }
Bill Wendling92c1e122009-02-13 02:16:35 +00003947 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003948
3949 return 0;
3950 }
3951 case Intrinsic::dbg_func_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003952 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003953 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3954 Value *SP = FSI.getSubprogram();
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00003955 if (!DIDescriptor::ValidDebugInfo(SP, OptLevel))
3956 return 0;
Devang Patel16f2ffd2009-04-16 02:33:41 +00003957
Devang Patelceddbe82009-07-01 23:19:01 +00003958 DISubprogram Subprogram(cast<GlobalVariable>(SP));
3959 DICompileUnit CompileUnit = Subprogram.getCompileUnit();
3960 unsigned Line = Subprogram.getLineNumber();
3961
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00003962 MachineFunction &MF = DAG.getMachineFunction();
Devang Patel07b0ec02009-07-02 00:08:09 +00003963 // If this subprogram does not describe current function then this is
3964 // beginning of a inlined function.
3965
3966 bool isInlinedFnStart = !Subprogram.describes(MF.getFunction());
3967 if (isInlinedFnStart && OptLevel != CodeGenOpt::None)
3968 // FIXME: Debugging informaation for inlined function is only
3969 // supported at CodeGenOpt::Node.
3970 return 0;
3971
3972 if (isInlinedFnStart && OptLevel == CodeGenOpt::None) {
3973 // This is a beginning of an inlined function.
Bill Wendlingc677fe52009-05-10 00:10:50 +00003974 DebugLoc PrevLoc = CurDebugLoc;
Devang Patel07b0ec02009-07-02 00:08:09 +00003975 // If llvm.dbg.func.start is seen in a new block before any
3976 // llvm.dbg.stoppoint intrinsic then the location info is unknown.
3977 // FIXME : Why DebugLoc is reset at the beginning of each block ?
3978 if (PrevLoc.isUnknown())
3979 return 0;
Devang Patel02f8c412009-04-16 17:55:30 +00003980
Devang Patel07b0ec02009-07-02 00:08:09 +00003981 // Record the source line.
3982 unsigned LocID = MF.getOrCreateDebugLocID(CompileUnit.getGV(), Line, 0);
3983 setCurDebugLoc(DebugLoc::get(LocID));
3984
3985 if (DW && DW->ShouldEmitDwarfDebug()) {
3986 DebugLocTuple PrevLocTpl = MF.getDebugLocTuple(PrevLoc);
3987 unsigned LabelID = DW->RecordInlinedFnStart(Subprogram,
3988 DICompileUnit(PrevLocTpl.CompileUnit),
3989 PrevLocTpl.Line,
3990 PrevLocTpl.Col);
Bill Wendlingc677fe52009-05-10 00:10:50 +00003991 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3992 getRoot(), LabelID));
Bill Wendlingc677fe52009-05-10 00:10:50 +00003993 }
Devang Patel07b0ec02009-07-02 00:08:09 +00003994 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003995 }
3996
Devang Patel07b0ec02009-07-02 00:08:09 +00003997 // This is a beginning of a new function.
3998 // Record the source line.
3999 unsigned LocID = MF.getOrCreateDebugLocID(CompileUnit.getGV(), Line, 0);
4000 MF.setDefaultDebugLoc(DebugLoc::get(LocID));
4001
4002 if (DW && DW->ShouldEmitDwarfDebug())
4003 // llvm.dbg.func_start also defines beginning of function scope.
4004 DW->RecordRegionStart(cast<GlobalVariable>(FSI.getSubprogram()));
4005
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004006 return 0;
4007 }
Bill Wendling92c1e122009-02-13 02:16:35 +00004008 case Intrinsic::dbg_declare: {
Bill Wendling98a366d2009-04-29 23:29:43 +00004009 if (OptLevel == CodeGenOpt::None) {
Bill Wendling86e6cb92009-02-17 01:04:54 +00004010 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4011 Value *Variable = DI.getVariable();
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00004012 if (DIDescriptor::ValidDebugInfo(Variable, OptLevel))
Bill Wendling86e6cb92009-02-17 01:04:54 +00004013 DAG.setRoot(DAG.getNode(ISD::DECLARE, dl, MVT::Other, getRoot(),
4014 getValue(DI.getAddress()), getValue(Variable)));
4015 } else {
4016 // FIXME: Do something sensible here when we support debug declare.
4017 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004018 return 0;
Bill Wendling92c1e122009-02-13 02:16:35 +00004019 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004020 case Intrinsic::eh_exception: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004021 // Insert the EXCEPTIONADDR instruction.
Duncan Sandsb0f1e172009-05-22 20:36:31 +00004022 assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004023 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4024 SDValue Ops[1];
4025 Ops[0] = DAG.getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004026 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004027 setValue(&I, Op);
4028 DAG.setRoot(Op.getValue(1));
4029 return 0;
4030 }
4031
4032 case Intrinsic::eh_selector_i32:
4033 case Intrinsic::eh_selector_i64: {
4034 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4035 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
4036 MVT::i32 : MVT::i64);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004037
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004038 if (MMI) {
4039 if (CurMBB->isLandingPad())
4040 AddCatchInfo(I, MMI, CurMBB);
4041 else {
4042#ifndef NDEBUG
4043 FuncInfo.CatchInfoLost.insert(&I);
4044#endif
4045 // FIXME: Mark exception selector register as live in. Hack for PR1508.
4046 unsigned Reg = TLI.getExceptionSelectorRegister();
4047 if (Reg) CurMBB->addLiveIn(Reg);
4048 }
4049
4050 // Insert the EHSELECTION instruction.
4051 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
4052 SDValue Ops[2];
4053 Ops[0] = getValue(I.getOperand(1));
4054 Ops[1] = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004055 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004056 setValue(&I, Op);
4057 DAG.setRoot(Op.getValue(1));
4058 } else {
4059 setValue(&I, DAG.getConstant(0, VT));
4060 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004061
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004062 return 0;
4063 }
4064
4065 case Intrinsic::eh_typeid_for_i32:
4066 case Intrinsic::eh_typeid_for_i64: {
4067 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4068 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
4069 MVT::i32 : MVT::i64);
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004070
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004071 if (MMI) {
4072 // Find the type id for the given typeinfo.
4073 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
4074
4075 unsigned TypeID = MMI->getTypeIDFor(GV);
4076 setValue(&I, DAG.getConstant(TypeID, VT));
4077 } else {
4078 // Return something different to eh_selector.
4079 setValue(&I, DAG.getConstant(1, VT));
4080 }
4081
4082 return 0;
4083 }
4084
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004085 case Intrinsic::eh_return_i32:
4086 case Intrinsic::eh_return_i64:
4087 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004088 MMI->setCallsEHReturn(true);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004089 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004090 MVT::Other,
4091 getControlRoot(),
4092 getValue(I.getOperand(1)),
4093 getValue(I.getOperand(2))));
4094 } else {
4095 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
4096 }
4097
4098 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004099 case Intrinsic::eh_unwind_init:
4100 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4101 MMI->setCallsUnwindInit(true);
4102 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004103
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004104 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004105
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004106 case Intrinsic::eh_dwarf_cfa: {
4107 MVT VT = getValue(I.getOperand(1)).getValueType();
4108 SDValue CfaArg;
4109 if (VT.bitsGT(TLI.getPointerTy()))
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004110 CfaArg = DAG.getNode(ISD::TRUNCATE, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004111 TLI.getPointerTy(), getValue(I.getOperand(1)));
4112 else
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004113 CfaArg = DAG.getNode(ISD::SIGN_EXTEND, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004114 TLI.getPointerTy(), getValue(I.getOperand(1)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004115
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004116 SDValue Offset = DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004117 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004118 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004119 TLI.getPointerTy()),
4120 CfaArg);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004121 setValue(&I, DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004122 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004123 DAG.getNode(ISD::FRAMEADDR, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004124 TLI.getPointerTy(),
4125 DAG.getConstant(0,
4126 TLI.getPointerTy())),
4127 Offset));
4128 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004129 }
4130
Mon P Wang77cdf302008-11-10 20:54:11 +00004131 case Intrinsic::convertff:
4132 case Intrinsic::convertfsi:
4133 case Intrinsic::convertfui:
4134 case Intrinsic::convertsif:
4135 case Intrinsic::convertuif:
4136 case Intrinsic::convertss:
4137 case Intrinsic::convertsu:
4138 case Intrinsic::convertus:
4139 case Intrinsic::convertuu: {
4140 ISD::CvtCode Code = ISD::CVT_INVALID;
4141 switch (Intrinsic) {
4142 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4143 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4144 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4145 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4146 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4147 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4148 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4149 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4150 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4151 }
4152 MVT DestVT = TLI.getValueType(I.getType());
4153 Value* Op1 = I.getOperand(1);
Dale Johannesena04b7572009-02-03 23:04:43 +00004154 setValue(&I, DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
Mon P Wang77cdf302008-11-10 20:54:11 +00004155 DAG.getValueType(DestVT),
4156 DAG.getValueType(getValue(Op1).getValueType()),
4157 getValue(I.getOperand(2)),
4158 getValue(I.getOperand(3)),
4159 Code));
4160 return 0;
4161 }
4162
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004163 case Intrinsic::sqrt:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004164 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004165 getValue(I.getOperand(1)).getValueType(),
4166 getValue(I.getOperand(1))));
4167 return 0;
4168 case Intrinsic::powi:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004169 setValue(&I, DAG.getNode(ISD::FPOWI, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004170 getValue(I.getOperand(1)).getValueType(),
4171 getValue(I.getOperand(1)),
4172 getValue(I.getOperand(2))));
4173 return 0;
4174 case Intrinsic::sin:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004175 setValue(&I, DAG.getNode(ISD::FSIN, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004176 getValue(I.getOperand(1)).getValueType(),
4177 getValue(I.getOperand(1))));
4178 return 0;
4179 case Intrinsic::cos:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004180 setValue(&I, DAG.getNode(ISD::FCOS, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004181 getValue(I.getOperand(1)).getValueType(),
4182 getValue(I.getOperand(1))));
4183 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004184 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004185 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004186 return 0;
4187 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004188 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004189 return 0;
4190 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004191 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004192 return 0;
4193 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004194 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004195 return 0;
4196 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00004197 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004198 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004199 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004200 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004201 return 0;
4202 case Intrinsic::pcmarker: {
4203 SDValue Tmp = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004204 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004205 return 0;
4206 }
4207 case Intrinsic::readcyclecounter: {
4208 SDValue Op = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004209 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER, dl,
Dan Gohmanfc166572009-04-09 23:54:40 +00004210 DAG.getVTList(MVT::i64, MVT::Other),
4211 &Op, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004212 setValue(&I, Tmp);
4213 DAG.setRoot(Tmp.getValue(1));
4214 return 0;
4215 }
4216 case Intrinsic::part_select: {
4217 // Currently not implemented: just abort
4218 assert(0 && "part_select intrinsic not implemented");
4219 abort();
4220 }
4221 case Intrinsic::part_set: {
4222 // Currently not implemented: just abort
4223 assert(0 && "part_set intrinsic not implemented");
4224 abort();
4225 }
4226 case Intrinsic::bswap:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004227 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004228 getValue(I.getOperand(1)).getValueType(),
4229 getValue(I.getOperand(1))));
4230 return 0;
4231 case Intrinsic::cttz: {
4232 SDValue Arg = getValue(I.getOperand(1));
4233 MVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004234 SDValue result = DAG.getNode(ISD::CTTZ, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004235 setValue(&I, result);
4236 return 0;
4237 }
4238 case Intrinsic::ctlz: {
4239 SDValue Arg = getValue(I.getOperand(1));
4240 MVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004241 SDValue result = DAG.getNode(ISD::CTLZ, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004242 setValue(&I, result);
4243 return 0;
4244 }
4245 case Intrinsic::ctpop: {
4246 SDValue Arg = getValue(I.getOperand(1));
4247 MVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004248 SDValue result = DAG.getNode(ISD::CTPOP, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004249 setValue(&I, result);
4250 return 0;
4251 }
4252 case Intrinsic::stacksave: {
4253 SDValue Op = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004254 SDValue Tmp = DAG.getNode(ISD::STACKSAVE, dl,
Dan Gohmanfc166572009-04-09 23:54:40 +00004255 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004256 setValue(&I, Tmp);
4257 DAG.setRoot(Tmp.getValue(1));
4258 return 0;
4259 }
4260 case Intrinsic::stackrestore: {
4261 SDValue Tmp = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004262 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004263 return 0;
4264 }
Bill Wendling57344502008-11-18 11:01:33 +00004265 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00004266 // Emit code into the DAG to store the stack guard onto the stack.
4267 MachineFunction &MF = DAG.getMachineFunction();
4268 MachineFrameInfo *MFI = MF.getFrameInfo();
4269 MVT PtrTy = TLI.getPointerTy();
4270
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004271 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4272 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
Bill Wendlingb2a42982008-11-06 02:29:10 +00004273
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004274 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00004275 MFI->setStackProtectorIndex(FI);
4276
4277 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4278
4279 // Store the stack protector onto the stack.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004280 SDValue Result = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
Bill Wendlingb2a42982008-11-06 02:29:10 +00004281 PseudoSourceValue::getFixedStack(FI),
4282 0, true);
4283 setValue(&I, Result);
4284 DAG.setRoot(Result);
4285 return 0;
4286 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004287 case Intrinsic::var_annotation:
4288 // Discard annotate attributes
4289 return 0;
4290
4291 case Intrinsic::init_trampoline: {
4292 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4293
4294 SDValue Ops[6];
4295 Ops[0] = getRoot();
4296 Ops[1] = getValue(I.getOperand(1));
4297 Ops[2] = getValue(I.getOperand(2));
4298 Ops[3] = getValue(I.getOperand(3));
4299 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4300 Ops[5] = DAG.getSrcValue(F);
4301
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004302 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE, dl,
Dan Gohmanfc166572009-04-09 23:54:40 +00004303 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4304 Ops, 6);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004305
4306 setValue(&I, Tmp);
4307 DAG.setRoot(Tmp.getValue(1));
4308 return 0;
4309 }
4310
4311 case Intrinsic::gcroot:
4312 if (GFI) {
4313 Value *Alloca = I.getOperand(1);
4314 Constant *TypeMap = cast<Constant>(I.getOperand(2));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004315
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004316 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4317 GFI->addStackRoot(FI->getIndex(), TypeMap);
4318 }
4319 return 0;
4320
4321 case Intrinsic::gcread:
4322 case Intrinsic::gcwrite:
4323 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
4324 return 0;
4325
4326 case Intrinsic::flt_rounds: {
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004327 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004328 return 0;
4329 }
4330
4331 case Intrinsic::trap: {
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004332 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004333 return 0;
4334 }
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004335
Bill Wendlingef375462008-11-21 02:38:44 +00004336 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00004337 return implVisitAluOverflow(I, ISD::UADDO);
4338 case Intrinsic::sadd_with_overflow:
4339 return implVisitAluOverflow(I, ISD::SADDO);
4340 case Intrinsic::usub_with_overflow:
4341 return implVisitAluOverflow(I, ISD::USUBO);
4342 case Intrinsic::ssub_with_overflow:
4343 return implVisitAluOverflow(I, ISD::SSUBO);
4344 case Intrinsic::umul_with_overflow:
4345 return implVisitAluOverflow(I, ISD::UMULO);
4346 case Intrinsic::smul_with_overflow:
4347 return implVisitAluOverflow(I, ISD::SMULO);
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004348
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004349 case Intrinsic::prefetch: {
4350 SDValue Ops[4];
4351 Ops[0] = getRoot();
4352 Ops[1] = getValue(I.getOperand(1));
4353 Ops[2] = getValue(I.getOperand(2));
4354 Ops[3] = getValue(I.getOperand(3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004355 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004356 return 0;
4357 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004358
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004359 case Intrinsic::memory_barrier: {
4360 SDValue Ops[6];
4361 Ops[0] = getRoot();
4362 for (int x = 1; x < 6; ++x)
4363 Ops[x] = getValue(I.getOperand(x));
4364
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004365 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004366 return 0;
4367 }
4368 case Intrinsic::atomic_cmp_swap: {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004369 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004370 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00004371 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004372 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4373 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004374 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004375 getValue(I.getOperand(2)),
4376 getValue(I.getOperand(3)),
4377 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004378 setValue(&I, L);
4379 DAG.setRoot(L.getValue(1));
4380 return 0;
4381 }
4382 case Intrinsic::atomic_load_add:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004383 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004384 case Intrinsic::atomic_load_sub:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004385 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004386 case Intrinsic::atomic_load_or:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004387 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004388 case Intrinsic::atomic_load_xor:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004389 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004390 case Intrinsic::atomic_load_and:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004391 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004392 case Intrinsic::atomic_load_nand:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004393 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004394 case Intrinsic::atomic_load_max:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004395 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004396 case Intrinsic::atomic_load_min:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004397 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004398 case Intrinsic::atomic_load_umin:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004399 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004400 case Intrinsic::atomic_load_umax:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004401 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004402 case Intrinsic::atomic_swap:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004403 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004404 }
4405}
4406
4407
4408void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4409 bool IsTailCall,
4410 MachineBasicBlock *LandingPad) {
4411 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4412 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4413 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4414 unsigned BeginLabel = 0, EndLabel = 0;
4415
4416 TargetLowering::ArgListTy Args;
4417 TargetLowering::ArgListEntry Entry;
4418 Args.reserve(CS.arg_size());
4419 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4420 i != e; ++i) {
4421 SDValue ArgNode = getValue(*i);
4422 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4423
4424 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00004425 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4426 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4427 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4428 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4429 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4430 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004431 Entry.Alignment = CS.getParamAlignment(attrInd);
4432 Args.push_back(Entry);
4433 }
4434
4435 if (LandingPad && MMI) {
4436 // Insert a label before the invoke call to mark the try range. This can be
4437 // used to detect deletion of the invoke via the MachineModuleInfo.
4438 BeginLabel = MMI->NextLabelID();
4439 // Both PendingLoads and PendingExports must be flushed here;
4440 // this call might not return.
4441 (void)getRoot();
Dale Johannesen8ad9b432009-02-04 01:17:06 +00004442 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4443 getControlRoot(), BeginLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004444 }
4445
4446 std::pair<SDValue,SDValue> Result =
4447 TLI.LowerCallTo(getRoot(), CS.getType(),
Devang Patel05988662008-09-25 21:00:45 +00004448 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004449 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4450 CS.paramHasAttr(0, Attribute::InReg),
4451 CS.getCallingConv(),
Dan Gohman1937e2f2008-09-16 01:42:28 +00004452 IsTailCall && PerformTailCallOpt,
Dale Johannesen66978ee2009-01-31 02:22:37 +00004453 Callee, Args, DAG, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004454 if (CS.getType() != Type::VoidTy)
4455 setValue(CS.getInstruction(), Result.first);
4456 DAG.setRoot(Result.second);
4457
4458 if (LandingPad && MMI) {
4459 // Insert a label at the end of the invoke call to mark the try range. This
4460 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4461 EndLabel = MMI->NextLabelID();
Dale Johannesen8ad9b432009-02-04 01:17:06 +00004462 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4463 getRoot(), EndLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004464
4465 // Inform MachineModuleInfo of range.
4466 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4467 }
4468}
4469
4470
4471void SelectionDAGLowering::visitCall(CallInst &I) {
4472 const char *RenameFn = 0;
4473 if (Function *F = I.getCalledFunction()) {
4474 if (F->isDeclaration()) {
Dale Johannesen49de9822009-02-05 01:49:45 +00004475 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4476 if (II) {
4477 if (unsigned IID = II->getIntrinsicID(F)) {
4478 RenameFn = visitIntrinsicCall(I, IID);
4479 if (!RenameFn)
4480 return;
4481 }
4482 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004483 if (unsigned IID = F->getIntrinsicID()) {
4484 RenameFn = visitIntrinsicCall(I, IID);
4485 if (!RenameFn)
4486 return;
4487 }
4488 }
4489
4490 // Check for well-known libc/libm calls. If the function is internal, it
4491 // can't be a library call.
4492 unsigned NameLen = F->getNameLen();
Rafael Espindolabb46f522009-01-15 20:18:42 +00004493 if (!F->hasLocalLinkage() && NameLen) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004494 const char *NameStr = F->getNameStart();
4495 if (NameStr[0] == 'c' &&
4496 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4497 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4498 if (I.getNumOperands() == 3 && // Basic sanity checks.
4499 I.getOperand(1)->getType()->isFloatingPoint() &&
4500 I.getType() == I.getOperand(1)->getType() &&
4501 I.getType() == I.getOperand(2)->getType()) {
4502 SDValue LHS = getValue(I.getOperand(1));
4503 SDValue RHS = getValue(I.getOperand(2));
Scott Michelfdc40a02009-02-17 22:15:04 +00004504 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004505 LHS.getValueType(), LHS, RHS));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004506 return;
4507 }
4508 } else if (NameStr[0] == 'f' &&
4509 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4510 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4511 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4512 if (I.getNumOperands() == 2 && // Basic sanity checks.
4513 I.getOperand(1)->getType()->isFloatingPoint() &&
4514 I.getType() == I.getOperand(1)->getType()) {
4515 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004516 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004517 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004518 return;
4519 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004520 } else if (NameStr[0] == 's' &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004521 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4522 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4523 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4524 if (I.getNumOperands() == 2 && // Basic sanity checks.
4525 I.getOperand(1)->getType()->isFloatingPoint() &&
4526 I.getType() == I.getOperand(1)->getType()) {
4527 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004528 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004529 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004530 return;
4531 }
4532 } else if (NameStr[0] == 'c' &&
4533 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4534 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4535 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4536 if (I.getNumOperands() == 2 && // Basic sanity checks.
4537 I.getOperand(1)->getType()->isFloatingPoint() &&
4538 I.getType() == I.getOperand(1)->getType()) {
4539 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004540 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004541 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004542 return;
4543 }
4544 }
4545 }
4546 } else if (isa<InlineAsm>(I.getOperand(0))) {
4547 visitInlineAsm(&I);
4548 return;
4549 }
4550
4551 SDValue Callee;
4552 if (!RenameFn)
4553 Callee = getValue(I.getOperand(0));
4554 else
Bill Wendling056292f2008-09-16 21:48:12 +00004555 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004556
4557 LowerCallTo(&I, Callee, I.isTailCall());
4558}
4559
4560
4561/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004562/// this value and returns the result as a ValueVT value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004563/// Chain/Flag as the input and updates them for the output Chain/Flag.
4564/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004565SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004566 SDValue &Chain,
4567 SDValue *Flag) const {
4568 // Assemble the legal parts into the final values.
4569 SmallVector<SDValue, 4> Values(ValueVTs.size());
4570 SmallVector<SDValue, 8> Parts;
4571 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4572 // Copy the legal parts from the registers.
4573 MVT ValueVT = ValueVTs[Value];
4574 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4575 MVT RegisterVT = RegVTs[Value];
4576
4577 Parts.resize(NumRegs);
4578 for (unsigned i = 0; i != NumRegs; ++i) {
4579 SDValue P;
4580 if (Flag == 0)
Dale Johannesena04b7572009-02-03 23:04:43 +00004581 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004582 else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004583 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004584 *Flag = P.getValue(2);
4585 }
4586 Chain = P.getValue(1);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004587
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004588 // If the source register was virtual and if we know something about it,
4589 // add an assert node.
4590 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4591 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4592 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4593 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4594 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4595 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004596
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004597 unsigned RegSize = RegisterVT.getSizeInBits();
4598 unsigned NumSignBits = LOI.NumSignBits;
4599 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004600
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004601 // FIXME: We capture more information than the dag can represent. For
4602 // now, just use the tightest assertzext/assertsext possible.
4603 bool isSExt = true;
4604 MVT FromVT(MVT::Other);
4605 if (NumSignBits == RegSize)
4606 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4607 else if (NumZeroBits >= RegSize-1)
4608 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4609 else if (NumSignBits > RegSize-8)
4610 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
Dan Gohman07c26ee2009-03-31 01:38:29 +00004611 else if (NumZeroBits >= RegSize-8)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004612 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4613 else if (NumSignBits > RegSize-16)
Bill Wendling181b6272008-10-19 20:34:04 +00004614 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
Dan Gohman07c26ee2009-03-31 01:38:29 +00004615 else if (NumZeroBits >= RegSize-16)
Bill Wendling181b6272008-10-19 20:34:04 +00004616 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004617 else if (NumSignBits > RegSize-32)
Bill Wendling181b6272008-10-19 20:34:04 +00004618 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
Dan Gohman07c26ee2009-03-31 01:38:29 +00004619 else if (NumZeroBits >= RegSize-32)
Bill Wendling181b6272008-10-19 20:34:04 +00004620 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004621
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004622 if (FromVT != MVT::Other) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00004623 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004624 RegisterVT, P, DAG.getValueType(FromVT));
4625
4626 }
4627 }
4628 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004629
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004630 Parts[i] = P;
4631 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004632
Scott Michelfdc40a02009-02-17 22:15:04 +00004633 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00004634 NumRegs, RegisterVT, ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004635 Part += NumRegs;
4636 Parts.clear();
4637 }
4638
Dale Johannesen66978ee2009-01-31 02:22:37 +00004639 return DAG.getNode(ISD::MERGE_VALUES, dl,
Duncan Sandsaaffa052008-12-01 11:41:29 +00004640 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4641 &Values[0], ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004642}
4643
4644/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004645/// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004646/// Chain/Flag as the input and updates them for the output Chain/Flag.
4647/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004648void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004649 SDValue &Chain, SDValue *Flag) const {
4650 // Get the list of the values's legal parts.
4651 unsigned NumRegs = Regs.size();
4652 SmallVector<SDValue, 8> Parts(NumRegs);
4653 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4654 MVT ValueVT = ValueVTs[Value];
4655 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4656 MVT RegisterVT = RegVTs[Value];
4657
Dale Johannesen66978ee2009-01-31 02:22:37 +00004658 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004659 &Parts[Part], NumParts, RegisterVT);
4660 Part += NumParts;
4661 }
4662
4663 // Copy the parts into the registers.
4664 SmallVector<SDValue, 8> Chains(NumRegs);
4665 for (unsigned i = 0; i != NumRegs; ++i) {
4666 SDValue Part;
4667 if (Flag == 0)
Dale Johannesena04b7572009-02-03 23:04:43 +00004668 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004669 else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004670 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004671 *Flag = Part.getValue(1);
4672 }
4673 Chains[i] = Part.getValue(0);
4674 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004675
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004676 if (NumRegs == 1 || Flag)
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004677 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004678 // flagged to it. That is the CopyToReg nodes and the user are considered
4679 // a single scheduling unit. If we create a TokenFactor and return it as
4680 // chain, then the TokenFactor is both a predecessor (operand) of the
4681 // user as well as a successor (the TF operands are flagged to the user).
4682 // c1, f1 = CopyToReg
4683 // c2, f2 = CopyToReg
4684 // c3 = TokenFactor c1, c2
4685 // ...
4686 // = op c3, ..., f2
4687 Chain = Chains[NumRegs-1];
4688 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00004689 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004690}
4691
4692/// AddInlineAsmOperands - Add this value to the specified inlineasm node
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004693/// operand list. This adds the code marker and includes the number of
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004694/// values added into it.
Evan Cheng697cbbf2009-03-20 18:03:34 +00004695void RegsForValue::AddInlineAsmOperands(unsigned Code,
4696 bool HasMatching,unsigned MatchingIdx,
4697 SelectionDAG &DAG,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004698 std::vector<SDValue> &Ops) const {
4699 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Evan Cheng697cbbf2009-03-20 18:03:34 +00004700 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
4701 unsigned Flag = Code | (Regs.size() << 3);
4702 if (HasMatching)
4703 Flag |= 0x80000000 | (MatchingIdx << 16);
4704 Ops.push_back(DAG.getTargetConstant(Flag, IntPtrTy));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004705 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4706 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4707 MVT RegisterVT = RegVTs[Value];
Chris Lattner58f15c42008-10-17 16:21:11 +00004708 for (unsigned i = 0; i != NumRegs; ++i) {
4709 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004710 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner58f15c42008-10-17 16:21:11 +00004711 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004712 }
4713}
4714
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004715/// isAllocatableRegister - If the specified register is safe to allocate,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004716/// i.e. it isn't a stack pointer or some other special register, return the
4717/// register class for the register. Otherwise, return null.
4718static const TargetRegisterClass *
4719isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4720 const TargetLowering &TLI,
4721 const TargetRegisterInfo *TRI) {
4722 MVT FoundVT = MVT::Other;
4723 const TargetRegisterClass *FoundRC = 0;
4724 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4725 E = TRI->regclass_end(); RCI != E; ++RCI) {
4726 MVT ThisVT = MVT::Other;
4727
4728 const TargetRegisterClass *RC = *RCI;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004729 // If none of the the value types for this register class are valid, we
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004730 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4731 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4732 I != E; ++I) {
4733 if (TLI.isTypeLegal(*I)) {
4734 // If we have already found this register in a different register class,
4735 // choose the one with the largest VT specified. For example, on
4736 // PowerPC, we favor f64 register classes over f32.
4737 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4738 ThisVT = *I;
4739 break;
4740 }
4741 }
4742 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004743
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004744 if (ThisVT == MVT::Other) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004745
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004746 // NOTE: This isn't ideal. In particular, this might allocate the
4747 // frame pointer in functions that need it (due to them not being taken
4748 // out of allocation, because a variable sized allocation hasn't been seen
4749 // yet). This is a slight code pessimization, but should still work.
4750 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4751 E = RC->allocation_order_end(MF); I != E; ++I)
4752 if (*I == Reg) {
4753 // We found a matching register class. Keep looking at others in case
4754 // we find one with larger registers that this physreg is also in.
4755 FoundRC = RC;
4756 FoundVT = ThisVT;
4757 break;
4758 }
4759 }
4760 return FoundRC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004761}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004762
4763
4764namespace llvm {
4765/// AsmOperandInfo - This contains information for each constraint that we are
4766/// lowering.
Cedric Venetaff9c272009-02-14 16:06:42 +00004767class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
Daniel Dunbarc0c3b9a2008-09-10 04:16:29 +00004768 public TargetLowering::AsmOperandInfo {
Cedric Venetaff9c272009-02-14 16:06:42 +00004769public:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004770 /// CallOperand - If this is the result output operand or a clobber
4771 /// this is null, otherwise it is the incoming operand to the CallInst.
4772 /// This gets modified as the asm is processed.
4773 SDValue CallOperand;
4774
4775 /// AssignedRegs - If this is a register or register class operand, this
4776 /// contains the set of register corresponding to the operand.
4777 RegsForValue AssignedRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004778
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004779 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4780 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4781 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004782
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004783 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4784 /// busy in OutputRegs/InputRegs.
4785 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004786 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004787 std::set<unsigned> &InputRegs,
4788 const TargetRegisterInfo &TRI) const {
4789 if (isOutReg) {
4790 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4791 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4792 }
4793 if (isInReg) {
4794 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4795 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4796 }
4797 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004798
Chris Lattner81249c92008-10-17 17:05:25 +00004799 /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4800 /// corresponds to. If there is no Value* for this operand, it returns
4801 /// MVT::Other.
4802 MVT getCallOperandValMVT(const TargetLowering &TLI,
4803 const TargetData *TD) const {
4804 if (CallOperandVal == 0) return MVT::Other;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004805
Chris Lattner81249c92008-10-17 17:05:25 +00004806 if (isa<BasicBlock>(CallOperandVal))
4807 return TLI.getPointerTy();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004808
Chris Lattner81249c92008-10-17 17:05:25 +00004809 const llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004810
Chris Lattner81249c92008-10-17 17:05:25 +00004811 // If this is an indirect operand, the operand is a pointer to the
4812 // accessed type.
4813 if (isIndirect)
4814 OpTy = cast<PointerType>(OpTy)->getElementType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004815
Chris Lattner81249c92008-10-17 17:05:25 +00004816 // If OpTy is not a single value, it may be a struct/union that we
4817 // can tile with integers.
4818 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4819 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4820 switch (BitSize) {
4821 default: break;
4822 case 1:
4823 case 8:
4824 case 16:
4825 case 32:
4826 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00004827 case 128:
Chris Lattner81249c92008-10-17 17:05:25 +00004828 OpTy = IntegerType::get(BitSize);
4829 break;
4830 }
4831 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004832
Chris Lattner81249c92008-10-17 17:05:25 +00004833 return TLI.getValueType(OpTy, true);
4834 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004835
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004836private:
4837 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4838 /// specified set.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004839 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004840 const TargetRegisterInfo &TRI) {
4841 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4842 Regs.insert(Reg);
4843 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4844 for (; *Aliases; ++Aliases)
4845 Regs.insert(*Aliases);
4846 }
4847};
4848} // end llvm namespace.
4849
4850
4851/// GetRegistersForValue - Assign registers (virtual or physical) for the
4852/// specified operand. We prefer to assign virtual registers, to allow the
4853/// register allocator handle the assignment process. However, if the asm uses
4854/// features that we can't model on machineinstrs, we have SDISel do the
4855/// allocation. This produces generally horrible, but correct, code.
4856///
4857/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004858/// Input and OutputRegs are the set of already allocated physical registers.
4859///
4860void SelectionDAGLowering::
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004861GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004862 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004863 std::set<unsigned> &InputRegs) {
4864 // Compute whether this value requires an input register, an output register,
4865 // or both.
4866 bool isOutReg = false;
4867 bool isInReg = false;
4868 switch (OpInfo.Type) {
4869 case InlineAsm::isOutput:
4870 isOutReg = true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004871
4872 // If there is an input constraint that matches this, we need to reserve
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004873 // the input register so no other inputs allocate to it.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004874 isInReg = OpInfo.hasMatchingInput();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004875 break;
4876 case InlineAsm::isInput:
4877 isInReg = true;
4878 isOutReg = false;
4879 break;
4880 case InlineAsm::isClobber:
4881 isOutReg = true;
4882 isInReg = true;
4883 break;
4884 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004885
4886
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004887 MachineFunction &MF = DAG.getMachineFunction();
4888 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004889
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004890 // If this is a constraint for a single physreg, or a constraint for a
4891 // register class, find it.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004892 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004893 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4894 OpInfo.ConstraintVT);
4895
4896 unsigned NumRegs = 1;
Chris Lattner01426e12008-10-21 00:45:36 +00004897 if (OpInfo.ConstraintVT != MVT::Other) {
4898 // If this is a FP input in an integer register (or visa versa) insert a bit
4899 // cast of the input value. More generally, handle any case where the input
4900 // value disagrees with the register class we plan to stick this in.
4901 if (OpInfo.Type == InlineAsm::isInput &&
4902 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4903 // Try to convert to the first MVT that the reg class contains. If the
4904 // types are identical size, use a bitcast to convert (e.g. two differing
4905 // vector types).
4906 MVT RegVT = *PhysReg.second->vt_begin();
4907 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00004908 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004909 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00004910 OpInfo.ConstraintVT = RegVT;
4911 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4912 // If the input is a FP value and we want it in FP registers, do a
4913 // bitcast to the corresponding integer type. This turns an f64 value
4914 // into i64, which can be passed with two i32 values on a 32-bit
4915 // machine.
4916 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
Dale Johannesen66978ee2009-01-31 02:22:37 +00004917 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004918 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00004919 OpInfo.ConstraintVT = RegVT;
4920 }
4921 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004922
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004923 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00004924 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004925
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004926 MVT RegVT;
4927 MVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004928
4929 // If this is a constraint for a specific physical register, like {r17},
4930 // assign it now.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004931 if (unsigned AssignedReg = PhysReg.first) {
4932 const TargetRegisterClass *RC = PhysReg.second;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004933 if (OpInfo.ConstraintVT == MVT::Other)
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004934 ValueVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004935
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004936 // Get the actual register value type. This is important, because the user
4937 // may have asked for (e.g.) the AX register in i32 type. We need to
4938 // remember that AX is actually i16 to get the right extension.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004939 RegVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004940
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004941 // This is a explicit reference to a physical register.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004942 Regs.push_back(AssignedReg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004943
4944 // If this is an expanded reference, add the rest of the regs to Regs.
4945 if (NumRegs != 1) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004946 TargetRegisterClass::iterator I = RC->begin();
4947 for (; *I != AssignedReg; ++I)
4948 assert(I != RC->end() && "Didn't find reg!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004949
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004950 // Already added the first reg.
4951 --NumRegs; ++I;
4952 for (; NumRegs; --NumRegs, ++I) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004953 assert(I != RC->end() && "Ran out of registers to allocate!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004954 Regs.push_back(*I);
4955 }
4956 }
4957 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4958 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4959 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4960 return;
4961 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004962
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004963 // Otherwise, if this was a reference to an LLVM register class, create vregs
4964 // for this reference.
Chris Lattnerb3b44842009-03-24 15:25:07 +00004965 if (const TargetRegisterClass *RC = PhysReg.second) {
4966 RegVT = *RC->vt_begin();
Evan Chengfb112882009-03-23 08:01:15 +00004967 if (OpInfo.ConstraintVT == MVT::Other)
4968 ValueVT = RegVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004969
Evan Chengfb112882009-03-23 08:01:15 +00004970 // Create the appropriate number of virtual registers.
4971 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4972 for (; NumRegs; --NumRegs)
Chris Lattnerb3b44842009-03-24 15:25:07 +00004973 Regs.push_back(RegInfo.createVirtualRegister(RC));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004974
Evan Chengfb112882009-03-23 08:01:15 +00004975 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4976 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004977 }
Chris Lattnerfc9d1612009-03-24 15:22:11 +00004978
4979 // This is a reference to a register class that doesn't directly correspond
4980 // to an LLVM register class. Allocate NumRegs consecutive, available,
4981 // registers from the class.
4982 std::vector<unsigned> RegClassRegs
4983 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4984 OpInfo.ConstraintVT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004985
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004986 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4987 unsigned NumAllocated = 0;
4988 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4989 unsigned Reg = RegClassRegs[i];
4990 // See if this register is available.
4991 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4992 (isInReg && InputRegs.count(Reg))) { // Already used.
4993 // Make sure we find consecutive registers.
4994 NumAllocated = 0;
4995 continue;
4996 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004997
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004998 // Check to see if this register is allocatable (i.e. don't give out the
4999 // stack pointer).
Chris Lattnerfc9d1612009-03-24 15:22:11 +00005000 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5001 if (!RC) { // Couldn't allocate this register.
5002 // Reset NumAllocated to make sure we return consecutive registers.
5003 NumAllocated = 0;
5004 continue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005005 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005006
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005007 // Okay, this register is good, we can use it.
5008 ++NumAllocated;
5009
5010 // If we allocated enough consecutive registers, succeed.
5011 if (NumAllocated == NumRegs) {
5012 unsigned RegStart = (i-NumAllocated)+1;
5013 unsigned RegEnd = i+1;
5014 // Mark all of the allocated registers used.
5015 for (unsigned i = RegStart; i != RegEnd; ++i)
5016 Regs.push_back(RegClassRegs[i]);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005017
5018 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005019 OpInfo.ConstraintVT);
5020 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5021 return;
5022 }
5023 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005024
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005025 // Otherwise, we couldn't allocate enough registers for this.
5026}
5027
Evan Chengda43bcf2008-09-24 00:05:32 +00005028/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5029/// processed uses a memory 'm' constraint.
5030static bool
5031hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
Dan Gohmane9530ec2009-01-15 16:58:17 +00005032 const TargetLowering &TLI) {
Evan Chengda43bcf2008-09-24 00:05:32 +00005033 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5034 InlineAsm::ConstraintInfo &CI = CInfos[i];
5035 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5036 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5037 if (CType == TargetLowering::C_Memory)
5038 return true;
5039 }
Chris Lattner6c147292009-04-30 00:48:50 +00005040
5041 // Indirect operand accesses access memory.
5042 if (CI.isIndirect)
5043 return true;
Evan Chengda43bcf2008-09-24 00:05:32 +00005044 }
5045
5046 return false;
5047}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005048
5049/// visitInlineAsm - Handle a call to an InlineAsm object.
5050///
5051void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
5052 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5053
5054 /// ConstraintOperands - Information about all of the constraints.
5055 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005056
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005057 std::set<unsigned> OutputRegs, InputRegs;
5058
5059 // Do a prepass over the constraints, canonicalizing them, and building up the
5060 // ConstraintOperands list.
5061 std::vector<InlineAsm::ConstraintInfo>
5062 ConstraintInfos = IA->ParseConstraints();
5063
Evan Chengda43bcf2008-09-24 00:05:32 +00005064 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Chris Lattner6c147292009-04-30 00:48:50 +00005065
5066 SDValue Chain, Flag;
5067
5068 // We won't need to flush pending loads if this asm doesn't touch
5069 // memory and is nonvolatile.
5070 if (hasMemory || IA->hasSideEffects())
Dale Johannesen97d14fc2009-04-18 00:09:40 +00005071 Chain = getRoot();
Chris Lattner6c147292009-04-30 00:48:50 +00005072 else
5073 Chain = DAG.getRoot();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005074
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005075 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5076 unsigned ResNo = 0; // ResNo - The result number of the next output.
5077 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5078 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5079 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005080
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005081 MVT OpVT = MVT::Other;
5082
5083 // Compute the value type for each operand.
5084 switch (OpInfo.Type) {
5085 case InlineAsm::isOutput:
5086 // Indirect outputs just consume an argument.
5087 if (OpInfo.isIndirect) {
5088 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5089 break;
5090 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005091
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005092 // The return value of the call is this value. As such, there is no
5093 // corresponding argument.
5094 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5095 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5096 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5097 } else {
5098 assert(ResNo == 0 && "Asm only has one result!");
5099 OpVT = TLI.getValueType(CS.getType());
5100 }
5101 ++ResNo;
5102 break;
5103 case InlineAsm::isInput:
5104 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5105 break;
5106 case InlineAsm::isClobber:
5107 // Nothing to do.
5108 break;
5109 }
5110
5111 // If this is an input or an indirect output, process the call argument.
5112 // BasicBlocks are labels, currently appearing only in asm's.
5113 if (OpInfo.CallOperandVal) {
Chris Lattner81249c92008-10-17 17:05:25 +00005114 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005115 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00005116 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005117 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005118 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005119
Chris Lattner81249c92008-10-17 17:05:25 +00005120 OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005121 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005122
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005123 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005124 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005125
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005126 // Second pass over the constraints: compute which constraint option to use
5127 // and assign registers to constraints that want a specific physreg.
5128 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5129 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005130
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005131 // If this is an output operand with a matching input operand, look up the
Evan Cheng09dc9c02008-12-16 18:21:39 +00005132 // matching input. If their types mismatch, e.g. one is an integer, the
5133 // other is floating point, or their sizes are different, flag it as an
5134 // error.
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005135 if (OpInfo.hasMatchingInput()) {
5136 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5137 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Evan Cheng09dc9c02008-12-16 18:21:39 +00005138 if ((OpInfo.ConstraintVT.isInteger() !=
5139 Input.ConstraintVT.isInteger()) ||
5140 (OpInfo.ConstraintVT.getSizeInBits() !=
5141 Input.ConstraintVT.getSizeInBits())) {
Daniel Dunbar4cbb1732009-04-13 22:26:09 +00005142 cerr << "llvm: error: Unsupported asm: input constraint with a "
5143 << "matching output constraint of incompatible type!\n";
Evan Cheng09dc9c02008-12-16 18:21:39 +00005144 exit(1);
5145 }
5146 Input.ConstraintVT = OpInfo.ConstraintVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005147 }
5148 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005149
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005150 // Compute the constraint code and ConstraintType to use.
Evan Chengda43bcf2008-09-24 00:05:32 +00005151 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005152
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005153 // If this is a memory input, and if the operand is not indirect, do what we
5154 // need to to provide an address for the memory input.
5155 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5156 !OpInfo.isIndirect) {
5157 assert(OpInfo.Type == InlineAsm::isInput &&
5158 "Can only indirectify direct input operands!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005159
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005160 // Memory operands really want the address of the value. If we don't have
5161 // an indirect input, put it in the constpool if we can, otherwise spill
5162 // it to a stack slot.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005163
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005164 // If the operand is a float, integer, or vector constant, spill to a
5165 // constant pool entry to get its address.
5166 Value *OpVal = OpInfo.CallOperandVal;
5167 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5168 isa<ConstantVector>(OpVal)) {
5169 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5170 TLI.getPointerTy());
5171 } else {
5172 // Otherwise, create a stack slot and emit a store to it before the
5173 // asm.
5174 const Type *Ty = OpVal->getType();
Duncan Sands777d2302009-05-09 07:06:46 +00005175 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005176 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5177 MachineFunction &MF = DAG.getMachineFunction();
5178 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
5179 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Dale Johannesen66978ee2009-01-31 02:22:37 +00005180 Chain = DAG.getStore(Chain, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005181 OpInfo.CallOperand, StackSlot, NULL, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005182 OpInfo.CallOperand = StackSlot;
5183 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005184
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005185 // There is no longer a Value* corresponding to this operand.
5186 OpInfo.CallOperandVal = 0;
5187 // It is now an indirect operand.
5188 OpInfo.isIndirect = true;
5189 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005190
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005191 // If this constraint is for a specific register, allocate it before
5192 // anything else.
5193 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005194 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005195 }
5196 ConstraintInfos.clear();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005197
5198
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005199 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00005200 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005201 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5202 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005203
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005204 // C_Register operands have already been allocated, Other/Memory don't need
5205 // to be.
5206 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005207 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005208 }
5209
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005210 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5211 std::vector<SDValue> AsmNodeOperands;
5212 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5213 AsmNodeOperands.push_back(
Bill Wendling056292f2008-09-16 21:48:12 +00005214 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005215
5216
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005217 // Loop over all of the inputs, copying the operand values into the
5218 // appropriate registers and processing the output regs.
5219 RegsForValue RetValRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005220
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005221 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5222 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005223
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005224 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5225 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5226
5227 switch (OpInfo.Type) {
5228 case InlineAsm::isOutput: {
5229 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5230 OpInfo.ConstraintType != TargetLowering::C_Register) {
5231 // Memory output, or 'other' output (e.g. 'X' constraint).
5232 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5233
5234 // Add information to the INLINEASM node to know about this output.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005235 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5236 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005237 TLI.getPointerTy()));
5238 AsmNodeOperands.push_back(OpInfo.CallOperand);
5239 break;
5240 }
5241
5242 // Otherwise, this is a register or register class output.
5243
5244 // Copy the output from the appropriate register. Find a register that
5245 // we can use.
5246 if (OpInfo.AssignedRegs.Regs.empty()) {
Daniel Dunbar4cbb1732009-04-13 22:26:09 +00005247 cerr << "llvm: error: Couldn't allocate output reg for constraint '"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005248 << OpInfo.ConstraintCode << "'!\n";
5249 exit(1);
5250 }
5251
5252 // If this is an indirect operand, store through the pointer after the
5253 // asm.
5254 if (OpInfo.isIndirect) {
5255 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5256 OpInfo.CallOperandVal));
5257 } else {
5258 // This is the result value of the call.
5259 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5260 // Concatenate this output onto the outputs list.
5261 RetValRegs.append(OpInfo.AssignedRegs);
5262 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005263
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005264 // Add information to the INLINEASM node to know that this register is
5265 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00005266 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5267 6 /* EARLYCLOBBER REGDEF */ :
5268 2 /* REGDEF */ ,
Evan Chengfb112882009-03-23 08:01:15 +00005269 false,
5270 0,
Dale Johannesen913d3df2008-09-12 17:49:03 +00005271 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005272 break;
5273 }
5274 case InlineAsm::isInput: {
5275 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005276
Chris Lattner6bdcda32008-10-17 16:47:46 +00005277 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005278 // If this is required to match an output register we have already set,
5279 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00005280 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005281
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005282 // Scan until we find the definition we already emitted of this operand.
5283 // When we find it, create a RegsForValue operand.
5284 unsigned CurOp = 2; // The first operand.
5285 for (; OperandNo; --OperandNo) {
5286 // Advance to the next operand.
Evan Cheng697cbbf2009-03-20 18:03:34 +00005287 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005288 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005289 assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5290 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5291 (OpFlag & 7) == 4 /*MEM*/) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005292 "Skipped past definitions?");
Evan Cheng697cbbf2009-03-20 18:03:34 +00005293 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005294 }
5295
Evan Cheng697cbbf2009-03-20 18:03:34 +00005296 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005297 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005298 if ((OpFlag & 7) == 2 /*REGDEF*/
5299 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5300 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
Dan Gohman15480bd2009-06-15 22:32:41 +00005301 if (OpInfo.isIndirect) {
5302 cerr << "llvm: error: "
5303 "Don't know how to handle tied indirect "
5304 "register inputs yet!\n";
5305 exit(1);
5306 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005307 RegsForValue MatchedRegs;
5308 MatchedRegs.TLI = &TLI;
5309 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
Evan Chengfb112882009-03-23 08:01:15 +00005310 MVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5311 MatchedRegs.RegVTs.push_back(RegVT);
5312 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005313 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
Evan Chengfb112882009-03-23 08:01:15 +00005314 i != e; ++i)
5315 MatchedRegs.Regs.
5316 push_back(RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005317
5318 // Use the produced MatchedRegs object to
Dale Johannesen66978ee2009-01-31 02:22:37 +00005319 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5320 Chain, &Flag);
Evan Chengfb112882009-03-23 08:01:15 +00005321 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5322 true, OpInfo.getMatchedOperand(),
Evan Cheng697cbbf2009-03-20 18:03:34 +00005323 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005324 break;
5325 } else {
Evan Cheng697cbbf2009-03-20 18:03:34 +00005326 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5327 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5328 "Unexpected number of operands");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005329 // Add information to the INLINEASM node to know about this input.
Evan Chengfb112882009-03-23 08:01:15 +00005330 // See InlineAsm.h isUseOperandTiedToDef.
5331 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
Evan Cheng697cbbf2009-03-20 18:03:34 +00005332 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005333 TLI.getPointerTy()));
5334 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5335 break;
5336 }
5337 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005338
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005339 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005340 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005341 "Don't know how to handle indirect other inputs yet!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005342
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005343 std::vector<SDValue> Ops;
5344 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Chengda43bcf2008-09-24 00:05:32 +00005345 hasMemory, Ops, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005346 if (Ops.empty()) {
Daniel Dunbar4cbb1732009-04-13 22:26:09 +00005347 cerr << "llvm: error: Invalid operand for inline asm constraint '"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005348 << OpInfo.ConstraintCode << "'!\n";
5349 exit(1);
5350 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005351
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005352 // Add information to the INLINEASM node to know about this input.
5353 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005354 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005355 TLI.getPointerTy()));
5356 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5357 break;
5358 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5359 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5360 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5361 "Memory operands expect pointer values");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005362
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005363 // Add information to the INLINEASM node to know about this input.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005364 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5365 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005366 TLI.getPointerTy()));
5367 AsmNodeOperands.push_back(InOperandVal);
5368 break;
5369 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005370
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005371 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5372 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5373 "Unknown constraint type!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005374 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005375 "Don't know how to handle indirect register inputs yet!");
5376
5377 // Copy the input into the appropriate registers.
Evan Chengaa765b82008-09-25 00:14:04 +00005378 if (OpInfo.AssignedRegs.Regs.empty()) {
Daniel Dunbar4cbb1732009-04-13 22:26:09 +00005379 cerr << "llvm: error: Couldn't allocate output reg for constraint '"
Evan Chengaa765b82008-09-25 00:14:04 +00005380 << OpInfo.ConstraintCode << "'!\n";
5381 exit(1);
5382 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005383
Dale Johannesen66978ee2009-01-31 02:22:37 +00005384 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5385 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005386
Evan Cheng697cbbf2009-03-20 18:03:34 +00005387 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
Dale Johannesen86b49f82008-09-24 01:07:17 +00005388 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005389 break;
5390 }
5391 case InlineAsm::isClobber: {
5392 // Add the clobbered value to the operand list, so that the register
5393 // allocator is aware that the physreg got clobbered.
5394 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesen91aac102008-09-17 21:13:11 +00005395 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
Evan Cheng697cbbf2009-03-20 18:03:34 +00005396 false, 0, DAG,AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005397 break;
5398 }
5399 }
5400 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005401
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005402 // Finish up input operands.
5403 AsmNodeOperands[0] = Chain;
5404 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005405
Dale Johannesen66978ee2009-01-31 02:22:37 +00005406 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00005407 DAG.getVTList(MVT::Other, MVT::Flag),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005408 &AsmNodeOperands[0], AsmNodeOperands.size());
5409 Flag = Chain.getValue(1);
5410
5411 // If this asm returns a register value, copy the result from that register
5412 // and set it as the value of the call.
5413 if (!RetValRegs.Regs.empty()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00005414 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00005415 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005416
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005417 // FIXME: Why don't we do this for inline asms with MRVs?
5418 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5419 MVT ResultType = TLI.getValueType(CS.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005420
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005421 // If any of the results of the inline asm is a vector, it may have the
5422 // wrong width/num elts. This can happen for register classes that can
5423 // contain multiple different value types. The preg or vreg allocated may
5424 // not have the same VT as was expected. Convert it to the right type
5425 // with bit_convert.
5426 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005427 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005428 ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005429
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005430 } else if (ResultType != Val.getValueType() &&
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005431 ResultType.isInteger() && Val.getValueType().isInteger()) {
5432 // If a result value was tied to an input value, the computed result may
5433 // have a wider width than the expected result. Extract the relevant
5434 // portion.
Dale Johannesen66978ee2009-01-31 02:22:37 +00005435 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005436 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005437
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005438 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00005439 }
Dan Gohman95915732008-10-18 01:03:45 +00005440
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005441 setValue(CS.getInstruction(), Val);
Dale Johannesenec65a7d2009-04-14 00:56:56 +00005442 // Don't need to use this as a chain in this case.
5443 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5444 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005445 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005446
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005447 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005448
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005449 // Process indirect outputs, first output all of the flagged copies out of
5450 // physregs.
5451 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5452 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5453 Value *Ptr = IndirectStoresToEmit[i].second;
Dale Johannesen66978ee2009-01-31 02:22:37 +00005454 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5455 Chain, &Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005456 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6c147292009-04-30 00:48:50 +00005457
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005458 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005459
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005460 // Emit the non-flagged stores from the physregs.
5461 SmallVector<SDValue, 8> OutChains;
5462 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00005463 OutChains.push_back(DAG.getStore(Chain, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005464 StoresToEmit[i].first,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005465 getValue(StoresToEmit[i].second),
5466 StoresToEmit[i].second, 0));
5467 if (!OutChains.empty())
Dale Johannesen66978ee2009-01-31 02:22:37 +00005468 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005469 &OutChains[0], OutChains.size());
5470 DAG.setRoot(Chain);
5471}
5472
5473
5474void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5475 SDValue Src = getValue(I.getOperand(0));
5476
Chris Lattner0b18e592009-03-17 19:36:00 +00005477 // Scale up by the type size in the original i32 type width. Various
5478 // mid-level optimizers may make assumptions about demanded bits etc from the
5479 // i32-ness of the optimizer: we do not want to promote to i64 and then
5480 // multiply on 64-bit targets.
5481 // FIXME: Malloc inst should go away: PR715.
Duncan Sands777d2302009-05-09 07:06:46 +00005482 uint64_t ElementSize = TD->getTypeAllocSize(I.getType()->getElementType());
Chris Lattner0b18e592009-03-17 19:36:00 +00005483 if (ElementSize != 1)
5484 Src = DAG.getNode(ISD::MUL, getCurDebugLoc(), Src.getValueType(),
5485 Src, DAG.getConstant(ElementSize, Src.getValueType()));
5486
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005487 MVT IntPtr = TLI.getPointerTy();
5488
5489 if (IntPtr.bitsLT(Src.getValueType()))
Dale Johannesen66978ee2009-01-31 02:22:37 +00005490 Src = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), IntPtr, Src);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005491 else if (IntPtr.bitsGT(Src.getValueType()))
Dale Johannesen66978ee2009-01-31 02:22:37 +00005492 Src = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), IntPtr, Src);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005493
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005494 TargetLowering::ArgListTy Args;
5495 TargetLowering::ArgListEntry Entry;
5496 Entry.Node = Src;
5497 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5498 Args.push_back(Entry);
5499
5500 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005501 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005502 CallingConv::C, PerformTailCallOpt,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005503 DAG.getExternalSymbol("malloc", IntPtr),
Dale Johannesen66978ee2009-01-31 02:22:37 +00005504 Args, DAG, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005505 setValue(&I, Result.first); // Pointers always fit in registers
5506 DAG.setRoot(Result.second);
5507}
5508
5509void SelectionDAGLowering::visitFree(FreeInst &I) {
5510 TargetLowering::ArgListTy Args;
5511 TargetLowering::ArgListEntry Entry;
5512 Entry.Node = getValue(I.getOperand(0));
5513 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5514 Args.push_back(Entry);
5515 MVT IntPtr = TLI.getPointerTy();
5516 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005517 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
Dan Gohman1937e2f2008-09-16 01:42:28 +00005518 CallingConv::C, PerformTailCallOpt,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005519 DAG.getExternalSymbol("free", IntPtr), Args, DAG,
Dale Johannesen66978ee2009-01-31 02:22:37 +00005520 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005521 DAG.setRoot(Result.second);
5522}
5523
5524void SelectionDAGLowering::visitVAStart(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005525 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005526 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005527 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005528 DAG.getSrcValue(I.getOperand(1))));
5529}
5530
5531void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Dale Johannesena04b7572009-02-03 23:04:43 +00005532 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5533 getRoot(), getValue(I.getOperand(0)),
5534 DAG.getSrcValue(I.getOperand(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005535 setValue(&I, V);
5536 DAG.setRoot(V.getValue(1));
5537}
5538
5539void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005540 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005541 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005542 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005543 DAG.getSrcValue(I.getOperand(1))));
5544}
5545
5546void SelectionDAGLowering::visitVACopy(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005547 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005548 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005549 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005550 getValue(I.getOperand(2)),
5551 DAG.getSrcValue(I.getOperand(1)),
5552 DAG.getSrcValue(I.getOperand(2))));
5553}
5554
5555/// TargetLowering::LowerArguments - This is the default LowerArguments
5556/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005557/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005558/// integrated into SDISel.
5559void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005560 SmallVectorImpl<SDValue> &ArgValues,
5561 DebugLoc dl) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005562 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5563 SmallVector<SDValue, 3+16> Ops;
5564 Ops.push_back(DAG.getRoot());
5565 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5566 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5567
5568 // Add one result value for each formal argument.
5569 SmallVector<MVT, 16> RetVals;
5570 unsigned j = 1;
5571 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5572 I != E; ++I, ++j) {
5573 SmallVector<MVT, 4> ValueVTs;
5574 ComputeValueVTs(*this, I->getType(), ValueVTs);
5575 for (unsigned Value = 0, NumValues = ValueVTs.size();
5576 Value != NumValues; ++Value) {
5577 MVT VT = ValueVTs[Value];
5578 const Type *ArgTy = VT.getTypeForMVT();
5579 ISD::ArgFlagsTy Flags;
5580 unsigned OriginalAlignment =
5581 getTargetData()->getABITypeAlignment(ArgTy);
5582
Devang Patel05988662008-09-25 21:00:45 +00005583 if (F.paramHasAttr(j, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005584 Flags.setZExt();
Devang Patel05988662008-09-25 21:00:45 +00005585 if (F.paramHasAttr(j, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005586 Flags.setSExt();
Devang Patel05988662008-09-25 21:00:45 +00005587 if (F.paramHasAttr(j, Attribute::InReg))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005588 Flags.setInReg();
Devang Patel05988662008-09-25 21:00:45 +00005589 if (F.paramHasAttr(j, Attribute::StructRet))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005590 Flags.setSRet();
Devang Patel05988662008-09-25 21:00:45 +00005591 if (F.paramHasAttr(j, Attribute::ByVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005592 Flags.setByVal();
5593 const PointerType *Ty = cast<PointerType>(I->getType());
5594 const Type *ElementTy = Ty->getElementType();
5595 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sands777d2302009-05-09 07:06:46 +00005596 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005597 // For ByVal, alignment should be passed from FE. BE will guess if
5598 // this info is not there but there are cases it cannot get right.
5599 if (F.getParamAlignment(j))
5600 FrameAlign = F.getParamAlignment(j);
5601 Flags.setByValAlign(FrameAlign);
5602 Flags.setByValSize(FrameSize);
5603 }
Devang Patel05988662008-09-25 21:00:45 +00005604 if (F.paramHasAttr(j, Attribute::Nest))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005605 Flags.setNest();
5606 Flags.setOrigAlign(OriginalAlignment);
5607
5608 MVT RegisterVT = getRegisterType(VT);
5609 unsigned NumRegs = getNumRegisters(VT);
5610 for (unsigned i = 0; i != NumRegs; ++i) {
5611 RetVals.push_back(RegisterVT);
5612 ISD::ArgFlagsTy MyFlags = Flags;
5613 if (NumRegs > 1 && i == 0)
5614 MyFlags.setSplit();
5615 // if it isn't first piece, alignment must be 1
5616 else if (i > 0)
5617 MyFlags.setOrigAlign(1);
5618 Ops.push_back(DAG.getArgFlags(MyFlags));
5619 }
5620 }
5621 }
5622
5623 RetVals.push_back(MVT::Other);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005624
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005625 // Create the node.
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005626 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005627 DAG.getVTList(&RetVals[0], RetVals.size()),
5628 &Ops[0], Ops.size()).getNode();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005629
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005630 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5631 // allows exposing the loads that may be part of the argument access to the
5632 // first DAGCombiner pass.
5633 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005634
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005635 // The number of results should match up, except that the lowered one may have
5636 // an extra flag result.
5637 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5638 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5639 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5640 && "Lowering produced unexpected number of results!");
5641
5642 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5643 if (Result != TmpRes.getNode() && Result->use_empty()) {
5644 HandleSDNode Dummy(DAG.getRoot());
5645 DAG.RemoveDeadNode(Result);
5646 }
5647
5648 Result = TmpRes.getNode();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005649
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005650 unsigned NumArgRegs = Result->getNumValues() - 1;
5651 DAG.setRoot(SDValue(Result, NumArgRegs));
5652
5653 // Set up the return result vector.
5654 unsigned i = 0;
5655 unsigned Idx = 1;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005656 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005657 ++I, ++Idx) {
5658 SmallVector<MVT, 4> ValueVTs;
5659 ComputeValueVTs(*this, I->getType(), ValueVTs);
5660 for (unsigned Value = 0, NumValues = ValueVTs.size();
5661 Value != NumValues; ++Value) {
5662 MVT VT = ValueVTs[Value];
5663 MVT PartVT = getRegisterType(VT);
5664
5665 unsigned NumParts = getNumRegisters(VT);
5666 SmallVector<SDValue, 4> Parts(NumParts);
5667 for (unsigned j = 0; j != NumParts; ++j)
5668 Parts[j] = SDValue(Result, i++);
5669
5670 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Devang Patel05988662008-09-25 21:00:45 +00005671 if (F.paramHasAttr(Idx, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005672 AssertOp = ISD::AssertSext;
Devang Patel05988662008-09-25 21:00:45 +00005673 else if (F.paramHasAttr(Idx, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005674 AssertOp = ISD::AssertZext;
5675
Dale Johannesen66978ee2009-01-31 02:22:37 +00005676 ArgValues.push_back(getCopyFromParts(DAG, dl, &Parts[0], NumParts,
5677 PartVT, VT, AssertOp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005678 }
5679 }
5680 assert(i == NumArgRegs && "Argument register count mismatch!");
5681}
5682
5683
5684/// TargetLowering::LowerCallTo - This is the default LowerCallTo
5685/// implementation, which just inserts an ISD::CALL node, which is later custom
5686/// lowered by the target to something concrete. FIXME: When all targets are
5687/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5688std::pair<SDValue, SDValue>
5689TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5690 bool RetSExt, bool RetZExt, bool isVarArg,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005691 bool isInreg,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005692 unsigned CallingConv, bool isTailCall,
5693 SDValue Callee,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005694 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
Dan Gohman1937e2f2008-09-16 01:42:28 +00005695 assert((!isTailCall || PerformTailCallOpt) &&
5696 "isTailCall set when tail-call optimizations are disabled!");
5697
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005698 SmallVector<SDValue, 32> Ops;
5699 Ops.push_back(Chain); // Op#0 - Chain
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005700 Ops.push_back(Callee);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005701
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005702 // Handle all of the outgoing arguments.
5703 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5704 SmallVector<MVT, 4> ValueVTs;
5705 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5706 for (unsigned Value = 0, NumValues = ValueVTs.size();
5707 Value != NumValues; ++Value) {
5708 MVT VT = ValueVTs[Value];
5709 const Type *ArgTy = VT.getTypeForMVT();
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005710 SDValue Op = SDValue(Args[i].Node.getNode(),
5711 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005712 ISD::ArgFlagsTy Flags;
5713 unsigned OriginalAlignment =
5714 getTargetData()->getABITypeAlignment(ArgTy);
5715
5716 if (Args[i].isZExt)
5717 Flags.setZExt();
5718 if (Args[i].isSExt)
5719 Flags.setSExt();
5720 if (Args[i].isInReg)
5721 Flags.setInReg();
5722 if (Args[i].isSRet)
5723 Flags.setSRet();
5724 if (Args[i].isByVal) {
5725 Flags.setByVal();
5726 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5727 const Type *ElementTy = Ty->getElementType();
5728 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sands777d2302009-05-09 07:06:46 +00005729 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005730 // For ByVal, alignment should come from FE. BE will guess if this
5731 // info is not there but there are cases it cannot get right.
5732 if (Args[i].Alignment)
5733 FrameAlign = Args[i].Alignment;
5734 Flags.setByValAlign(FrameAlign);
5735 Flags.setByValSize(FrameSize);
5736 }
5737 if (Args[i].isNest)
5738 Flags.setNest();
5739 Flags.setOrigAlign(OriginalAlignment);
5740
5741 MVT PartVT = getRegisterType(VT);
5742 unsigned NumParts = getNumRegisters(VT);
5743 SmallVector<SDValue, 4> Parts(NumParts);
5744 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5745
5746 if (Args[i].isSExt)
5747 ExtendKind = ISD::SIGN_EXTEND;
5748 else if (Args[i].isZExt)
5749 ExtendKind = ISD::ZERO_EXTEND;
5750
Dale Johannesen66978ee2009-01-31 02:22:37 +00005751 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, PartVT, ExtendKind);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005752
5753 for (unsigned i = 0; i != NumParts; ++i) {
5754 // if it isn't first piece, alignment must be 1
5755 ISD::ArgFlagsTy MyFlags = Flags;
5756 if (NumParts > 1 && i == 0)
5757 MyFlags.setSplit();
5758 else if (i != 0)
5759 MyFlags.setOrigAlign(1);
5760
5761 Ops.push_back(Parts[i]);
5762 Ops.push_back(DAG.getArgFlags(MyFlags));
5763 }
5764 }
5765 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005766
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005767 // Figure out the result value types. We start by making a list of
5768 // the potentially illegal return value types.
5769 SmallVector<MVT, 4> LoweredRetTys;
5770 SmallVector<MVT, 4> RetTys;
5771 ComputeValueVTs(*this, RetTy, RetTys);
5772
5773 // Then we translate that to a list of legal types.
5774 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5775 MVT VT = RetTys[I];
5776 MVT RegisterVT = getRegisterType(VT);
5777 unsigned NumRegs = getNumRegisters(VT);
5778 for (unsigned i = 0; i != NumRegs; ++i)
5779 LoweredRetTys.push_back(RegisterVT);
5780 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005781
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005782 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005783
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005784 // Create the CALL node.
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005785 SDValue Res = DAG.getCall(CallingConv, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005786 isVarArg, isTailCall, isInreg,
Dan Gohman095cc292008-09-13 01:54:27 +00005787 DAG.getVTList(&LoweredRetTys[0],
5788 LoweredRetTys.size()),
Dale Johannesen86098bd2008-09-26 19:31:26 +00005789 &Ops[0], Ops.size()
5790 );
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005791 Chain = Res.getValue(LoweredRetTys.size() - 1);
5792
5793 // Gather up the call result into a single value.
Dan Gohmanb5cc34d2008-10-07 00:12:37 +00005794 if (RetTy != Type::VoidTy && !RetTys.empty()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005795 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5796
5797 if (RetSExt)
5798 AssertOp = ISD::AssertSext;
5799 else if (RetZExt)
5800 AssertOp = ISD::AssertZext;
5801
5802 SmallVector<SDValue, 4> ReturnValues;
5803 unsigned RegNo = 0;
5804 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5805 MVT VT = RetTys[I];
5806 MVT RegisterVT = getRegisterType(VT);
5807 unsigned NumRegs = getNumRegisters(VT);
5808 unsigned RegNoEnd = NumRegs + RegNo;
5809 SmallVector<SDValue, 4> Results;
5810 for (; RegNo != RegNoEnd; ++RegNo)
5811 Results.push_back(Res.getValue(RegNo));
5812 SDValue ReturnValue =
Dale Johannesen66978ee2009-01-31 02:22:37 +00005813 getCopyFromParts(DAG, dl, &Results[0], NumRegs, RegisterVT, VT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005814 AssertOp);
5815 ReturnValues.push_back(ReturnValue);
5816 }
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005817 Res = DAG.getNode(ISD::MERGE_VALUES, dl,
Duncan Sandsaaffa052008-12-01 11:41:29 +00005818 DAG.getVTList(&RetTys[0], RetTys.size()),
5819 &ReturnValues[0], ReturnValues.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005820 }
5821
5822 return std::make_pair(Res, Chain);
5823}
5824
Duncan Sands9fbc7e22009-01-21 09:00:29 +00005825void TargetLowering::LowerOperationWrapper(SDNode *N,
5826 SmallVectorImpl<SDValue> &Results,
5827 SelectionDAG &DAG) {
5828 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptabb326bb2009-01-21 04:48:39 +00005829 if (Res.getNode())
5830 Results.push_back(Res);
5831}
5832
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005833SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5834 assert(0 && "LowerOperation not implemented for this target!");
5835 abort();
5836 return SDValue();
5837}
5838
5839
5840void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5841 SDValue Op = getValue(V);
5842 assert((Op.getOpcode() != ISD::CopyFromReg ||
5843 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5844 "Copy from a reg to the same reg!");
5845 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5846
5847 RegsForValue RFV(TLI, Reg, V->getType());
5848 SDValue Chain = DAG.getEntryNode();
Dale Johannesen66978ee2009-01-31 02:22:37 +00005849 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005850 PendingExports.push_back(Chain);
5851}
5852
5853#include "llvm/CodeGen/SelectionDAGISel.h"
5854
5855void SelectionDAGISel::
5856LowerArguments(BasicBlock *LLVMBB) {
5857 // If this is the entry block, emit arguments.
5858 Function &F = *LLVMBB->getParent();
5859 SDValue OldRoot = SDL->DAG.getRoot();
5860 SmallVector<SDValue, 16> Args;
Dale Johannesen66978ee2009-01-31 02:22:37 +00005861 TLI.LowerArguments(F, SDL->DAG, Args, SDL->getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005862
5863 unsigned a = 0;
5864 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5865 AI != E; ++AI) {
5866 SmallVector<MVT, 4> ValueVTs;
5867 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5868 unsigned NumValues = ValueVTs.size();
5869 if (!AI->use_empty()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00005870 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues,
Dale Johannesen4be0bdf2009-02-05 00:20:09 +00005871 SDL->getCurDebugLoc()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005872 // If this argument is live outside of the entry block, insert a copy from
5873 // whereever we got it to the vreg that other BB's will reference it as.
Dan Gohmanad62f532009-04-23 23:13:24 +00005874 SDL->CopyToExportRegsIfNeeded(AI);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005875 }
5876 a += NumValues;
5877 }
5878
5879 // Finally, if the target has anything special to do, allow it to do so.
5880 // FIXME: this should insert code into the DAG!
5881 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5882}
5883
5884/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5885/// ensure constants are generated when needed. Remember the virtual registers
5886/// that need to be added to the Machine PHI nodes as input. We cannot just
5887/// directly add them, because expansion might result in multiple MBB's for one
5888/// BB. As such, the start of the BB might correspond to a different MBB than
5889/// the end.
5890///
5891void
5892SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5893 TerminatorInst *TI = LLVMBB->getTerminator();
5894
5895 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5896
5897 // Check successor nodes' PHI nodes that expect a constant to be available
5898 // from this block.
5899 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5900 BasicBlock *SuccBB = TI->getSuccessor(succ);
5901 if (!isa<PHINode>(SuccBB->begin())) continue;
5902 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005903
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005904 // If this terminator has multiple identical successors (common for
5905 // switches), only handle each succ once.
5906 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005907
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005908 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5909 PHINode *PN;
5910
5911 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5912 // nodes and Machine PHI nodes, but the incoming operands have not been
5913 // emitted yet.
5914 for (BasicBlock::iterator I = SuccBB->begin();
5915 (PN = dyn_cast<PHINode>(I)); ++I) {
5916 // Ignore dead phi's.
5917 if (PN->use_empty()) continue;
5918
5919 unsigned Reg;
5920 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5921
5922 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5923 unsigned &RegOut = SDL->ConstantsOut[C];
5924 if (RegOut == 0) {
5925 RegOut = FuncInfo->CreateRegForValue(C);
5926 SDL->CopyValueToVirtualRegister(C, RegOut);
5927 }
5928 Reg = RegOut;
5929 } else {
5930 Reg = FuncInfo->ValueMap[PHIOp];
5931 if (Reg == 0) {
5932 assert(isa<AllocaInst>(PHIOp) &&
5933 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5934 "Didn't codegen value into a register!??");
5935 Reg = FuncInfo->CreateRegForValue(PHIOp);
5936 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5937 }
5938 }
5939
5940 // Remember that this register needs to added to the machine PHI node as
5941 // the input for this MBB.
5942 SmallVector<MVT, 4> ValueVTs;
5943 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5944 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5945 MVT VT = ValueVTs[vti];
5946 unsigned NumRegisters = TLI.getNumRegisters(VT);
5947 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5948 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5949 Reg += NumRegisters;
5950 }
5951 }
5952 }
5953 SDL->ConstantsOut.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005954}
5955
Dan Gohman3df24e62008-09-03 23:12:08 +00005956/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5957/// supports legal types, and it emits MachineInstrs directly instead of
5958/// creating SelectionDAG nodes.
5959///
5960bool
5961SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5962 FastISel *F) {
5963 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005964
Dan Gohman3df24e62008-09-03 23:12:08 +00005965 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5966 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5967
5968 // Check successor nodes' PHI nodes that expect a constant to be available
5969 // from this block.
5970 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5971 BasicBlock *SuccBB = TI->getSuccessor(succ);
5972 if (!isa<PHINode>(SuccBB->begin())) continue;
5973 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005974
Dan Gohman3df24e62008-09-03 23:12:08 +00005975 // If this terminator has multiple identical successors (common for
5976 // switches), only handle each succ once.
5977 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005978
Dan Gohman3df24e62008-09-03 23:12:08 +00005979 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5980 PHINode *PN;
5981
5982 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5983 // nodes and Machine PHI nodes, but the incoming operands have not been
5984 // emitted yet.
5985 for (BasicBlock::iterator I = SuccBB->begin();
5986 (PN = dyn_cast<PHINode>(I)); ++I) {
5987 // Ignore dead phi's.
5988 if (PN->use_empty()) continue;
5989
5990 // Only handle legal types. Two interesting things to note here. First,
5991 // by bailing out early, we may leave behind some dead instructions,
5992 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5993 // own moves. Second, this check is necessary becuase FastISel doesn't
5994 // use CreateRegForValue to create registers, so it always creates
5995 // exactly one register for each non-void instruction.
5996 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5997 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
Dan Gohman74321ab2008-09-10 21:01:31 +00005998 // Promote MVT::i1.
5999 if (VT == MVT::i1)
6000 VT = TLI.getTypeToTransformTo(VT);
6001 else {
6002 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6003 return false;
6004 }
Dan Gohman3df24e62008-09-03 23:12:08 +00006005 }
6006
6007 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6008
6009 unsigned Reg = F->getRegForValue(PHIOp);
6010 if (Reg == 0) {
6011 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6012 return false;
6013 }
6014 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
6015 }
6016 }
6017
6018 return true;
6019}