blob: 260911e3b9940b11e58a51924155ebacdfafb55d [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);
Devang Patel7e1e31f2009-07-02 22:43:26 +0000335 if (isValidDebugInfoIntrinsic(*SPI, CodeGenOpt::Default))
336 DL = ExtractDebugLocation(*SPI, MF->getDebugLocInfo());
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000337 break;
338 }
339 case Intrinsic::dbg_func_start: {
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +0000340 DbgFuncStartInst *FSI = cast<DbgFuncStartInst>(I);
Devang Patel7e1e31f2009-07-02 22:43:26 +0000341 if (isValidDebugInfoIntrinsic(*FSI, CodeGenOpt::Default))
342 DL = ExtractDebugLocation(*FSI, MF->getDebugLocInfo());
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000343 break;
344 }
345 }
346 }
347 }
348
349 PN = dyn_cast<PHINode>(I);
350 if (!PN || PN->use_empty()) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000351
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000352 unsigned PHIReg = ValueMap[PN];
353 assert(PHIReg && "PHI node does not have an assigned virtual register!");
354
355 SmallVector<MVT, 4> ValueVTs;
356 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
357 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
358 MVT VT = ValueVTs[vti];
359 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohman6448d912008-09-04 15:39:15 +0000360 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000361 for (unsigned i = 0; i != NumRegisters; ++i)
Bill Wendling6a8a0d72009-02-03 02:20:52 +0000362 BuildMI(MBB, DL, TII->get(TargetInstrInfo::PHI), PHIReg + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000363 PHIReg += NumRegisters;
364 }
365 }
366 }
367}
368
369unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
370 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
371}
372
373/// CreateRegForValue - Allocate the appropriate number of virtual registers of
374/// the correctly promoted or expanded types. Assign these registers
375/// consecutive vreg numbers and return the first assigned number.
376///
377/// In the case that the given value has struct or array type, this function
378/// will assign registers for each member or element.
379///
380unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
381 SmallVector<MVT, 4> ValueVTs;
382 ComputeValueVTs(TLI, V->getType(), ValueVTs);
383
384 unsigned FirstReg = 0;
385 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
386 MVT ValueVT = ValueVTs[Value];
387 MVT RegisterVT = TLI.getRegisterType(ValueVT);
388
389 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
390 for (unsigned i = 0; i != NumRegs; ++i) {
391 unsigned R = MakeReg(RegisterVT);
392 if (!FirstReg) FirstReg = R;
393 }
394 }
395 return FirstReg;
396}
397
398/// getCopyFromParts - Create a value that contains the specified legal parts
399/// combined into the value they represent. If the parts combine to a type
400/// larger then ValueVT then AssertOp can be used to specify whether the extra
401/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
402/// (ISD::AssertSext).
Dale Johannesen66978ee2009-01-31 02:22:37 +0000403static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
404 const SDValue *Parts,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000405 unsigned NumParts, MVT PartVT, MVT ValueVT,
406 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000407 assert(NumParts > 0 && "No parts to assemble!");
Dan Gohmane9530ec2009-01-15 16:58:17 +0000408 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000409 SDValue Val = Parts[0];
410
411 if (NumParts > 1) {
412 // Assemble the value from multiple parts.
Eli Friedman2ac8b322009-05-20 06:02:09 +0000413 if (!ValueVT.isVector() && ValueVT.isInteger()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000414 unsigned PartBits = PartVT.getSizeInBits();
415 unsigned ValueBits = ValueVT.getSizeInBits();
416
417 // Assemble the power of 2 part.
418 unsigned RoundParts = NumParts & (NumParts - 1) ?
419 1 << Log2_32(NumParts) : NumParts;
420 unsigned RoundBits = PartBits * RoundParts;
421 MVT RoundVT = RoundBits == ValueBits ?
422 ValueVT : MVT::getIntegerVT(RoundBits);
423 SDValue Lo, Hi;
424
Eli Friedman2ac8b322009-05-20 06:02:09 +0000425 MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000426
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000427 if (RoundParts > 2) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000428 Lo = getCopyFromParts(DAG, dl, Parts, RoundParts/2, PartVT, HalfVT);
429 Hi = getCopyFromParts(DAG, dl, Parts+RoundParts/2, RoundParts/2,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000430 PartVT, HalfVT);
431 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000432 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
433 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000434 }
435 if (TLI.isBigEndian())
436 std::swap(Lo, Hi);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000437 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000438
439 if (RoundParts < NumParts) {
440 // Assemble the trailing non-power-of-2 part.
441 unsigned OddParts = NumParts - RoundParts;
442 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
Scott Michelfdc40a02009-02-17 22:15:04 +0000443 Hi = getCopyFromParts(DAG, dl,
Dale Johannesen66978ee2009-01-31 02:22:37 +0000444 Parts+RoundParts, OddParts, PartVT, OddVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000445
446 // Combine the round and odd parts.
447 Lo = Val;
448 if (TLI.isBigEndian())
449 std::swap(Lo, Hi);
450 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000451 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
452 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000453 DAG.getConstant(Lo.getValueType().getSizeInBits(),
Duncan Sands92abc622009-01-31 15:50:11 +0000454 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000455 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
456 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000457 }
Eli Friedman2ac8b322009-05-20 06:02:09 +0000458 } else if (ValueVT.isVector()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000459 // Handle a multi-element vector.
460 MVT IntermediateVT, RegisterVT;
461 unsigned NumIntermediates;
462 unsigned NumRegs =
463 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
464 RegisterVT);
465 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
466 NumParts = NumRegs; // Silence a compiler warning.
467 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
468 assert(RegisterVT == Parts[0].getValueType() &&
469 "Part type doesn't match part!");
470
471 // Assemble the parts into intermediate operands.
472 SmallVector<SDValue, 8> Ops(NumIntermediates);
473 if (NumIntermediates == NumParts) {
474 // If the register was not expanded, truncate or copy the value,
475 // as appropriate.
476 for (unsigned i = 0; i != NumParts; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000477 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000478 PartVT, IntermediateVT);
479 } else if (NumParts > 0) {
480 // If the intermediate type was expanded, build the intermediate operands
481 // from the parts.
482 assert(NumParts % NumIntermediates == 0 &&
483 "Must expand into a divisible number of parts!");
484 unsigned Factor = NumParts / NumIntermediates;
485 for (unsigned i = 0; i != NumIntermediates; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000486 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000487 PartVT, IntermediateVT);
488 }
489
490 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
491 // operands.
492 Val = DAG.getNode(IntermediateVT.isVector() ?
Dale Johannesen66978ee2009-01-31 02:22:37 +0000493 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000494 ValueVT, &Ops[0], NumIntermediates);
Eli Friedman2ac8b322009-05-20 06:02:09 +0000495 } else if (PartVT.isFloatingPoint()) {
496 // FP split into multiple FP parts (for ppcf128)
497 assert(ValueVT == MVT(MVT::ppcf128) && PartVT == MVT(MVT::f64) &&
498 "Unexpected split");
499 SDValue Lo, Hi;
500 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, MVT(MVT::f64), Parts[0]);
501 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, MVT(MVT::f64), Parts[1]);
502 if (TLI.isBigEndian())
503 std::swap(Lo, Hi);
504 Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi);
505 } else {
506 // FP split into integer parts (soft fp)
507 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
508 !PartVT.isVector() && "Unexpected split");
509 MVT IntVT = MVT::getIntegerVT(ValueVT.getSizeInBits());
510 Val = getCopyFromParts(DAG, dl, Parts, NumParts, PartVT, IntVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000511 }
512 }
513
514 // There is now one part, held in Val. Correct it to match ValueVT.
515 PartVT = Val.getValueType();
516
517 if (PartVT == ValueVT)
518 return Val;
519
520 if (PartVT.isVector()) {
521 assert(ValueVT.isVector() && "Unknown vector conversion!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000522 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000523 }
524
525 if (ValueVT.isVector()) {
526 assert(ValueVT.getVectorElementType() == PartVT &&
527 ValueVT.getVectorNumElements() == 1 &&
528 "Only trivial scalar-to-vector conversions should get here!");
Evan Chenga87008d2009-02-25 22:49:59 +0000529 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000530 }
531
532 if (PartVT.isInteger() &&
533 ValueVT.isInteger()) {
534 if (ValueVT.bitsLT(PartVT)) {
535 // For a truncate, see if we have any information to
536 // indicate whether the truncated bits will always be
537 // zero or sign-extension.
538 if (AssertOp != ISD::DELETED_NODE)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000539 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000540 DAG.getValueType(ValueVT));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000541 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000542 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000543 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000544 }
545 }
546
547 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
548 if (ValueVT.bitsLT(Val.getValueType()))
549 // FP_ROUND's are always exact here.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000550 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000551 DAG.getIntPtrConstant(1));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000552 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000553 }
554
555 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
Dale Johannesen66978ee2009-01-31 02:22:37 +0000556 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000557
558 assert(0 && "Unknown mismatch!");
559 return SDValue();
560}
561
562/// getCopyToParts - Create a series of nodes that contain the specified value
563/// split into legal parts. If the parts contain more bits than Val, then, for
564/// integers, ExtendKind can be used to specify how to generate the extra bits.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000565static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, SDValue Val,
Chris Lattner01426e12008-10-21 00:45:36 +0000566 SDValue *Parts, unsigned NumParts, MVT PartVT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000567 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
Dan Gohmane9530ec2009-01-15 16:58:17 +0000568 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000569 MVT PtrVT = TLI.getPointerTy();
570 MVT ValueVT = Val.getValueType();
571 unsigned PartBits = PartVT.getSizeInBits();
Dale Johannesen8a36f502009-02-25 22:39:13 +0000572 unsigned OrigNumParts = NumParts;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000573 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
574
575 if (!NumParts)
576 return;
577
578 if (!ValueVT.isVector()) {
579 if (PartVT == ValueVT) {
580 assert(NumParts == 1 && "No-op copy with multiple parts!");
581 Parts[0] = Val;
582 return;
583 }
584
585 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
586 // If the parts cover more bits than the value has, promote the value.
587 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
588 assert(NumParts == 1 && "Do not know what to promote to!");
Dale Johannesen66978ee2009-01-31 02:22:37 +0000589 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000590 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
591 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000592 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000593 } else {
594 assert(0 && "Unknown mismatch!");
595 }
596 } else if (PartBits == ValueVT.getSizeInBits()) {
597 // Different types of the same size.
598 assert(NumParts == 1 && PartVT != ValueVT);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000599 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000600 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
601 // If the parts cover less bits than value has, truncate the value.
602 if (PartVT.isInteger() && ValueVT.isInteger()) {
603 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000604 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000605 } else {
606 assert(0 && "Unknown mismatch!");
607 }
608 }
609
610 // The value may have changed - recompute ValueVT.
611 ValueVT = Val.getValueType();
612 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
613 "Failed to tile the value with PartVT!");
614
615 if (NumParts == 1) {
616 assert(PartVT == ValueVT && "Type conversion failed!");
617 Parts[0] = Val;
618 return;
619 }
620
621 // Expand the value into multiple parts.
622 if (NumParts & (NumParts - 1)) {
623 // The number of parts is not a power of 2. Split off and copy the tail.
624 assert(PartVT.isInteger() && ValueVT.isInteger() &&
625 "Do not know what to expand to!");
626 unsigned RoundParts = 1 << Log2_32(NumParts);
627 unsigned RoundBits = RoundParts * PartBits;
628 unsigned OddParts = NumParts - RoundParts;
Dale Johannesen66978ee2009-01-31 02:22:37 +0000629 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
Duncan Sands0b3aa262009-01-28 14:42:54 +0000630 DAG.getConstant(RoundBits,
Duncan Sands92abc622009-01-31 15:50:11 +0000631 TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +0000632 getCopyToParts(DAG, dl, OddVal, Parts + RoundParts, OddParts, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000633 if (TLI.isBigEndian())
634 // The odd parts were reversed by getCopyToParts - unreverse them.
635 std::reverse(Parts + RoundParts, Parts + NumParts);
636 NumParts = RoundParts;
637 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000638 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000639 }
640
641 // The number of parts is a power of 2. Repeatedly bisect the value using
642 // EXTRACT_ELEMENT.
Scott Michelfdc40a02009-02-17 22:15:04 +0000643 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000644 MVT::getIntegerVT(ValueVT.getSizeInBits()),
645 Val);
646 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
647 for (unsigned i = 0; i < NumParts; i += StepSize) {
648 unsigned ThisBits = StepSize * PartBits / 2;
649 MVT ThisVT = MVT::getIntegerVT (ThisBits);
650 SDValue &Part0 = Parts[i];
651 SDValue &Part1 = Parts[i+StepSize/2];
652
Scott Michelfdc40a02009-02-17 22:15:04 +0000653 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000654 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000655 DAG.getConstant(1, PtrVT));
Scott Michelfdc40a02009-02-17 22:15:04 +0000656 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000657 ThisVT, Part0,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000658 DAG.getConstant(0, PtrVT));
659
660 if (ThisBits == PartBits && ThisVT != PartVT) {
Scott Michelfdc40a02009-02-17 22:15:04 +0000661 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000662 PartVT, Part0);
Scott Michelfdc40a02009-02-17 22:15:04 +0000663 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000664 PartVT, Part1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000665 }
666 }
667 }
668
669 if (TLI.isBigEndian())
Dale Johannesen8a36f502009-02-25 22:39:13 +0000670 std::reverse(Parts, Parts + OrigNumParts);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000671
672 return;
673 }
674
675 // Vector ValueVT.
676 if (NumParts == 1) {
677 if (PartVT != ValueVT) {
678 if (PartVT.isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +0000679 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000680 } else {
681 assert(ValueVT.getVectorElementType() == PartVT &&
682 ValueVT.getVectorNumElements() == 1 &&
683 "Only trivial vector-to-scalar conversions should get here!");
Scott Michelfdc40a02009-02-17 22:15:04 +0000684 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000685 PartVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000686 DAG.getConstant(0, PtrVT));
687 }
688 }
689
690 Parts[0] = Val;
691 return;
692 }
693
694 // Handle a multi-element vector.
695 MVT IntermediateVT, RegisterVT;
696 unsigned NumIntermediates;
Dan Gohmane9530ec2009-01-15 16:58:17 +0000697 unsigned NumRegs = TLI
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000698 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
699 RegisterVT);
700 unsigned NumElements = ValueVT.getVectorNumElements();
701
702 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
703 NumParts = NumRegs; // Silence a compiler warning.
704 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
705
706 // Split the vector into intermediate operands.
707 SmallVector<SDValue, 8> Ops(NumIntermediates);
708 for (unsigned i = 0; i != NumIntermediates; ++i)
709 if (IntermediateVT.isVector())
Scott Michelfdc40a02009-02-17 22:15:04 +0000710 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000711 IntermediateVT, Val,
712 DAG.getConstant(i * (NumElements / NumIntermediates),
713 PtrVT));
714 else
Scott Michelfdc40a02009-02-17 22:15:04 +0000715 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000716 IntermediateVT, Val,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000717 DAG.getConstant(i, PtrVT));
718
719 // Split the intermediate operands into legal parts.
720 if (NumParts == NumIntermediates) {
721 // If the register was not expanded, promote or copy the value,
722 // as appropriate.
723 for (unsigned i = 0; i != NumParts; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000724 getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000725 } else if (NumParts > 0) {
726 // If the intermediate type was expanded, split each the value into
727 // legal parts.
728 assert(NumParts % NumIntermediates == 0 &&
729 "Must expand into a divisible number of parts!");
730 unsigned Factor = NumParts / NumIntermediates;
731 for (unsigned i = 0; i != NumIntermediates; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +0000732 getCopyToParts(DAG, dl, Ops[i], &Parts[i * Factor], Factor, PartVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000733 }
734}
735
736
737void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
738 AA = &aa;
739 GFI = gfi;
740 TD = DAG.getTarget().getTargetData();
741}
742
743/// clear - Clear out the curret SelectionDAG and the associated
744/// state and prepare this SelectionDAGLowering object to be used
745/// for a new block. This doesn't clear out information about
746/// additional blocks that are needed to complete switch lowering
747/// or PHI node updating; that information is cleared out as it is
748/// consumed.
749void SelectionDAGLowering::clear() {
750 NodeMap.clear();
751 PendingLoads.clear();
752 PendingExports.clear();
753 DAG.clear();
Bill Wendling8fcf1702009-02-06 21:36:23 +0000754 CurDebugLoc = DebugLoc::getUnknownLoc();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000755}
756
757/// getRoot - Return the current virtual root of the Selection DAG,
758/// flushing any PendingLoad items. This must be done before emitting
759/// a store or any other node that may need to be ordered after any
760/// prior load instructions.
761///
762SDValue SelectionDAGLowering::getRoot() {
763 if (PendingLoads.empty())
764 return DAG.getRoot();
765
766 if (PendingLoads.size() == 1) {
767 SDValue Root = PendingLoads[0];
768 DAG.setRoot(Root);
769 PendingLoads.clear();
770 return Root;
771 }
772
773 // Otherwise, we have to make a token factor node.
Dale Johannesen66978ee2009-01-31 02:22:37 +0000774 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000775 &PendingLoads[0], PendingLoads.size());
776 PendingLoads.clear();
777 DAG.setRoot(Root);
778 return Root;
779}
780
781/// getControlRoot - Similar to getRoot, but instead of flushing all the
782/// PendingLoad items, flush all the PendingExports items. It is necessary
783/// to do this before emitting a terminator instruction.
784///
785SDValue SelectionDAGLowering::getControlRoot() {
786 SDValue Root = DAG.getRoot();
787
788 if (PendingExports.empty())
789 return Root;
790
791 // Turn all of the CopyToReg chains into one factored node.
792 if (Root.getOpcode() != ISD::EntryToken) {
793 unsigned i = 0, e = PendingExports.size();
794 for (; i != e; ++i) {
795 assert(PendingExports[i].getNode()->getNumOperands() > 1);
796 if (PendingExports[i].getNode()->getOperand(0) == Root)
797 break; // Don't add the root if we already indirectly depend on it.
798 }
799
800 if (i == e)
801 PendingExports.push_back(Root);
802 }
803
Dale Johannesen66978ee2009-01-31 02:22:37 +0000804 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000805 &PendingExports[0],
806 PendingExports.size());
807 PendingExports.clear();
808 DAG.setRoot(Root);
809 return Root;
810}
811
812void SelectionDAGLowering::visit(Instruction &I) {
813 visit(I.getOpcode(), I);
814}
815
816void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
817 // Note: this doesn't use InstVisitor, because it has to work with
818 // ConstantExpr's in addition to instructions.
819 switch (Opcode) {
820 default: assert(0 && "Unknown instruction type encountered!");
821 abort();
822 // Build the switch statement using the Instruction.def file.
823#define HANDLE_INST(NUM, OPCODE, CLASS) \
824 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
825#include "llvm/Instruction.def"
826 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000827}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000828
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000829SDValue SelectionDAGLowering::getValue(const Value *V) {
830 SDValue &N = NodeMap[V];
831 if (N.getNode()) return N;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000832
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000833 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
834 MVT VT = TLI.getValueType(V->getType(), true);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000835
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000836 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000837 return N = DAG.getConstant(*CI, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000838
839 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
840 return N = DAG.getGlobalAddress(GV, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000841
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000842 if (isa<ConstantPointerNull>(C))
843 return N = DAG.getConstant(0, TLI.getPointerTy());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000844
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000845 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000846 return N = DAG.getConstantFP(*CFP, VT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000847
Nate Begeman9008ca62009-04-27 18:41:29 +0000848 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
Dale Johannesene8d72302009-02-06 23:05:02 +0000849 return N = DAG.getUNDEF(VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000850
851 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
852 visit(CE->getOpcode(), *CE);
853 SDValue N1 = NodeMap[V];
854 assert(N1.getNode() && "visit didn't populate the ValueMap!");
855 return N1;
856 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000857
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000858 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
859 SmallVector<SDValue, 4> Constants;
860 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
861 OI != OE; ++OI) {
862 SDNode *Val = getValue(*OI).getNode();
863 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
864 Constants.push_back(SDValue(Val, i));
865 }
Dale Johannesen4be0bdf2009-02-05 00:20:09 +0000866 return DAG.getMergeValues(&Constants[0], Constants.size(),
867 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000868 }
869
870 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
871 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
872 "Unknown struct or array constant!");
873
874 SmallVector<MVT, 4> ValueVTs;
875 ComputeValueVTs(TLI, C->getType(), ValueVTs);
876 unsigned NumElts = ValueVTs.size();
877 if (NumElts == 0)
878 return SDValue(); // empty struct
879 SmallVector<SDValue, 4> Constants(NumElts);
880 for (unsigned i = 0; i != NumElts; ++i) {
881 MVT EltVT = ValueVTs[i];
882 if (isa<UndefValue>(C))
Dale Johannesene8d72302009-02-06 23:05:02 +0000883 Constants[i] = DAG.getUNDEF(EltVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000884 else if (EltVT.isFloatingPoint())
885 Constants[i] = DAG.getConstantFP(0, EltVT);
886 else
887 Constants[i] = DAG.getConstant(0, EltVT);
888 }
Dale Johannesen4be0bdf2009-02-05 00:20:09 +0000889 return DAG.getMergeValues(&Constants[0], NumElts, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000890 }
891
892 const VectorType *VecTy = cast<VectorType>(V->getType());
893 unsigned NumElements = VecTy->getNumElements();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000894
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000895 // Now that we know the number and type of the elements, get that number of
896 // elements into the Ops array based on what kind of constant it is.
897 SmallVector<SDValue, 16> Ops;
898 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
899 for (unsigned i = 0; i != NumElements; ++i)
900 Ops.push_back(getValue(CP->getOperand(i)));
901 } else {
Nate Begeman9008ca62009-04-27 18:41:29 +0000902 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000903 MVT EltVT = TLI.getValueType(VecTy->getElementType());
904
905 SDValue Op;
Nate Begeman9008ca62009-04-27 18:41:29 +0000906 if (EltVT.isFloatingPoint())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000907 Op = DAG.getConstantFP(0, EltVT);
908 else
909 Op = DAG.getConstant(0, EltVT);
910 Ops.assign(NumElements, Op);
911 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000912
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000913 // Create a BUILD_VECTOR node.
Evan Chenga87008d2009-02-25 22:49:59 +0000914 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
915 VT, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000916 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000917
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000918 // If this is a static alloca, generate it as the frameindex instead of
919 // computation.
920 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
921 DenseMap<const AllocaInst*, int>::iterator SI =
922 FuncInfo.StaticAllocaMap.find(AI);
923 if (SI != FuncInfo.StaticAllocaMap.end())
924 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
925 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000926
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000927 unsigned InReg = FuncInfo.ValueMap[V];
928 assert(InReg && "Value not in map!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000929
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000930 RegsForValue RFV(TLI, InReg, V->getType());
931 SDValue Chain = DAG.getEntryNode();
Dale Johannesen66978ee2009-01-31 02:22:37 +0000932 return RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000933}
934
935
936void SelectionDAGLowering::visitRet(ReturnInst &I) {
937 if (I.getNumOperands() == 0) {
Scott Michelfdc40a02009-02-17 22:15:04 +0000938 DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +0000939 MVT::Other, getControlRoot()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000940 return;
941 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000942
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000943 SmallVector<SDValue, 8> NewValues;
944 NewValues.push_back(getControlRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000945 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000946 SmallVector<MVT, 4> ValueVTs;
947 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
Dan Gohman7ea1ca62008-10-21 20:00:42 +0000948 unsigned NumValues = ValueVTs.size();
949 if (NumValues == 0) continue;
950
951 SDValue RetOp = getValue(I.getOperand(i));
952 for (unsigned j = 0, f = NumValues; j != f; ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000953 MVT VT = ValueVTs[j];
954
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000955 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000956
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000957 const Function *F = I.getParent()->getParent();
Devang Patel05988662008-09-25 21:00:45 +0000958 if (F->paramHasAttr(0, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000959 ExtendKind = ISD::SIGN_EXTEND;
Devang Patel05988662008-09-25 21:00:45 +0000960 else if (F->paramHasAttr(0, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000961 ExtendKind = ISD::ZERO_EXTEND;
962
Evan Cheng3927f432009-03-25 20:20:11 +0000963 // FIXME: C calling convention requires the return type to be promoted to
964 // at least 32-bit. But this is not necessary for non-C calling
965 // conventions. The frontend should mark functions whose return values
966 // require promoting with signext or zeroext attributes.
967 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
968 MVT MinVT = TLI.getRegisterType(MVT::i32);
969 if (VT.bitsLT(MinVT))
970 VT = MinVT;
971 }
972
973 unsigned NumParts = TLI.getNumRegisters(VT);
974 MVT PartVT = TLI.getRegisterType(VT);
975 SmallVector<SDValue, 4> Parts(NumParts);
Dale Johannesen66978ee2009-01-31 02:22:37 +0000976 getCopyToParts(DAG, getCurDebugLoc(),
977 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000978 &Parts[0], NumParts, PartVT, ExtendKind);
979
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000980 // 'inreg' on function refers to return value
981 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Devang Patel05988662008-09-25 21:00:45 +0000982 if (F->paramHasAttr(0, Attribute::InReg))
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000983 Flags.setInReg();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000984 for (unsigned i = 0; i < NumParts; ++i) {
985 NewValues.push_back(Parts[i]);
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000986 NewValues.push_back(DAG.getArgFlags(Flags));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000987 }
988 }
989 }
Dale Johannesen66978ee2009-01-31 02:22:37 +0000990 DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000991 &NewValues[0], NewValues.size()));
992}
993
Dan Gohmanad62f532009-04-23 23:13:24 +0000994/// CopyToExportRegsIfNeeded - If the given value has virtual registers
995/// created for it, emit nodes to copy the value into the virtual
996/// registers.
997void SelectionDAGLowering::CopyToExportRegsIfNeeded(Value *V) {
998 if (!V->use_empty()) {
999 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1000 if (VMI != FuncInfo.ValueMap.end())
1001 CopyValueToVirtualRegister(V, VMI->second);
1002 }
1003}
1004
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001005/// ExportFromCurrentBlock - If this condition isn't known to be exported from
1006/// the current basic block, add it to ValueMap now so that we'll get a
1007/// CopyTo/FromReg.
1008void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1009 // No need to export constants.
1010 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001011
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001012 // Already exported?
1013 if (FuncInfo.isExportedInst(V)) return;
1014
1015 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1016 CopyValueToVirtualRegister(V, Reg);
1017}
1018
1019bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1020 const BasicBlock *FromBB) {
1021 // The operands of the setcc have to be in this block. We don't know
1022 // how to export them from some other block.
1023 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1024 // Can export from current BB.
1025 if (VI->getParent() == FromBB)
1026 return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001027
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001028 // Is already exported, noop.
1029 return FuncInfo.isExportedInst(V);
1030 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001031
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001032 // If this is an argument, we can export it if the BB is the entry block or
1033 // if it is already exported.
1034 if (isa<Argument>(V)) {
1035 if (FromBB == &FromBB->getParent()->getEntryBlock())
1036 return true;
1037
1038 // Otherwise, can only export this if it is already exported.
1039 return FuncInfo.isExportedInst(V);
1040 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001041
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001042 // Otherwise, constants can always be exported.
1043 return true;
1044}
1045
1046static bool InBlock(const Value *V, const BasicBlock *BB) {
1047 if (const Instruction *I = dyn_cast<Instruction>(V))
1048 return I->getParent() == BB;
1049 return true;
1050}
1051
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001052/// getFCmpCondCode - Return the ISD condition code corresponding to
1053/// the given LLVM IR floating-point condition code. This includes
1054/// consideration of global floating-point math flags.
1055///
1056static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1057 ISD::CondCode FPC, FOC;
1058 switch (Pred) {
1059 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1060 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1061 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1062 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1063 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1064 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1065 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1066 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1067 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1068 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1069 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1070 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1071 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1072 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1073 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1074 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1075 default:
1076 assert(0 && "Invalid FCmp predicate opcode!");
1077 FOC = FPC = ISD::SETFALSE;
1078 break;
1079 }
1080 if (FiniteOnlyFPMath())
1081 return FOC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001082 else
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001083 return FPC;
1084}
1085
1086/// getICmpCondCode - Return the ISD condition code corresponding to
1087/// the given LLVM IR integer condition code.
1088///
1089static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1090 switch (Pred) {
1091 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1092 case ICmpInst::ICMP_NE: return ISD::SETNE;
1093 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1094 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1095 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1096 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1097 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1098 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1099 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1100 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1101 default:
1102 assert(0 && "Invalid ICmp predicate opcode!");
1103 return ISD::SETNE;
1104 }
1105}
1106
Dan Gohmanc2277342008-10-17 21:16:08 +00001107/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1108/// This function emits a branch and is used at the leaves of an OR or an
1109/// AND operator tree.
1110///
1111void
1112SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1113 MachineBasicBlock *TBB,
1114 MachineBasicBlock *FBB,
1115 MachineBasicBlock *CurBB) {
1116 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001117
Dan Gohmanc2277342008-10-17 21:16:08 +00001118 // If the leaf of the tree is a comparison, merge the condition into
1119 // the caseblock.
1120 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1121 // The operands of the cmp have to be in this block. We don't know
1122 // how to export them from some other block. If this is the first block
1123 // of the sequence, no exporting is needed.
1124 if (CurBB == CurMBB ||
1125 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1126 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001127 ISD::CondCode Condition;
1128 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001129 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001130 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001131 Condition = getFCmpCondCode(FC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001132 } else {
1133 Condition = ISD::SETEQ; // silence warning.
1134 assert(0 && "Unknown compare instruction");
1135 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001136
1137 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001138 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1139 SwitchCases.push_back(CB);
1140 return;
1141 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001142 }
1143
1144 // Create a CaseBlock record representing this branch.
1145 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1146 NULL, TBB, FBB, CurBB);
1147 SwitchCases.push_back(CB);
1148}
1149
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001150/// FindMergedConditions - If Cond is an expression like
Dan Gohmanc2277342008-10-17 21:16:08 +00001151void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1152 MachineBasicBlock *TBB,
1153 MachineBasicBlock *FBB,
1154 MachineBasicBlock *CurBB,
1155 unsigned Opc) {
1156 // If this node is not part of the or/and tree, emit it as a branch.
1157 Instruction *BOp = dyn_cast<Instruction>(Cond);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001158 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
Dan Gohmanc2277342008-10-17 21:16:08 +00001159 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1160 BOp->getParent() != CurBB->getBasicBlock() ||
1161 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1162 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1163 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001164 return;
1165 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001166
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001167 // Create TmpBB after CurBB.
1168 MachineFunction::iterator BBI = CurBB;
1169 MachineFunction &MF = DAG.getMachineFunction();
1170 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1171 CurBB->getParent()->insert(++BBI, TmpBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001172
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001173 if (Opc == Instruction::Or) {
1174 // Codegen X | Y as:
1175 // jmp_if_X TBB
1176 // jmp TmpBB
1177 // TmpBB:
1178 // jmp_if_Y TBB
1179 // jmp FBB
1180 //
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001181
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001182 // Emit the LHS condition.
1183 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001184
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001185 // Emit the RHS condition into TmpBB.
1186 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1187 } else {
1188 assert(Opc == Instruction::And && "Unknown merge op!");
1189 // Codegen X & Y as:
1190 // jmp_if_X TmpBB
1191 // jmp FBB
1192 // TmpBB:
1193 // jmp_if_Y TBB
1194 // jmp FBB
1195 //
1196 // This requires creation of TmpBB after CurBB.
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), TmpBB, FBB, 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 }
1204}
1205
1206/// If the set of cases should be emitted as a series of branches, return true.
1207/// If we should emit this as a bunch of and/or'd together conditions, return
1208/// false.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001209bool
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001210SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1211 if (Cases.size() != 2) return true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001212
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001213 // If this is two comparisons of the same values or'd or and'd together, they
1214 // will get folded into a single comparison, so don't emit two blocks.
1215 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1216 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1217 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1218 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1219 return false;
1220 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001221
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001222 return true;
1223}
1224
1225void SelectionDAGLowering::visitBr(BranchInst &I) {
1226 // Update machine-CFG edges.
1227 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1228
1229 // Figure out which block is immediately after the current one.
1230 MachineBasicBlock *NextBlock = 0;
1231 MachineFunction::iterator BBI = CurMBB;
1232 if (++BBI != CurMBB->getParent()->end())
1233 NextBlock = BBI;
1234
1235 if (I.isUnconditional()) {
1236 // Update machine-CFG edges.
1237 CurMBB->addSuccessor(Succ0MBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001238
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001239 // If this is not a fall-through branch, emit the branch.
1240 if (Succ0MBB != NextBlock)
Scott Michelfdc40a02009-02-17 22:15:04 +00001241 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001242 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001243 DAG.getBasicBlock(Succ0MBB)));
1244 return;
1245 }
1246
1247 // If this condition is one of the special cases we handle, do special stuff
1248 // now.
1249 Value *CondVal = I.getCondition();
1250 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1251
1252 // If this is a series of conditions that are or'd or and'd together, emit
1253 // this as a sequence of branches instead of setcc's with and/or operations.
1254 // For example, instead of something like:
1255 // cmp A, B
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001256 // C = seteq
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001257 // cmp D, E
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001258 // F = setle
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001259 // or C, F
1260 // jnz foo
1261 // Emit:
1262 // cmp A, B
1263 // je foo
1264 // cmp D, E
1265 // jle foo
1266 //
1267 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001268 if (BOp->hasOneUse() &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001269 (BOp->getOpcode() == Instruction::And ||
1270 BOp->getOpcode() == Instruction::Or)) {
1271 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1272 // If the compares in later blocks need to use values not currently
1273 // exported from this block, export them now. This block should always
1274 // be the first entry.
1275 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001276
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001277 // Allow some cases to be rejected.
1278 if (ShouldEmitAsBranches(SwitchCases)) {
1279 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1280 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1281 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1282 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001283
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001284 // Emit the branch for this block.
1285 visitSwitchCase(SwitchCases[0]);
1286 SwitchCases.erase(SwitchCases.begin());
1287 return;
1288 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001289
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001290 // Okay, we decided not to do this, remove any inserted MBB's and clear
1291 // SwitchCases.
1292 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1293 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001294
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001295 SwitchCases.clear();
1296 }
1297 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001298
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001299 // Create a CaseBlock record representing this branch.
1300 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1301 NULL, Succ0MBB, Succ1MBB, CurMBB);
1302 // Use visitSwitchCase to actually insert the fast branch sequence for this
1303 // cond branch.
1304 visitSwitchCase(CB);
1305}
1306
1307/// visitSwitchCase - Emits the necessary code to represent a single node in
1308/// the binary search tree resulting from lowering a switch instruction.
1309void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1310 SDValue Cond;
1311 SDValue CondLHS = getValue(CB.CmpLHS);
Dale Johannesenf5d97892009-02-04 01:48:28 +00001312 DebugLoc dl = getCurDebugLoc();
Anton Korobeynikov23218582008-12-23 22:25:27 +00001313
1314 // Build the setcc now.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001315 if (CB.CmpMHS == NULL) {
1316 // Fold "(X == true)" to X and "(X == false)" to !X to
1317 // handle common cases produced by branch lowering.
1318 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1319 Cond = CondLHS;
1320 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1321 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001322 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001323 } else
Dale Johannesenf5d97892009-02-04 01:48:28 +00001324 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001325 } else {
1326 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1327
Anton Korobeynikov23218582008-12-23 22:25:27 +00001328 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1329 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001330
1331 SDValue CmpOp = getValue(CB.CmpMHS);
1332 MVT VT = CmpOp.getValueType();
1333
1334 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
Scott Michelfdc40a02009-02-17 22:15:04 +00001335 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
Dale Johannesenf5d97892009-02-04 01:48:28 +00001336 ISD::SETLE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001337 } else {
Dale Johannesenf5d97892009-02-04 01:48:28 +00001338 SDValue SUB = DAG.getNode(ISD::SUB, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001339 VT, CmpOp, DAG.getConstant(Low, VT));
Dale Johannesenf5d97892009-02-04 01:48:28 +00001340 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001341 DAG.getConstant(High-Low, VT), ISD::SETULE);
1342 }
1343 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001344
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001345 // Update successor info
1346 CurMBB->addSuccessor(CB.TrueBB);
1347 CurMBB->addSuccessor(CB.FalseBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001348
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001349 // Set NextBlock to be the MBB immediately after the current one, if any.
1350 // This is used to avoid emitting unnecessary branches to the next block.
1351 MachineBasicBlock *NextBlock = 0;
1352 MachineFunction::iterator BBI = CurMBB;
1353 if (++BBI != CurMBB->getParent()->end())
1354 NextBlock = BBI;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001355
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001356 // If the lhs block is the next block, invert the condition so that we can
1357 // fall through to the lhs instead of the rhs block.
1358 if (CB.TrueBB == NextBlock) {
1359 std::swap(CB.TrueBB, CB.FalseBB);
1360 SDValue True = DAG.getConstant(1, Cond.getValueType());
Dale Johannesenf5d97892009-02-04 01:48:28 +00001361 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001362 }
Dale Johannesenf5d97892009-02-04 01:48:28 +00001363 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001364 MVT::Other, getControlRoot(), Cond,
1365 DAG.getBasicBlock(CB.TrueBB));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001366
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001367 // If the branch was constant folded, fix up the CFG.
1368 if (BrCond.getOpcode() == ISD::BR) {
1369 CurMBB->removeSuccessor(CB.FalseBB);
1370 DAG.setRoot(BrCond);
1371 } else {
1372 // Otherwise, go ahead and insert the false branch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001373 if (BrCond == getControlRoot())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001374 CurMBB->removeSuccessor(CB.TrueBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001375
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001376 if (CB.FalseBB == NextBlock)
1377 DAG.setRoot(BrCond);
1378 else
Dale Johannesenf5d97892009-02-04 01:48:28 +00001379 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001380 DAG.getBasicBlock(CB.FalseBB)));
1381 }
1382}
1383
1384/// visitJumpTable - Emit JumpTable node in the current MBB
1385void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1386 // Emit the code for the jump table
1387 assert(JT.Reg != -1U && "Should lower JT Header first!");
1388 MVT PTy = TLI.getPointerTy();
Dale Johannesena04b7572009-02-03 23:04:43 +00001389 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1390 JT.Reg, PTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001391 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
Scott Michelfdc40a02009-02-17 22:15:04 +00001392 DAG.setRoot(DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001393 MVT::Other, Index.getValue(1),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001394 Table, Index));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001395}
1396
1397/// visitJumpTableHeader - This function emits necessary code to produce index
1398/// in the JumpTable from switch case.
1399void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1400 JumpTableHeader &JTH) {
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001401 // Subtract the lowest switch case value from the value being switched on and
1402 // conditional branch to default mbb if the result is greater than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001403 // difference between smallest and largest cases.
1404 SDValue SwitchOp = getValue(JTH.SValue);
1405 MVT VT = SwitchOp.getValueType();
Dale Johannesen66978ee2009-01-31 02:22:37 +00001406 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001407 DAG.getConstant(JTH.First, VT));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001408
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001409 // The SDNode we just created, which holds the value being switched on minus
1410 // the the smallest case value, needs to be copied to a virtual register so it
1411 // can be used as an index into the jump table in a subsequent basic block.
1412 // This value may be smaller or larger than the target's pointer type, and
1413 // therefore require extension or truncating.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001414 if (VT.bitsGT(TLI.getPointerTy()))
Scott Michelfdc40a02009-02-17 22:15:04 +00001415 SwitchOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001416 TLI.getPointerTy(), SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001417 else
Scott Michelfdc40a02009-02-17 22:15:04 +00001418 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001419 TLI.getPointerTy(), SUB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001420
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001421 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001422 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1423 JumpTableReg, SwitchOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001424 JT.Reg = JumpTableReg;
1425
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001426 // Emit the range check for the jump table, and branch to the default block
1427 // for the switch statement if the value being switched on exceeds the largest
1428 // case in the switch.
Dale Johannesenf5d97892009-02-04 01:48:28 +00001429 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1430 TLI.getSetCCResultType(SUB.getValueType()), SUB,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001431 DAG.getConstant(JTH.Last-JTH.First,VT),
1432 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001433
1434 // Set NextBlock to be the MBB immediately after the current one, if any.
1435 // This is used to avoid emitting unnecessary branches to the next block.
1436 MachineBasicBlock *NextBlock = 0;
1437 MachineFunction::iterator BBI = CurMBB;
1438 if (++BBI != CurMBB->getParent()->end())
1439 NextBlock = BBI;
1440
Dale Johannesen66978ee2009-01-31 02:22:37 +00001441 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001442 MVT::Other, CopyTo, CMP,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001443 DAG.getBasicBlock(JT.Default));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001444
1445 if (JT.MBB == NextBlock)
1446 DAG.setRoot(BrCond);
1447 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001448 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001449 DAG.getBasicBlock(JT.MBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001450}
1451
1452/// visitBitTestHeader - This function emits necessary code to produce value
1453/// suitable for "bit tests"
1454void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1455 // Subtract the minimum value
1456 SDValue SwitchOp = getValue(B.SValue);
1457 MVT VT = SwitchOp.getValueType();
Dale Johannesen66978ee2009-01-31 02:22:37 +00001458 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001459 DAG.getConstant(B.First, VT));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001460
1461 // Check range
Dale Johannesenf5d97892009-02-04 01:48:28 +00001462 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1463 TLI.getSetCCResultType(SUB.getValueType()),
1464 SUB, DAG.getConstant(B.Range, VT),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001465 ISD::SETUGT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001466
1467 SDValue ShiftOp;
Duncan Sands92abc622009-01-31 15:50:11 +00001468 if (VT.bitsGT(TLI.getPointerTy()))
Scott Michelfdc40a02009-02-17 22:15:04 +00001469 ShiftOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00001470 TLI.getPointerTy(), SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001471 else
Scott Michelfdc40a02009-02-17 22:15:04 +00001472 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00001473 TLI.getPointerTy(), SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001474
Duncan Sands92abc622009-01-31 15:50:11 +00001475 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
Dale Johannesena04b7572009-02-03 23:04:43 +00001476 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1477 B.Reg, ShiftOp);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001478
1479 // Set NextBlock to be the MBB immediately after the current one, if any.
1480 // This is used to avoid emitting unnecessary branches to the next block.
1481 MachineBasicBlock *NextBlock = 0;
1482 MachineFunction::iterator BBI = CurMBB;
1483 if (++BBI != CurMBB->getParent()->end())
1484 NextBlock = BBI;
1485
1486 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1487
1488 CurMBB->addSuccessor(B.Default);
1489 CurMBB->addSuccessor(MBB);
1490
Dale Johannesen66978ee2009-01-31 02:22:37 +00001491 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001492 MVT::Other, CopyTo, RangeCmp,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001493 DAG.getBasicBlock(B.Default));
Anton Korobeynikov23218582008-12-23 22:25:27 +00001494
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001495 if (MBB == NextBlock)
1496 DAG.setRoot(BrRange);
1497 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001498 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001499 DAG.getBasicBlock(MBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001500}
1501
1502/// visitBitTestCase - this function produces one "bit test"
1503void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1504 unsigned Reg,
1505 BitTestCase &B) {
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001506 // Make desired shift
Dale Johannesena04b7572009-02-03 23:04:43 +00001507 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
Duncan Sands92abc622009-01-31 15:50:11 +00001508 TLI.getPointerTy());
Scott Michelfdc40a02009-02-17 22:15:04 +00001509 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001510 TLI.getPointerTy(),
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001511 DAG.getConstant(1, TLI.getPointerTy()),
1512 ShiftOp);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001513
Anton Korobeynikov36c826a2009-01-26 19:26:01 +00001514 // Emit bit tests and jumps
Scott Michelfdc40a02009-02-17 22:15:04 +00001515 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001516 TLI.getPointerTy(), SwitchVal,
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001517 DAG.getConstant(B.Mask, TLI.getPointerTy()));
Dale Johannesenf5d97892009-02-04 01:48:28 +00001518 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1519 TLI.getSetCCResultType(AndOp.getValueType()),
Duncan Sands5480c042009-01-01 15:52:00 +00001520 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001521 ISD::SETNE);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001522
1523 CurMBB->addSuccessor(B.TargetBB);
1524 CurMBB->addSuccessor(NextMBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001525
Dale Johannesen66978ee2009-01-31 02:22:37 +00001526 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001527 MVT::Other, getControlRoot(),
Anton Korobeynikov1bfe2372008-12-23 22:25:45 +00001528 AndCmp, DAG.getBasicBlock(B.TargetBB));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001529
1530 // Set NextBlock to be the MBB immediately after the current one, if any.
1531 // This is used to avoid emitting unnecessary branches to the next block.
1532 MachineBasicBlock *NextBlock = 0;
1533 MachineFunction::iterator BBI = CurMBB;
1534 if (++BBI != CurMBB->getParent()->end())
1535 NextBlock = BBI;
1536
1537 if (NextMBB == NextBlock)
1538 DAG.setRoot(BrAnd);
1539 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00001540 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001541 DAG.getBasicBlock(NextMBB)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001542}
1543
1544void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1545 // Retrieve successors.
1546 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1547 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1548
Gabor Greifb67e6b32009-01-15 11:10:44 +00001549 const Value *Callee(I.getCalledValue());
1550 if (isa<InlineAsm>(Callee))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001551 visitInlineAsm(&I);
1552 else
Gabor Greifb67e6b32009-01-15 11:10:44 +00001553 LowerCallTo(&I, getValue(Callee), false, LandingPad);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001554
1555 // If the value of the invoke is used outside of its defining block, make it
1556 // available as a virtual register.
Dan Gohmanad62f532009-04-23 23:13:24 +00001557 CopyToExportRegsIfNeeded(&I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001558
1559 // Update successor info
1560 CurMBB->addSuccessor(Return);
1561 CurMBB->addSuccessor(LandingPad);
1562
1563 // Drop into normal successor.
Scott Michelfdc40a02009-02-17 22:15:04 +00001564 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00001565 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001566 DAG.getBasicBlock(Return)));
1567}
1568
1569void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1570}
1571
1572/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1573/// small case ranges).
1574bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1575 CaseRecVector& WorkList,
1576 Value* SV,
1577 MachineBasicBlock* Default) {
1578 Case& BackCase = *(CR.Range.second-1);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001579
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001580 // Size is the number of Cases represented by this range.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001581 size_t Size = CR.Range.second - CR.Range.first;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001582 if (Size > 3)
Anton Korobeynikov23218582008-12-23 22:25:27 +00001583 return false;
1584
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001585 // Get the MachineFunction which holds the current MBB. This is used when
1586 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001587 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001588
1589 // Figure out which block is immediately after the current one.
1590 MachineBasicBlock *NextBlock = 0;
1591 MachineFunction::iterator BBI = CR.CaseBB;
1592
1593 if (++BBI != CurMBB->getParent()->end())
1594 NextBlock = BBI;
1595
1596 // TODO: If any two of the cases has the same destination, and if one value
1597 // is the same as the other, but has one bit unset that the other has set,
1598 // use bit manipulation to do two compares at once. For example:
1599 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
Anton Korobeynikov23218582008-12-23 22:25:27 +00001600
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001601 // Rearrange the case blocks so that the last one falls through if possible.
1602 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1603 // The last case block won't fall through into 'NextBlock' if we emit the
1604 // branches in this order. See if rearranging a case value would help.
1605 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1606 if (I->BB == NextBlock) {
1607 std::swap(*I, BackCase);
1608 break;
1609 }
1610 }
1611 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001612
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001613 // Create a CaseBlock record representing a conditional branch to
1614 // the Case's target mbb if the value being switched on SV is equal
1615 // to C.
1616 MachineBasicBlock *CurBlock = CR.CaseBB;
1617 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1618 MachineBasicBlock *FallThrough;
1619 if (I != E-1) {
1620 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1621 CurMF->insert(BBI, FallThrough);
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001622
1623 // Put SV in a virtual register to make it available from the new blocks.
1624 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001625 } else {
1626 // If the last case doesn't match, go to the default block.
1627 FallThrough = Default;
1628 }
1629
1630 Value *RHS, *LHS, *MHS;
1631 ISD::CondCode CC;
1632 if (I->High == I->Low) {
1633 // This is just small small case range :) containing exactly 1 case
1634 CC = ISD::SETEQ;
1635 LHS = SV; RHS = I->High; MHS = NULL;
1636 } else {
1637 CC = ISD::SETLE;
1638 LHS = I->Low; MHS = SV; RHS = I->High;
1639 }
1640 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001641
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001642 // If emitting the first comparison, just call visitSwitchCase to emit the
1643 // code into the current block. Otherwise, push the CaseBlock onto the
1644 // vector to be later processed by SDISel, and insert the node's MBB
1645 // before the next MBB.
1646 if (CurBlock == CurMBB)
1647 visitSwitchCase(CB);
1648 else
1649 SwitchCases.push_back(CB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001650
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001651 CurBlock = FallThrough;
1652 }
1653
1654 return true;
1655}
1656
1657static inline bool areJTsAllowed(const TargetLowering &TLI) {
1658 return !DisableJumpTables &&
Dan Gohmanf560ffa2009-01-28 17:46:25 +00001659 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1660 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001661}
Anton Korobeynikov23218582008-12-23 22:25:27 +00001662
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001663static APInt ComputeRange(const APInt &First, const APInt &Last) {
1664 APInt LastExt(Last), FirstExt(First);
1665 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1666 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1667 return (LastExt - FirstExt + 1ULL);
1668}
1669
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001670/// handleJTSwitchCase - Emit jumptable for current switch case range
1671bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1672 CaseRecVector& WorkList,
1673 Value* SV,
1674 MachineBasicBlock* Default) {
1675 Case& FrontCase = *CR.Range.first;
1676 Case& BackCase = *(CR.Range.second-1);
1677
Anton Korobeynikov23218582008-12-23 22:25:27 +00001678 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1679 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001680
Anton Korobeynikov23218582008-12-23 22:25:27 +00001681 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001682 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1683 I!=E; ++I)
1684 TSize += I->size();
1685
1686 if (!areJTsAllowed(TLI) || TSize <= 3)
1687 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001688
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001689 APInt Range = ComputeRange(First, Last);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001690 double Density = (double)TSize / Range.roundToDouble();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001691 if (Density < 0.4)
1692 return false;
1693
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001694 DEBUG(errs() << "Lowering jump table\n"
1695 << "First entry: " << First << ". Last entry: " << Last << '\n'
1696 << "Range: " << Range
1697 << "Size: " << TSize << ". Density: " << Density << "\n\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001698
1699 // Get the MachineFunction which holds the current MBB. This is used when
1700 // inserting any additional MBBs necessary to represent the switch.
1701 MachineFunction *CurMF = CurMBB->getParent();
1702
1703 // Figure out which block is immediately after the current one.
1704 MachineBasicBlock *NextBlock = 0;
1705 MachineFunction::iterator BBI = CR.CaseBB;
1706
1707 if (++BBI != CurMBB->getParent()->end())
1708 NextBlock = BBI;
1709
1710 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1711
1712 // Create a new basic block to hold the code for loading the address
1713 // of the jump table, and jumping to it. Update successor information;
1714 // we will either branch to the default case for the switch, or the jump
1715 // table.
1716 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1717 CurMF->insert(BBI, JumpTableBB);
1718 CR.CaseBB->addSuccessor(Default);
1719 CR.CaseBB->addSuccessor(JumpTableBB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001720
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001721 // Build a vector of destination BBs, corresponding to each target
1722 // of the jump table. If the value of the jump table slot corresponds to
1723 // a case statement, push the case's BB onto the vector, otherwise, push
1724 // the default BB.
1725 std::vector<MachineBasicBlock*> DestBBs;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001726 APInt TEI = First;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001727 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001728 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1729 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1730
1731 if (Low.sle(TEI) && TEI.sle(High)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001732 DestBBs.push_back(I->BB);
1733 if (TEI==High)
1734 ++I;
1735 } else {
1736 DestBBs.push_back(Default);
1737 }
1738 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001739
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001740 // Update successor info. Add one edge to each unique successor.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001741 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1742 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001743 E = DestBBs.end(); I != E; ++I) {
1744 if (!SuccsHandled[(*I)->getNumber()]) {
1745 SuccsHandled[(*I)->getNumber()] = true;
1746 JumpTableBB->addSuccessor(*I);
1747 }
1748 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001749
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001750 // Create a jump table index for this jump table, or return an existing
1751 // one.
1752 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001753
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001754 // Set the jump table information so that we can codegen it as a second
1755 // MachineBasicBlock
1756 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1757 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1758 if (CR.CaseBB == CurMBB)
1759 visitJumpTableHeader(JT, JTH);
Anton Korobeynikov23218582008-12-23 22:25:27 +00001760
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001761 JTCases.push_back(JumpTableBlock(JTH, JT));
1762
1763 return true;
1764}
1765
1766/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1767/// 2 subtrees.
1768bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1769 CaseRecVector& WorkList,
1770 Value* SV,
1771 MachineBasicBlock* Default) {
1772 // Get the MachineFunction which holds the current MBB. This is used when
1773 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001774 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001775
1776 // Figure out which block is immediately after the current one.
1777 MachineBasicBlock *NextBlock = 0;
1778 MachineFunction::iterator BBI = CR.CaseBB;
1779
1780 if (++BBI != CurMBB->getParent()->end())
1781 NextBlock = BBI;
1782
1783 Case& FrontCase = *CR.Range.first;
1784 Case& BackCase = *(CR.Range.second-1);
1785 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1786
1787 // Size is the number of Cases represented by this range.
1788 unsigned Size = CR.Range.second - CR.Range.first;
1789
Anton Korobeynikov23218582008-12-23 22:25:27 +00001790 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1791 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001792 double FMetric = 0;
1793 CaseItr Pivot = CR.Range.first + Size/2;
1794
1795 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1796 // (heuristically) allow us to emit JumpTable's later.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001797 size_t TSize = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001798 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1799 I!=E; ++I)
1800 TSize += I->size();
1801
Anton Korobeynikov23218582008-12-23 22:25:27 +00001802 size_t LSize = FrontCase.size();
1803 size_t RSize = TSize-LSize;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001804 DEBUG(errs() << "Selecting best pivot: \n"
1805 << "First: " << First << ", Last: " << Last <<'\n'
1806 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001807 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1808 J!=E; ++I, ++J) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001809 const APInt& LEnd = cast<ConstantInt>(I->High)->getValue();
1810 const APInt& RBegin = cast<ConstantInt>(J->Low)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001811 APInt Range = ComputeRange(LEnd, RBegin);
1812 assert((Range - 2ULL).isNonNegative() &&
1813 "Invalid case distance");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001814 double LDensity = (double)LSize / (LEnd - First + 1ULL).roundToDouble();
1815 double RDensity = (double)RSize / (Last - RBegin + 1ULL).roundToDouble();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001816 double Metric = Range.logBase2()*(LDensity+RDensity);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001817 // Should always split in some non-trivial place
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001818 DEBUG(errs() <<"=>Step\n"
1819 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1820 << "LDensity: " << LDensity
1821 << ", RDensity: " << RDensity << '\n'
1822 << "Metric: " << Metric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001823 if (FMetric < Metric) {
1824 Pivot = J;
1825 FMetric = Metric;
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001826 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001827 }
1828
1829 LSize += J->size();
1830 RSize -= J->size();
1831 }
1832 if (areJTsAllowed(TLI)) {
1833 // If our case is dense we *really* should handle it earlier!
1834 assert((FMetric > 0) && "Should handle dense range earlier!");
1835 } else {
1836 Pivot = CR.Range.first + Size/2;
1837 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001838
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001839 CaseRange LHSR(CR.Range.first, Pivot);
1840 CaseRange RHSR(Pivot, CR.Range.second);
1841 Constant *C = Pivot->Low;
1842 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001843
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001844 // We know that we branch to the LHS if the Value being switched on is
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001845 // less than the Pivot value, C. We use this to optimize our binary
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001846 // tree a bit, by recognizing that if SV is greater than or equal to the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001847 // LHS's Case Value, and that Case Value is exactly one less than the
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001848 // Pivot's Value, then we can branch directly to the LHS's Target,
1849 // rather than creating a leaf node for it.
1850 if ((LHSR.second - LHSR.first) == 1 &&
1851 LHSR.first->High == CR.GE &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001852 cast<ConstantInt>(C)->getValue() ==
1853 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001854 TrueBB = LHSR.first->BB;
1855 } else {
1856 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1857 CurMF->insert(BBI, TrueBB);
1858 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001859
1860 // Put SV in a virtual register to make it available from the new blocks.
1861 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001862 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001863
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001864 // Similar to the optimization above, if the Value being switched on is
1865 // known to be less than the Constant CR.LT, and the current Case Value
1866 // is CR.LT - 1, then we can branch directly to the target block for
1867 // the current Case Value, rather than emitting a RHS leaf node for it.
1868 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
Anton Korobeynikov23218582008-12-23 22:25:27 +00001869 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1870 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001871 FalseBB = RHSR.first->BB;
1872 } else {
1873 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1874 CurMF->insert(BBI, FalseBB);
1875 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00001876
1877 // Put SV in a virtual register to make it available from the new blocks.
1878 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001879 }
1880
1881 // Create a CaseBlock record representing a conditional branch to
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00001882 // the LHS node if the value being switched on SV is less than C.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001883 // Otherwise, branch to LHS.
1884 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1885
1886 if (CR.CaseBB == CurMBB)
1887 visitSwitchCase(CB);
1888 else
1889 SwitchCases.push_back(CB);
1890
1891 return true;
1892}
1893
1894/// handleBitTestsSwitchCase - if current case range has few destination and
1895/// range span less, than machine word bitwidth, encode case range into series
1896/// of masks and emit bit tests with these masks.
1897bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1898 CaseRecVector& WorkList,
1899 Value* SV,
1900 MachineBasicBlock* Default){
1901 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1902
1903 Case& FrontCase = *CR.Range.first;
1904 Case& BackCase = *(CR.Range.second-1);
1905
1906 // Get the MachineFunction which holds the current MBB. This is used when
1907 // inserting any additional MBBs necessary to represent the switch.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001908 MachineFunction *CurMF = CurMBB->getParent();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001909
Anton Korobeynikovd34167a2009-05-08 18:51:34 +00001910 // If target does not have legal shift left, do not emit bit tests at all.
1911 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
1912 return false;
1913
Anton Korobeynikov23218582008-12-23 22:25:27 +00001914 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001915 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1916 I!=E; ++I) {
1917 // Single case counts one, case range - two.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001918 numCmps += (I->Low == I->High ? 1 : 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001919 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001920
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001921 // Count unique destinations
1922 SmallSet<MachineBasicBlock*, 4> Dests;
1923 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1924 Dests.insert(I->BB);
1925 if (Dests.size() > 3)
1926 // Don't bother the code below, if there are too much unique destinations
1927 return false;
1928 }
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001929 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1930 << "Total number of comparisons: " << numCmps << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001931
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001932 // Compute span of values.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001933 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1934 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00001935 APInt cmpRange = maxValue - minValue;
1936
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001937 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1938 << "Low bound: " << minValue << '\n'
1939 << "High bound: " << maxValue << '\n');
Anton Korobeynikov23218582008-12-23 22:25:27 +00001940
1941 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001942 (!(Dests.size() == 1 && numCmps >= 3) &&
1943 !(Dests.size() == 2 && numCmps >= 5) &&
1944 !(Dests.size() >= 3 && numCmps >= 6)))
1945 return false;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001946
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001947 DEBUG(errs() << "Emitting bit tests\n");
Anton Korobeynikov23218582008-12-23 22:25:27 +00001948 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1949
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001950 // Optimize the case where all the case values fit in a
1951 // word without having to subtract minValue. In this case,
1952 // we can optimize away the subtraction.
Anton Korobeynikov23218582008-12-23 22:25:27 +00001953 if (minValue.isNonNegative() &&
1954 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1955 cmpRange = maxValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001956 } else {
Anton Korobeynikov23218582008-12-23 22:25:27 +00001957 lowBound = minValue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001958 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001959
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001960 CaseBitsVector CasesBits;
1961 unsigned i, count = 0;
1962
1963 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1964 MachineBasicBlock* Dest = I->BB;
1965 for (i = 0; i < count; ++i)
1966 if (Dest == CasesBits[i].BB)
1967 break;
Anton Korobeynikov23218582008-12-23 22:25:27 +00001968
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001969 if (i == count) {
1970 assert((count < 3) && "Too much destinations to test!");
1971 CasesBits.push_back(CaseBits(0, Dest, 0));
1972 count++;
1973 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001974
1975 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1976 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1977
1978 uint64_t lo = (lowValue - lowBound).getZExtValue();
1979 uint64_t hi = (highValue - lowBound).getZExtValue();
1980
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001981 for (uint64_t j = lo; j <= hi; j++) {
1982 CasesBits[i].Mask |= 1ULL << j;
1983 CasesBits[i].Bits++;
1984 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00001985
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001986 }
1987 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
Anton Korobeynikov23218582008-12-23 22:25:27 +00001988
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001989 BitTestInfo BTC;
1990
1991 // Figure out which block is immediately after the current one.
1992 MachineFunction::iterator BBI = CR.CaseBB;
1993 ++BBI;
1994
1995 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1996
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001997 DEBUG(errs() << "Cases:\n");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001998 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00001999 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
2000 << ", Bits: " << CasesBits[i].Bits
2001 << ", BB: " << CasesBits[i].BB << '\n');
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002002
2003 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2004 CurMF->insert(BBI, CaseBB);
2005 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2006 CaseBB,
2007 CasesBits[i].BB));
Dan Gohman8e5c0da2009-04-09 02:33:36 +00002008
2009 // Put SV in a virtual register to make it available from the new blocks.
2010 ExportFromCurrentBlock(SV);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002011 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002012
2013 BitTestBlock BTB(lowBound, cmpRange, SV,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002014 -1U, (CR.CaseBB == CurMBB),
2015 CR.CaseBB, Default, BTC);
2016
2017 if (CR.CaseBB == CurMBB)
2018 visitBitTestHeader(BTB);
Anton Korobeynikov23218582008-12-23 22:25:27 +00002019
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002020 BitTestCases.push_back(BTB);
2021
2022 return true;
2023}
2024
2025
2026/// Clusterify - Transform simple list of Cases into list of CaseRange's
Anton Korobeynikov23218582008-12-23 22:25:27 +00002027size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002028 const SwitchInst& SI) {
Anton Korobeynikov23218582008-12-23 22:25:27 +00002029 size_t numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002030
2031 // Start with "simple" cases
Anton Korobeynikov23218582008-12-23 22:25:27 +00002032 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002033 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2034 Cases.push_back(Case(SI.getSuccessorValue(i),
2035 SI.getSuccessorValue(i),
2036 SMBB));
2037 }
2038 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2039
2040 // Merge case into clusters
Anton Korobeynikov23218582008-12-23 22:25:27 +00002041 if (Cases.size() >= 2)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002042 // Must recompute end() each iteration because it may be
2043 // invalidated by erase if we hold on to it
Anton Korobeynikov23218582008-12-23 22:25:27 +00002044 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
2045 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2046 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002047 MachineBasicBlock* nextBB = J->BB;
2048 MachineBasicBlock* currentBB = I->BB;
2049
2050 // If the two neighboring cases go to the same destination, merge them
2051 // into a single case.
Anton Korobeynikov23218582008-12-23 22:25:27 +00002052 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002053 I->High = J->High;
2054 J = Cases.erase(J);
2055 } else {
2056 I = J++;
2057 }
2058 }
2059
2060 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2061 if (I->Low != I->High)
2062 // A range counts double, since it requires two compares.
2063 ++numCmps;
2064 }
2065
2066 return numCmps;
2067}
2068
Anton Korobeynikov23218582008-12-23 22:25:27 +00002069void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002070 // Figure out which block is immediately after the current one.
2071 MachineBasicBlock *NextBlock = 0;
2072 MachineFunction::iterator BBI = CurMBB;
2073
2074 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2075
2076 // If there is only the default destination, branch to it if it is not the
2077 // next basic block. Otherwise, just fall through.
2078 if (SI.getNumOperands() == 2) {
2079 // Update machine-CFG edges.
2080
2081 // If this is not a fall-through branch, emit the branch.
2082 CurMBB->addSuccessor(Default);
2083 if (Default != NextBlock)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002084 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002085 MVT::Other, getControlRoot(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002086 DAG.getBasicBlock(Default)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002087 return;
2088 }
Anton Korobeynikov23218582008-12-23 22:25:27 +00002089
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002090 // If there are any non-default case statements, create a vector of Cases
2091 // representing each one, and sort the vector so that we can efficiently
2092 // create a binary search tree from them.
2093 CaseVector Cases;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002094 size_t numCmps = Clusterify(Cases, SI);
Anton Korobeynikov56d245b2008-12-23 22:26:18 +00002095 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2096 << ". Total compares: " << numCmps << '\n');
Devang Patel8a84e442009-01-05 17:31:22 +00002097 numCmps = 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002098
2099 // Get the Value to be switched on and default basic blocks, which will be
2100 // inserted into CaseBlock records, representing basic blocks in the binary
2101 // search tree.
2102 Value *SV = SI.getOperand(0);
2103
2104 // Push the initial CaseRec onto the worklist
2105 CaseRecVector WorkList;
2106 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2107
2108 while (!WorkList.empty()) {
2109 // Grab a record representing a case range to process off the worklist
2110 CaseRec CR = WorkList.back();
2111 WorkList.pop_back();
2112
2113 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2114 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002115
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002116 // If the range has few cases (two or less) emit a series of specific
2117 // tests.
2118 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2119 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002120
Anton Korobeynikove2f95e92008-12-23 22:26:01 +00002121 // If the switch has more than 5 blocks, and at least 40% dense, and the
2122 // target supports indirect branches, then emit a jump table rather than
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002123 // lowering the switch to a binary tree of conditional branches.
2124 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2125 continue;
Anton Korobeynikov23218582008-12-23 22:25:27 +00002126
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002127 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2128 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2129 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2130 }
2131}
2132
2133
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002134void SelectionDAGLowering::visitFSub(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002135 // -0.0 - X --> fneg
2136 const Type *Ty = I.getType();
2137 if (isa<VectorType>(Ty)) {
2138 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2139 const VectorType *DestTy = cast<VectorType>(I.getType());
2140 const Type *ElTy = DestTy->getElementType();
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002141 unsigned VL = DestTy->getNumElements();
2142 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2143 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2144 if (CV == CNZ) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002145 SDValue Op2 = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002146 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002147 Op2.getValueType(), Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002148 return;
2149 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002150 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002151 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002152 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2153 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2154 SDValue Op2 = getValue(I.getOperand(1));
2155 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2156 Op2.getValueType(), Op2));
2157 return;
2158 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002159
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002160 visitBinary(I, ISD::FSUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002161}
2162
2163void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2164 SDValue Op1 = getValue(I.getOperand(0));
2165 SDValue Op2 = getValue(I.getOperand(1));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002166
Scott Michelfdc40a02009-02-17 22:15:04 +00002167 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002168 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002169}
2170
2171void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2172 SDValue Op1 = getValue(I.getOperand(0));
2173 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman57fc82d2009-04-09 03:51:29 +00002174 if (!isa<VectorType>(I.getType()) &&
2175 Op2.getValueType() != TLI.getShiftAmountTy()) {
2176 // If the operand is smaller than the shift count type, promote it.
2177 if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2178 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2179 TLI.getShiftAmountTy(), Op2);
2180 // If the operand is larger than the shift count type but the shift
2181 // count type has enough bits to represent any shift value, truncate
2182 // it now. This is a common case and it exposes the truncate to
2183 // optimization early.
2184 else if (TLI.getShiftAmountTy().getSizeInBits() >=
2185 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2186 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2187 TLI.getShiftAmountTy(), Op2);
2188 // Otherwise we'll need to temporarily settle for some other
2189 // convenient type; type legalization will make adjustments as
2190 // needed.
2191 else if (TLI.getPointerTy().bitsLT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002192 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002193 TLI.getPointerTy(), Op2);
2194 else if (TLI.getPointerTy().bitsGT(Op2.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002195 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
Duncan Sands92abc622009-01-31 15:50:11 +00002196 TLI.getPointerTy(), Op2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002197 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002198
Scott Michelfdc40a02009-02-17 22:15:04 +00002199 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002200 Op1.getValueType(), Op1, Op2));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002201}
2202
2203void SelectionDAGLowering::visitICmp(User &I) {
2204 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2205 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2206 predicate = IC->getPredicate();
2207 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2208 predicate = ICmpInst::Predicate(IC->getPredicate());
2209 SDValue Op1 = getValue(I.getOperand(0));
2210 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002211 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dale Johannesenf5d97892009-02-04 01:48:28 +00002212 setValue(&I, DAG.getSetCC(getCurDebugLoc(),MVT::i1, Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002213}
2214
2215void SelectionDAGLowering::visitFCmp(User &I) {
2216 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2217 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2218 predicate = FC->getPredicate();
2219 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2220 predicate = FCmpInst::Predicate(FC->getPredicate());
2221 SDValue Op1 = getValue(I.getOperand(0));
2222 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002223 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dale Johannesenf5d97892009-02-04 01:48:28 +00002224 setValue(&I, DAG.getSetCC(getCurDebugLoc(), MVT::i1, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002225}
2226
2227void SelectionDAGLowering::visitVICmp(User &I) {
2228 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2229 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2230 predicate = IC->getPredicate();
2231 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2232 predicate = ICmpInst::Predicate(IC->getPredicate());
2233 SDValue Op1 = getValue(I.getOperand(0));
2234 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002235 ISD::CondCode Opcode = getICmpCondCode(predicate);
Scott Michelfdc40a02009-02-17 22:15:04 +00002236 setValue(&I, DAG.getVSetCC(getCurDebugLoc(), Op1.getValueType(),
Dale Johannesenf5d97892009-02-04 01:48:28 +00002237 Op1, Op2, Opcode));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002238}
2239
2240void SelectionDAGLowering::visitVFCmp(User &I) {
2241 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2242 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2243 predicate = FC->getPredicate();
2244 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2245 predicate = FCmpInst::Predicate(FC->getPredicate());
2246 SDValue Op1 = getValue(I.getOperand(0));
2247 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002248 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002249 MVT DestVT = TLI.getValueType(I.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002250
Dale Johannesenf5d97892009-02-04 01:48:28 +00002251 setValue(&I, DAG.getVSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002252}
2253
2254void SelectionDAGLowering::visitSelect(User &I) {
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002255 SmallVector<MVT, 4> ValueVTs;
2256 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2257 unsigned NumValues = ValueVTs.size();
2258 if (NumValues != 0) {
2259 SmallVector<SDValue, 4> Values(NumValues);
2260 SDValue Cond = getValue(I.getOperand(0));
2261 SDValue TrueVal = getValue(I.getOperand(1));
2262 SDValue FalseVal = getValue(I.getOperand(2));
2263
2264 for (unsigned i = 0; i != NumValues; ++i)
Scott Michelfdc40a02009-02-17 22:15:04 +00002265 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002266 TrueVal.getValueType(), Cond,
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002267 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2268 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2269
Scott Michelfdc40a02009-02-17 22:15:04 +00002270 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002271 DAG.getVTList(&ValueVTs[0], NumValues),
2272 &Values[0], NumValues));
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002273 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002274}
2275
2276
2277void SelectionDAGLowering::visitTrunc(User &I) {
2278 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2279 SDValue N = getValue(I.getOperand(0));
2280 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002281 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002282}
2283
2284void SelectionDAGLowering::visitZExt(User &I) {
2285 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2286 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2287 SDValue N = getValue(I.getOperand(0));
2288 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002289 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002290}
2291
2292void SelectionDAGLowering::visitSExt(User &I) {
2293 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2294 // SExt also can't be a cast to bool for same reason. So, nothing much to do
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::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002298}
2299
2300void SelectionDAGLowering::visitFPTrunc(User &I) {
2301 // FPTrunc is never a no-op cast, no need to check
2302 SDValue N = getValue(I.getOperand(0));
2303 MVT DestVT = TLI.getValueType(I.getType());
Scott Michelfdc40a02009-02-17 22:15:04 +00002304 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002305 DestVT, N, DAG.getIntPtrConstant(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002306}
2307
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002308void SelectionDAGLowering::visitFPExt(User &I){
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002309 // FPTrunc is never a no-op cast, no need to check
2310 SDValue N = getValue(I.getOperand(0));
2311 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002312 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002313}
2314
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002315void SelectionDAGLowering::visitFPToUI(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002316 // FPToUI is never a no-op cast, no need to check
2317 SDValue N = getValue(I.getOperand(0));
2318 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002319 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002320}
2321
2322void SelectionDAGLowering::visitFPToSI(User &I) {
2323 // FPToSI is never a no-op cast, no need to check
2324 SDValue N = getValue(I.getOperand(0));
2325 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002326 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002327}
2328
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002329void SelectionDAGLowering::visitUIToFP(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002330 // UIToFP is never a no-op cast, no need to check
2331 SDValue N = getValue(I.getOperand(0));
2332 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002333 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002334}
2335
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002336void SelectionDAGLowering::visitSIToFP(User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002337 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002338 SDValue N = getValue(I.getOperand(0));
2339 MVT DestVT = TLI.getValueType(I.getType());
Dale Johannesen66978ee2009-01-31 02:22:37 +00002340 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002341}
2342
2343void SelectionDAGLowering::visitPtrToInt(User &I) {
2344 // What to do depends on the size of the integer and the size of the pointer.
2345 // We can either truncate, zero extend, or no-op, accordingly.
2346 SDValue N = getValue(I.getOperand(0));
2347 MVT SrcVT = N.getValueType();
2348 MVT DestVT = TLI.getValueType(I.getType());
2349 SDValue Result;
2350 if (DestVT.bitsLT(SrcVT))
Dale Johannesen66978ee2009-01-31 02:22:37 +00002351 Result = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002352 else
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002353 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
Dale Johannesen66978ee2009-01-31 02:22:37 +00002354 Result = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002355 setValue(&I, Result);
2356}
2357
2358void SelectionDAGLowering::visitIntToPtr(User &I) {
2359 // What to do depends on the size of the integer and the size of the pointer.
2360 // We can either truncate, zero extend, or no-op, accordingly.
2361 SDValue N = getValue(I.getOperand(0));
2362 MVT SrcVT = N.getValueType();
2363 MVT DestVT = TLI.getValueType(I.getType());
2364 if (DestVT.bitsLT(SrcVT))
Dale Johannesen66978ee2009-01-31 02:22:37 +00002365 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002366 else
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002367 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
Scott Michelfdc40a02009-02-17 22:15:04 +00002368 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002369 DestVT, N));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002370}
2371
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002372void SelectionDAGLowering::visitBitCast(User &I) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002373 SDValue N = getValue(I.getOperand(0));
2374 MVT DestVT = TLI.getValueType(I.getType());
2375
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002376 // BitCast assures us that source and destination are the same size so this
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002377 // is either a BIT_CONVERT or a no-op.
2378 if (DestVT != N.getValueType())
Scott Michelfdc40a02009-02-17 22:15:04 +00002379 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002380 DestVT, N)); // convert types
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002381 else
2382 setValue(&I, N); // noop cast.
2383}
2384
2385void SelectionDAGLowering::visitInsertElement(User &I) {
2386 SDValue InVec = getValue(I.getOperand(0));
2387 SDValue InVal = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00002388 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002389 TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002390 getValue(I.getOperand(2)));
2391
Scott Michelfdc40a02009-02-17 22:15:04 +00002392 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002393 TLI.getValueType(I.getType()),
2394 InVec, InVal, InIdx));
2395}
2396
2397void SelectionDAGLowering::visitExtractElement(User &I) {
2398 SDValue InVec = getValue(I.getOperand(0));
Scott Michelfdc40a02009-02-17 22:15:04 +00002399 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002400 TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002401 getValue(I.getOperand(1)));
Dale Johannesen66978ee2009-01-31 02:22:37 +00002402 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002403 TLI.getValueType(I.getType()), InVec, InIdx));
2404}
2405
Mon P Wangaeb06d22008-11-10 04:46:22 +00002406
2407// Utility for visitShuffleVector - Returns true if the mask is mask starting
2408// from SIndx and increasing to the element length (undefs are allowed).
Nate Begeman5a5ca152009-04-29 05:20:52 +00002409static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2410 unsigned MaskNumElts = Mask.size();
2411 for (unsigned i = 0; i != MaskNumElts; ++i)
2412 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
Nate Begeman9008ca62009-04-27 18:41:29 +00002413 return false;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002414 return true;
2415}
2416
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002417void SelectionDAGLowering::visitShuffleVector(User &I) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002418 SmallVector<int, 8> Mask;
Mon P Wang230e4fa2008-11-21 04:25:21 +00002419 SDValue Src1 = getValue(I.getOperand(0));
2420 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002421
Nate Begeman9008ca62009-04-27 18:41:29 +00002422 // Convert the ConstantVector mask operand into an array of ints, with -1
2423 // representing undef values.
2424 SmallVector<Constant*, 8> MaskElts;
2425 cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
Nate Begeman5a5ca152009-04-29 05:20:52 +00002426 unsigned MaskNumElts = MaskElts.size();
2427 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002428 if (isa<UndefValue>(MaskElts[i]))
2429 Mask.push_back(-1);
2430 else
2431 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2432 }
2433
Mon P Wangaeb06d22008-11-10 04:46:22 +00002434 MVT VT = TLI.getValueType(I.getType());
Mon P Wang230e4fa2008-11-21 04:25:21 +00002435 MVT SrcVT = Src1.getValueType();
Nate Begeman5a5ca152009-04-29 05:20:52 +00002436 unsigned SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002437
Mon P Wangc7849c22008-11-16 05:06:27 +00002438 if (SrcNumElts == MaskNumElts) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002439 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2440 &Mask[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002441 return;
2442 }
2443
2444 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002445 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2446 // Mask is longer than the source vectors and is a multiple of the source
2447 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang230e4fa2008-11-21 04:25:21 +00002448 // lengths match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002449 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2450 // The shuffle is concatenating two vectors together.
Scott Michelfdc40a02009-02-17 22:15:04 +00002451 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002452 VT, Src1, Src2));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002453 return;
2454 }
2455
Mon P Wangc7849c22008-11-16 05:06:27 +00002456 // Pad both vectors with undefs to make them the same length as the mask.
2457 unsigned NumConcat = MaskNumElts / SrcNumElts;
Nate Begeman9008ca62009-04-27 18:41:29 +00002458 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2459 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
Dale Johannesene8d72302009-02-06 23:05:02 +00002460 SDValue UndefVal = DAG.getUNDEF(SrcVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002461
Nate Begeman9008ca62009-04-27 18:41:29 +00002462 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2463 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002464 MOps1[0] = Src1;
2465 MOps2[0] = Src2;
Nate Begeman9008ca62009-04-27 18:41:29 +00002466
2467 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2468 getCurDebugLoc(), VT,
2469 &MOps1[0], NumConcat);
2470 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2471 getCurDebugLoc(), VT,
2472 &MOps2[0], NumConcat);
Mon P Wang230e4fa2008-11-21 04:25:21 +00002473
Mon P Wangaeb06d22008-11-10 04:46:22 +00002474 // Readjust mask for new input vector length.
Nate Begeman9008ca62009-04-27 18:41:29 +00002475 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002476 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002477 int Idx = Mask[i];
Nate Begeman5a5ca152009-04-29 05:20:52 +00002478 if (Idx < (int)SrcNumElts)
Nate Begeman9008ca62009-04-27 18:41:29 +00002479 MappedOps.push_back(Idx);
2480 else
2481 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002482 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002483 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2484 &MappedOps[0]));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002485 return;
2486 }
2487
Mon P Wangc7849c22008-11-16 05:06:27 +00002488 if (SrcNumElts > MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002489 // Analyze the access pattern of the vector to see if we can extract
2490 // two subvectors and do the shuffle. The analysis is done by calculating
2491 // the range of elements the mask access on both vectors.
2492 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2493 int MaxRange[2] = {-1, -1};
2494
Nate Begeman5a5ca152009-04-29 05:20:52 +00002495 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002496 int Idx = Mask[i];
2497 int Input = 0;
2498 if (Idx < 0)
2499 continue;
2500
Nate Begeman5a5ca152009-04-29 05:20:52 +00002501 if (Idx >= (int)SrcNumElts) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002502 Input = 1;
2503 Idx -= SrcNumElts;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002504 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002505 if (Idx > MaxRange[Input])
2506 MaxRange[Input] = Idx;
2507 if (Idx < MinRange[Input])
2508 MinRange[Input] = Idx;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002509 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002510
Mon P Wangc7849c22008-11-16 05:06:27 +00002511 // Check if the access is smaller than the vector size and can we find
2512 // a reasonable extract index.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002513 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
Mon P Wangc7849c22008-11-16 05:06:27 +00002514 int StartIdx[2]; // StartIdx to extract from
2515 for (int Input=0; Input < 2; ++Input) {
Nate Begeman5a5ca152009-04-29 05:20:52 +00002516 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002517 RangeUse[Input] = 0; // Unused
2518 StartIdx[Input] = 0;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002519 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002520 // Fits within range but we should see if we can find a good
Mon P Wang230e4fa2008-11-21 04:25:21 +00002521 // start index that is a multiple of the mask length.
Nate Begeman5a5ca152009-04-29 05:20:52 +00002522 if (MaxRange[Input] < (int)MaskNumElts) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002523 RangeUse[Input] = 1; // Extract from beginning of the vector
2524 StartIdx[Input] = 0;
2525 } else {
2526 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002527 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002528 StartIdx[Input] + MaskNumElts < SrcNumElts)
Mon P Wangc7849c22008-11-16 05:06:27 +00002529 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002530 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002531 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002532 }
2533
2534 if (RangeUse[0] == 0 && RangeUse[0] == 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002535 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
Mon P Wangc7849c22008-11-16 05:06:27 +00002536 return;
2537 }
2538 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2539 // Extract appropriate subvector and generate a vector shuffle
2540 for (int Input=0; Input < 2; ++Input) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002541 SDValue& Src = Input == 0 ? Src1 : Src2;
Mon P Wangc7849c22008-11-16 05:06:27 +00002542 if (RangeUse[Input] == 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002543 Src = DAG.getUNDEF(VT);
Mon P Wangc7849c22008-11-16 05:06:27 +00002544 } else {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002545 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002546 Src, DAG.getIntPtrConstant(StartIdx[Input]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002547 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002548 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002549 // Calculate new mask.
Nate Begeman9008ca62009-04-27 18:41:29 +00002550 SmallVector<int, 8> MappedOps;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002551 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002552 int Idx = Mask[i];
2553 if (Idx < 0)
2554 MappedOps.push_back(Idx);
Nate Begeman5a5ca152009-04-29 05:20:52 +00002555 else if (Idx < (int)SrcNumElts)
Nate Begeman9008ca62009-04-27 18:41:29 +00002556 MappedOps.push_back(Idx - StartIdx[0]);
2557 else
2558 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
Mon P Wangc7849c22008-11-16 05:06:27 +00002559 }
Nate Begeman9008ca62009-04-27 18:41:29 +00002560 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2561 &MappedOps[0]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002562 return;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002563 }
2564 }
2565
Mon P Wangc7849c22008-11-16 05:06:27 +00002566 // We can't use either concat vectors or extract subvectors so fall back to
2567 // replacing the shuffle with extract and build vector.
2568 // to insert and build vector.
Mon P Wangaeb06d22008-11-10 04:46:22 +00002569 MVT EltVT = VT.getVectorElementType();
2570 MVT PtrVT = TLI.getPointerTy();
2571 SmallVector<SDValue,8> Ops;
Nate Begeman5a5ca152009-04-29 05:20:52 +00002572 for (unsigned i = 0; i != MaskNumElts; ++i) {
Nate Begeman9008ca62009-04-27 18:41:29 +00002573 if (Mask[i] < 0) {
Dale Johannesene8d72302009-02-06 23:05:02 +00002574 Ops.push_back(DAG.getUNDEF(EltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002575 } else {
Nate Begeman9008ca62009-04-27 18:41:29 +00002576 int Idx = Mask[i];
Nate Begeman5a5ca152009-04-29 05:20:52 +00002577 if (Idx < (int)SrcNumElts)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002578 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002579 EltVT, Src1, DAG.getConstant(Idx, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002580 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00002581 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
Scott Michelfdc40a02009-02-17 22:15:04 +00002582 EltVT, Src2,
Mon P Wangc7849c22008-11-16 05:06:27 +00002583 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002584 }
2585 }
Evan Chenga87008d2009-02-25 22:49:59 +00002586 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2587 VT, &Ops[0], Ops.size()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002588}
2589
2590void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2591 const Value *Op0 = I.getOperand(0);
2592 const Value *Op1 = I.getOperand(1);
2593 const Type *AggTy = I.getType();
2594 const Type *ValTy = Op1->getType();
2595 bool IntoUndef = isa<UndefValue>(Op0);
2596 bool FromUndef = isa<UndefValue>(Op1);
2597
2598 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2599 I.idx_begin(), I.idx_end());
2600
2601 SmallVector<MVT, 4> AggValueVTs;
2602 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2603 SmallVector<MVT, 4> ValValueVTs;
2604 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2605
2606 unsigned NumAggValues = AggValueVTs.size();
2607 unsigned NumValValues = ValValueVTs.size();
2608 SmallVector<SDValue, 4> Values(NumAggValues);
2609
2610 SDValue Agg = getValue(Op0);
2611 SDValue Val = getValue(Op1);
2612 unsigned i = 0;
2613 // Copy the beginning value(s) from the original aggregate.
2614 for (; i != LinearIndex; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002615 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002616 SDValue(Agg.getNode(), Agg.getResNo() + i);
2617 // Copy values from the inserted value(s).
2618 for (; i != LinearIndex + NumValValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002619 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002620 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2621 // Copy remaining value(s) from the original aggregate.
2622 for (; i != NumAggValues; ++i)
Dale Johannesene8d72302009-02-06 23:05:02 +00002623 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002624 SDValue(Agg.getNode(), Agg.getResNo() + i);
2625
Scott Michelfdc40a02009-02-17 22:15:04 +00002626 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002627 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2628 &Values[0], NumAggValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002629}
2630
2631void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2632 const Value *Op0 = I.getOperand(0);
2633 const Type *AggTy = Op0->getType();
2634 const Type *ValTy = I.getType();
2635 bool OutOfUndef = isa<UndefValue>(Op0);
2636
2637 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2638 I.idx_begin(), I.idx_end());
2639
2640 SmallVector<MVT, 4> ValValueVTs;
2641 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2642
2643 unsigned NumValValues = ValValueVTs.size();
2644 SmallVector<SDValue, 4> Values(NumValValues);
2645
2646 SDValue Agg = getValue(Op0);
2647 // Copy out the selected value(s).
2648 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2649 Values[i - LinearIndex] =
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002650 OutOfUndef ?
Dale Johannesene8d72302009-02-06 23:05:02 +00002651 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002652 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002653
Scott Michelfdc40a02009-02-17 22:15:04 +00002654 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002655 DAG.getVTList(&ValValueVTs[0], NumValValues),
2656 &Values[0], NumValValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002657}
2658
2659
2660void SelectionDAGLowering::visitGetElementPtr(User &I) {
2661 SDValue N = getValue(I.getOperand(0));
2662 const Type *Ty = I.getOperand(0)->getType();
2663
2664 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2665 OI != E; ++OI) {
2666 Value *Idx = *OI;
2667 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2668 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2669 if (Field) {
2670 // N = N + Offset
2671 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002672 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002673 DAG.getIntPtrConstant(Offset));
2674 }
2675 Ty = StTy->getElementType(Field);
2676 } else {
2677 Ty = cast<SequentialType>(Ty)->getElementType();
2678
2679 // If this is a constant subscript, handle it quickly.
2680 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2681 if (CI->getZExtValue() == 0) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002682 uint64_t Offs =
Duncan Sands777d2302009-05-09 07:06:46 +00002683 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
Evan Cheng65b52df2009-02-09 21:01:06 +00002684 SDValue OffsVal;
Evan Chengb1032a82009-02-09 20:54:38 +00002685 unsigned PtrBits = TLI.getPointerTy().getSizeInBits();
Evan Cheng65b52df2009-02-09 21:01:06 +00002686 if (PtrBits < 64) {
2687 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2688 TLI.getPointerTy(),
2689 DAG.getConstant(Offs, MVT::i64));
2690 } else
Evan Chengb1032a82009-02-09 20:54:38 +00002691 OffsVal = DAG.getIntPtrConstant(Offs);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002692 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
Evan Chengb1032a82009-02-09 20:54:38 +00002693 OffsVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002694 continue;
2695 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002696
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002697 // N = N + Idx * ElementSize;
Duncan Sands777d2302009-05-09 07:06:46 +00002698 uint64_t ElementSize = TD->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002699 SDValue IdxN = getValue(Idx);
2700
2701 // If the index is smaller or larger than intptr_t, truncate or extend
2702 // it.
2703 if (IdxN.getValueType().bitsLT(N.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002704 IdxN = DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002705 N.getValueType(), IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002706 else if (IdxN.getValueType().bitsGT(N.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002707 IdxN = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002708 N.getValueType(), IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002709
2710 // If this is a multiply by a power of two, turn it into a shl
2711 // immediately. This is a very common case.
2712 if (ElementSize != 1) {
2713 if (isPowerOf2_64(ElementSize)) {
2714 unsigned Amt = Log2_64(ElementSize);
Scott Michelfdc40a02009-02-17 22:15:04 +00002715 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002716 N.getValueType(), IdxN,
Duncan Sands92abc622009-01-31 15:50:11 +00002717 DAG.getConstant(Amt, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002718 } else {
2719 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
Scott Michelfdc40a02009-02-17 22:15:04 +00002720 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002721 N.getValueType(), IdxN, Scale);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002722 }
2723 }
2724
Scott Michelfdc40a02009-02-17 22:15:04 +00002725 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002726 N.getValueType(), N, IdxN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002727 }
2728 }
2729 setValue(&I, N);
2730}
2731
2732void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2733 // If this is a fixed sized alloca in the entry block of the function,
2734 // allocate it statically on the stack.
2735 if (FuncInfo.StaticAllocaMap.count(&I))
2736 return; // getValue will auto-populate this.
2737
2738 const Type *Ty = I.getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00002739 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002740 unsigned Align =
2741 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2742 I.getAlignment());
2743
2744 SDValue AllocSize = getValue(I.getArraySize());
Chris Lattner0b18e592009-03-17 19:36:00 +00002745
2746 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2747 AllocSize,
2748 DAG.getConstant(TySize, AllocSize.getValueType()));
2749
2750
2751
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002752 MVT IntPtr = TLI.getPointerTy();
2753 if (IntPtr.bitsLT(AllocSize.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002754 AllocSize = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002755 IntPtr, AllocSize);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002756 else if (IntPtr.bitsGT(AllocSize.getValueType()))
Scott Michelfdc40a02009-02-17 22:15:04 +00002757 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002758 IntPtr, AllocSize);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002759
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002760 // Handle alignment. If the requested alignment is less than or equal to
2761 // the stack alignment, ignore it. If the size is greater than or equal to
2762 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2763 unsigned StackAlign =
2764 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2765 if (Align <= StackAlign)
2766 Align = 0;
2767
2768 // Round the size of the allocation up to the stack alignment size
2769 // by add SA-1 to the size.
Scott Michelfdc40a02009-02-17 22:15:04 +00002770 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002771 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002772 DAG.getIntPtrConstant(StackAlign-1));
2773 // Mask out the low bits for alignment purposes.
Scott Michelfdc40a02009-02-17 22:15:04 +00002774 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002775 AllocSize.getValueType(), AllocSize,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002776 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2777
2778 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
Dan Gohmanfc166572009-04-09 23:54:40 +00002779 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
Scott Michelfdc40a02009-02-17 22:15:04 +00002780 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002781 VTs, Ops, 3);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002782 setValue(&I, DSA);
2783 DAG.setRoot(DSA.getValue(1));
2784
2785 // Inform the Frame Information that we have just allocated a variable-sized
2786 // object.
2787 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2788}
2789
2790void SelectionDAGLowering::visitLoad(LoadInst &I) {
2791 const Value *SV = I.getOperand(0);
2792 SDValue Ptr = getValue(SV);
2793
2794 const Type *Ty = I.getType();
2795 bool isVolatile = I.isVolatile();
2796 unsigned Alignment = I.getAlignment();
2797
2798 SmallVector<MVT, 4> ValueVTs;
2799 SmallVector<uint64_t, 4> Offsets;
2800 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2801 unsigned NumValues = ValueVTs.size();
2802 if (NumValues == 0)
2803 return;
2804
2805 SDValue Root;
2806 bool ConstantMemory = false;
2807 if (I.isVolatile())
2808 // Serialize volatile loads with other side effects.
2809 Root = getRoot();
2810 else if (AA->pointsToConstantMemory(SV)) {
2811 // Do not serialize (non-volatile) loads of constant memory with anything.
2812 Root = DAG.getEntryNode();
2813 ConstantMemory = true;
2814 } else {
2815 // Do not serialize non-volatile loads against each other.
2816 Root = DAG.getRoot();
2817 }
2818
2819 SmallVector<SDValue, 4> Values(NumValues);
2820 SmallVector<SDValue, 4> Chains(NumValues);
2821 MVT PtrVT = Ptr.getValueType();
2822 for (unsigned i = 0; i != NumValues; ++i) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00002823 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
Scott Michelfdc40a02009-02-17 22:15:04 +00002824 DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002825 PtrVT, Ptr,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002826 DAG.getConstant(Offsets[i], PtrVT)),
2827 SV, Offsets[i],
2828 isVolatile, Alignment);
2829 Values[i] = L;
2830 Chains[i] = L.getValue(1);
2831 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002832
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002833 if (!ConstantMemory) {
Scott Michelfdc40a02009-02-17 22:15:04 +00002834 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002835 MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002836 &Chains[0], NumValues);
2837 if (isVolatile)
2838 DAG.setRoot(Chain);
2839 else
2840 PendingLoads.push_back(Chain);
2841 }
2842
Scott Michelfdc40a02009-02-17 22:15:04 +00002843 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
Duncan Sandsaaffa052008-12-01 11:41:29 +00002844 DAG.getVTList(&ValueVTs[0], NumValues),
2845 &Values[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002846}
2847
2848
2849void SelectionDAGLowering::visitStore(StoreInst &I) {
2850 Value *SrcV = I.getOperand(0);
2851 Value *PtrV = I.getOperand(1);
2852
2853 SmallVector<MVT, 4> ValueVTs;
2854 SmallVector<uint64_t, 4> Offsets;
2855 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2856 unsigned NumValues = ValueVTs.size();
2857 if (NumValues == 0)
2858 return;
2859
2860 // Get the lowered operands. Note that we do this after
2861 // checking if NumResults is zero, because with zero results
2862 // the operands won't have values in the map.
2863 SDValue Src = getValue(SrcV);
2864 SDValue Ptr = getValue(PtrV);
2865
2866 SDValue Root = getRoot();
2867 SmallVector<SDValue, 4> Chains(NumValues);
2868 MVT PtrVT = Ptr.getValueType();
2869 bool isVolatile = I.isVolatile();
2870 unsigned Alignment = I.getAlignment();
2871 for (unsigned i = 0; i != NumValues; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00002872 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002873 SDValue(Src.getNode(), Src.getResNo() + i),
Scott Michelfdc40a02009-02-17 22:15:04 +00002874 DAG.getNode(ISD::ADD, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002875 PtrVT, Ptr,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002876 DAG.getConstant(Offsets[i], PtrVT)),
2877 PtrV, Offsets[i],
2878 isVolatile, Alignment);
2879
Scott Michelfdc40a02009-02-17 22:15:04 +00002880 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00002881 MVT::Other, &Chains[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002882}
2883
2884/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2885/// node.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002886void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002887 unsigned Intrinsic) {
2888 bool HasChain = !I.doesNotAccessMemory();
2889 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2890
2891 // Build the operand list.
2892 SmallVector<SDValue, 8> Ops;
2893 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2894 if (OnlyLoad) {
2895 // We don't need to serialize loads against other loads.
2896 Ops.push_back(DAG.getRoot());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002897 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002898 Ops.push_back(getRoot());
2899 }
2900 }
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002901
2902 // Info is set by getTgtMemInstrinsic
2903 TargetLowering::IntrinsicInfo Info;
2904 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2905
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002906 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002907 if (!IsTgtIntrinsic)
2908 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002909
2910 // Add all operands of the call to the operand list.
2911 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2912 SDValue Op = getValue(I.getOperand(i));
2913 assert(TLI.isTypeLegal(Op.getValueType()) &&
2914 "Intrinsic uses a non-legal type?");
2915 Ops.push_back(Op);
2916 }
2917
Dan Gohmanfc166572009-04-09 23:54:40 +00002918 std::vector<MVT> VTArray;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002919 if (I.getType() != Type::VoidTy) {
2920 MVT VT = TLI.getValueType(I.getType());
2921 if (VT.isVector()) {
2922 const VectorType *DestTy = cast<VectorType>(I.getType());
2923 MVT EltVT = TLI.getValueType(DestTy->getElementType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002924
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002925 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2926 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2927 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002928
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002929 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
Dan Gohmanfc166572009-04-09 23:54:40 +00002930 VTArray.push_back(VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002931 }
2932 if (HasChain)
Dan Gohmanfc166572009-04-09 23:54:40 +00002933 VTArray.push_back(MVT::Other);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002934
Dan Gohmanfc166572009-04-09 23:54:40 +00002935 SDVTList VTs = DAG.getVTList(&VTArray[0], VTArray.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002936
2937 // Create the node.
2938 SDValue Result;
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002939 if (IsTgtIntrinsic) {
2940 // This is target intrinsic that touches memory
Dale Johannesen66978ee2009-01-31 02:22:37 +00002941 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002942 VTs, &Ops[0], Ops.size(),
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002943 Info.memVT, Info.ptrVal, Info.offset,
2944 Info.align, Info.vol,
2945 Info.readMem, Info.writeMem);
2946 }
2947 else if (!HasChain)
Scott Michelfdc40a02009-02-17 22:15:04 +00002948 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002949 VTs, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002950 else if (I.getType() != Type::VoidTy)
Scott Michelfdc40a02009-02-17 22:15:04 +00002951 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002952 VTs, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002953 else
Scott Michelfdc40a02009-02-17 22:15:04 +00002954 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00002955 VTs, &Ops[0], Ops.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002956
2957 if (HasChain) {
2958 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2959 if (OnlyLoad)
2960 PendingLoads.push_back(Chain);
2961 else
2962 DAG.setRoot(Chain);
2963 }
2964 if (I.getType() != Type::VoidTy) {
2965 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2966 MVT VT = TLI.getValueType(PTy);
Dale Johannesen66978ee2009-01-31 02:22:37 +00002967 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00002968 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002969 setValue(&I, Result);
2970 }
2971}
2972
2973/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2974static GlobalVariable *ExtractTypeInfo(Value *V) {
2975 V = V->stripPointerCasts();
2976 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2977 assert ((GV || isa<ConstantPointerNull>(V)) &&
2978 "TypeInfo must be a global variable or NULL");
2979 return GV;
2980}
2981
2982namespace llvm {
2983
2984/// AddCatchInfo - Extract the personality and type infos from an eh.selector
2985/// call, and add them to the specified machine basic block.
2986void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2987 MachineBasicBlock *MBB) {
2988 // Inform the MachineModuleInfo of the personality for this landing pad.
2989 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2990 assert(CE->getOpcode() == Instruction::BitCast &&
2991 isa<Function>(CE->getOperand(0)) &&
2992 "Personality should be a function");
2993 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2994
2995 // Gather all the type infos for this landing pad and pass them along to
2996 // MachineModuleInfo.
2997 std::vector<GlobalVariable *> TyInfo;
2998 unsigned N = I.getNumOperands();
2999
3000 for (unsigned i = N - 1; i > 2; --i) {
3001 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3002 unsigned FilterLength = CI->getZExtValue();
3003 unsigned FirstCatch = i + FilterLength + !FilterLength;
3004 assert (FirstCatch <= N && "Invalid filter length");
3005
3006 if (FirstCatch < N) {
3007 TyInfo.reserve(N - FirstCatch);
3008 for (unsigned j = FirstCatch; j < N; ++j)
3009 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3010 MMI->addCatchTypeInfo(MBB, TyInfo);
3011 TyInfo.clear();
3012 }
3013
3014 if (!FilterLength) {
3015 // Cleanup.
3016 MMI->addCleanup(MBB);
3017 } else {
3018 // Filter.
3019 TyInfo.reserve(FilterLength - 1);
3020 for (unsigned j = i + 1; j < FirstCatch; ++j)
3021 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3022 MMI->addFilterTypeInfo(MBB, TyInfo);
3023 TyInfo.clear();
3024 }
3025
3026 N = i;
3027 }
3028 }
3029
3030 if (N > 3) {
3031 TyInfo.reserve(N - 3);
3032 for (unsigned j = 3; j < N; ++j)
3033 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3034 MMI->addCatchTypeInfo(MBB, TyInfo);
3035 }
3036}
3037
3038}
3039
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003040/// GetSignificand - Get the significand and build it into a floating-point
3041/// number with exponent of 1:
3042///
3043/// Op = (Op & 0x007fffff) | 0x3f800000;
3044///
3045/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003046static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003047GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
3048 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003049 DAG.getConstant(0x007fffff, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003050 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003051 DAG.getConstant(0x3f800000, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003052 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003053}
3054
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003055/// GetExponent - Get the exponent:
3056///
Bill Wendlinge9a72862009-01-20 21:17:57 +00003057/// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003058///
3059/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00003060static SDValue
Dale Johannesen66978ee2009-01-31 02:22:37 +00003061GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3062 DebugLoc dl) {
3063 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003064 DAG.getConstant(0x7f800000, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003065 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
Duncan Sands92abc622009-01-31 15:50:11 +00003066 DAG.getConstant(23, TLI.getPointerTy()));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003067 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
Bill Wendlinge9a72862009-01-20 21:17:57 +00003068 DAG.getConstant(127, MVT::i32));
Dale Johannesen66978ee2009-01-31 02:22:37 +00003069 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00003070}
3071
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003072/// getF32Constant - Get 32-bit floating point constant.
3073static SDValue
3074getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3075 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3076}
3077
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003078/// Inlined utility function to implement binary input atomic intrinsics for
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003079/// visitIntrinsicCall: I is a call instruction
3080/// Op is the associated NodeType for I
3081const char *
3082SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003083 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003084 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00003085 DAG.getAtomic(Op, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003086 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003087 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003088 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00003089 getValue(I.getOperand(2)),
3090 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003091 setValue(&I, L);
3092 DAG.setRoot(L.getValue(1));
3093 return 0;
3094}
3095
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003096// implVisitAluOverflow - Lower arithmetic overflow instrinsics.
Bill Wendling74c37652008-12-09 22:08:41 +00003097const char *
3098SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003099 SDValue Op1 = getValue(I.getOperand(1));
3100 SDValue Op2 = getValue(I.getOperand(2));
Bill Wendling74c37652008-12-09 22:08:41 +00003101
Dan Gohmanfc166572009-04-09 23:54:40 +00003102 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
3103 SDValue Result = DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2);
Bill Wendling74c37652008-12-09 22:08:41 +00003104
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00003105 setValue(&I, Result);
3106 return 0;
3107}
Bill Wendling74c37652008-12-09 22:08:41 +00003108
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003109/// visitExp - Lower an exp intrinsic. Handles the special sequences for
3110/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003111void
3112SelectionDAGLowering::visitExp(CallInst &I) {
3113 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003114 DebugLoc dl = getCurDebugLoc();
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003115
3116 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3117 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3118 SDValue Op = getValue(I.getOperand(1));
3119
3120 // Put the exponent in the right bit position for later addition to the
3121 // final result:
3122 //
3123 // #define LOG2OFe 1.4426950f
3124 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003125 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003126 getF32Constant(DAG, 0x3fb8aa3b));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003127 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003128
3129 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003130 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3131 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003132
3133 // IntegerPartOfX <<= 23;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003134 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003135 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003136
3137 if (LimitFloatPrecision <= 6) {
3138 // For floating-point precision of 6:
3139 //
3140 // TwoToFractionalPartOfX =
3141 // 0.997535578f +
3142 // (0.735607626f + 0.252464424f * x) * x;
3143 //
3144 // error 0.0144103317, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003145 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003146 getF32Constant(DAG, 0x3e814304));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003147 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003148 getF32Constant(DAG, 0x3f3c50c8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003149 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3150 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003151 getF32Constant(DAG, 0x3f7f5e7e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003152 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003153
3154 // Add the exponent into the result in integer domain.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003155 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003156 TwoToFracPartOfX, IntegerPartOfX);
3157
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003158 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003159 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3160 // For floating-point precision of 12:
3161 //
3162 // TwoToFractionalPartOfX =
3163 // 0.999892986f +
3164 // (0.696457318f +
3165 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3166 //
3167 // 0.000107046256 error, which is 13 to 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003168 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003169 getF32Constant(DAG, 0x3da235e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003170 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003171 getF32Constant(DAG, 0x3e65b8f3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003172 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3173 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003174 getF32Constant(DAG, 0x3f324b07));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003175 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3176 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003177 getF32Constant(DAG, 0x3f7ff8fd));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003178 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003179
3180 // Add the exponent into the result in integer domain.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003181 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003182 TwoToFracPartOfX, IntegerPartOfX);
3183
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003184 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003185 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3186 // For floating-point precision of 18:
3187 //
3188 // TwoToFractionalPartOfX =
3189 // 0.999999982f +
3190 // (0.693148872f +
3191 // (0.240227044f +
3192 // (0.554906021e-1f +
3193 // (0.961591928e-2f +
3194 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3195 //
3196 // error 2.47208000*10^(-7), which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003197 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003198 getF32Constant(DAG, 0x3924b03e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003199 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003200 getF32Constant(DAG, 0x3ab24b87));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003201 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3202 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003203 getF32Constant(DAG, 0x3c1d8c17));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003204 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3205 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003206 getF32Constant(DAG, 0x3d634a1d));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003207 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3208 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003209 getF32Constant(DAG, 0x3e75fe14));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003210 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3211 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003212 getF32Constant(DAG, 0x3f317234));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003213 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3214 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003215 getF32Constant(DAG, 0x3f800000));
Scott Michelfdc40a02009-02-17 22:15:04 +00003216 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003217 MVT::i32, t13);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003218
3219 // Add the exponent into the result in integer domain.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003220 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003221 TwoToFracPartOfX, IntegerPartOfX);
3222
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003223 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003224 }
3225 } else {
3226 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003227 result = DAG.getNode(ISD::FEXP, dl,
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003228 getValue(I.getOperand(1)).getValueType(),
3229 getValue(I.getOperand(1)));
3230 }
3231
Dale Johannesen59e577f2008-09-05 18:38:42 +00003232 setValue(&I, result);
3233}
3234
Bill Wendling39150252008-09-09 20:39:27 +00003235/// visitLog - Lower a log intrinsic. Handles the special sequences for
3236/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003237void
3238SelectionDAGLowering::visitLog(CallInst &I) {
3239 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003240 DebugLoc dl = getCurDebugLoc();
Bill Wendling39150252008-09-09 20:39:27 +00003241
3242 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3243 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3244 SDValue Op = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003245 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling39150252008-09-09 20:39:27 +00003246
3247 // Scale the exponent by log(2) [0.69314718f].
Dale Johannesen66978ee2009-01-31 02:22:37 +00003248 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003249 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003250 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003251
3252 // Get the significand and build it into a floating-point number with
3253 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003254 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling39150252008-09-09 20:39:27 +00003255
3256 if (LimitFloatPrecision <= 6) {
3257 // For floating-point precision of 6:
3258 //
3259 // LogofMantissa =
3260 // -1.1609546f +
3261 // (1.4034025f - 0.23903021f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003262 //
Bill Wendling39150252008-09-09 20:39:27 +00003263 // error 0.0034276066, which is better than 8 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003264 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003265 getF32Constant(DAG, 0xbe74c456));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003266 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003267 getF32Constant(DAG, 0x3fb3a2b1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003268 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3269 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003270 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00003271
Scott Michelfdc40a02009-02-17 22:15:04 +00003272 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003273 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003274 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3275 // For floating-point precision of 12:
3276 //
3277 // LogOfMantissa =
3278 // -1.7417939f +
3279 // (2.8212026f +
3280 // (-1.4699568f +
3281 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3282 //
3283 // error 0.000061011436, which is 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003284 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003285 getF32Constant(DAG, 0xbd67b6d6));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003286 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003287 getF32Constant(DAG, 0x3ee4f4b8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003288 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3289 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003290 getF32Constant(DAG, 0x3fbc278b));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003291 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3292 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003293 getF32Constant(DAG, 0x40348e95));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003294 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3295 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003296 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00003297
Scott Michelfdc40a02009-02-17 22:15:04 +00003298 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003299 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003300 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3301 // For floating-point precision of 18:
3302 //
3303 // LogOfMantissa =
3304 // -2.1072184f +
3305 // (4.2372794f +
3306 // (-3.7029485f +
3307 // (2.2781945f +
3308 // (-0.87823314f +
3309 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3310 //
3311 // error 0.0000023660568, which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003312 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003313 getF32Constant(DAG, 0xbc91e5ac));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003314 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003315 getF32Constant(DAG, 0x3e4350aa));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003316 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3317 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003318 getF32Constant(DAG, 0x3f60d3e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003319 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3320 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003321 getF32Constant(DAG, 0x4011cdf0));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003322 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3323 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003324 getF32Constant(DAG, 0x406cfd1c));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003325 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3326 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003327 getF32Constant(DAG, 0x408797cb));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003328 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3329 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003330 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003331
Scott Michelfdc40a02009-02-17 22:15:04 +00003332 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003333 MVT::f32, LogOfExponent, LogOfMantissa);
Bill Wendling39150252008-09-09 20:39:27 +00003334 }
3335 } else {
3336 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003337 result = DAG.getNode(ISD::FLOG, dl,
Bill Wendling39150252008-09-09 20:39:27 +00003338 getValue(I.getOperand(1)).getValueType(),
3339 getValue(I.getOperand(1)));
3340 }
3341
Dale Johannesen59e577f2008-09-05 18:38:42 +00003342 setValue(&I, result);
3343}
3344
Bill Wendling3eb59402008-09-09 00:28:24 +00003345/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3346/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003347void
3348SelectionDAGLowering::visitLog2(CallInst &I) {
3349 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003350 DebugLoc dl = getCurDebugLoc();
Bill Wendling3eb59402008-09-09 00:28:24 +00003351
Dale Johannesen853244f2008-09-05 23:49:37 +00003352 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003353 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3354 SDValue Op = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003355 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003356
Bill Wendling39150252008-09-09 20:39:27 +00003357 // Get the exponent.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003358 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00003359
3360 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003361 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003362 SDValue X = GetSignificand(DAG, Op1, dl);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003363
Bill Wendling3eb59402008-09-09 00:28:24 +00003364 // Different possible minimax approximations of significand in
3365 // floating-point for various degrees of accuracy over [1,2].
3366 if (LimitFloatPrecision <= 6) {
3367 // For floating-point precision of 6:
3368 //
3369 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3370 //
3371 // error 0.0049451742, which is more than 7 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003372 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003373 getF32Constant(DAG, 0xbeb08fe0));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003374 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003375 getF32Constant(DAG, 0x40019463));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003376 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3377 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003378 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003379
Scott Michelfdc40a02009-02-17 22:15:04 +00003380 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003381 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003382 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3383 // For floating-point precision of 12:
3384 //
3385 // Log2ofMantissa =
3386 // -2.51285454f +
3387 // (4.07009056f +
3388 // (-2.12067489f +
3389 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003390 //
Bill Wendling3eb59402008-09-09 00:28:24 +00003391 // error 0.0000876136000, which is better than 13 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003392 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003393 getF32Constant(DAG, 0xbda7262e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003394 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003395 getF32Constant(DAG, 0x3f25280b));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003396 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3397 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003398 getF32Constant(DAG, 0x4007b923));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003399 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3400 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003401 getF32Constant(DAG, 0x40823e2f));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003402 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3403 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003404 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003405
Scott Michelfdc40a02009-02-17 22:15:04 +00003406 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003407 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003408 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3409 // For floating-point precision of 18:
3410 //
3411 // Log2ofMantissa =
3412 // -3.0400495f +
3413 // (6.1129976f +
3414 // (-5.3420409f +
3415 // (3.2865683f +
3416 // (-1.2669343f +
3417 // (0.27515199f -
3418 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3419 //
3420 // error 0.0000018516, which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003421 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003422 getF32Constant(DAG, 0xbcd2769e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003423 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003424 getF32Constant(DAG, 0x3e8ce0b9));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003425 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3426 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003427 getF32Constant(DAG, 0x3fa22ae7));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003428 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3429 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003430 getF32Constant(DAG, 0x40525723));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003431 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3432 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003433 getF32Constant(DAG, 0x40aaf200));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003434 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3435 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003436 getF32Constant(DAG, 0x40c39dad));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003437 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3438 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003439 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003440
Scott Michelfdc40a02009-02-17 22:15:04 +00003441 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003442 MVT::f32, LogOfExponent, Log2ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003443 }
Dale Johannesen853244f2008-09-05 23:49:37 +00003444 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003445 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003446 result = DAG.getNode(ISD::FLOG2, dl,
Dale Johannesen853244f2008-09-05 23:49:37 +00003447 getValue(I.getOperand(1)).getValueType(),
3448 getValue(I.getOperand(1)));
3449 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003450
Dale Johannesen59e577f2008-09-05 18:38:42 +00003451 setValue(&I, result);
3452}
3453
Bill Wendling3eb59402008-09-09 00:28:24 +00003454/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3455/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003456void
3457SelectionDAGLowering::visitLog10(CallInst &I) {
3458 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003459 DebugLoc dl = getCurDebugLoc();
Bill Wendling181b6272008-10-19 20:34:04 +00003460
Dale Johannesen852680a2008-09-05 21:27:19 +00003461 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003462 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3463 SDValue Op = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003464 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
Bill Wendling3eb59402008-09-09 00:28:24 +00003465
Bill Wendling39150252008-09-09 20:39:27 +00003466 // Scale the exponent by log10(2) [0.30102999f].
Dale Johannesen66978ee2009-01-31 02:22:37 +00003467 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003468 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003469 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003470
3471 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003472 // exponent of 1.
Dale Johannesen66978ee2009-01-31 02:22:37 +00003473 SDValue X = GetSignificand(DAG, Op1, dl);
Bill Wendling3eb59402008-09-09 00:28:24 +00003474
3475 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003476 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003477 //
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003478 // Log10ofMantissa =
3479 // -0.50419619f +
3480 // (0.60948995f - 0.10380950f * x) * x;
3481 //
3482 // error 0.0014886165, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003483 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003484 getF32Constant(DAG, 0xbdd49a13));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003485 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003486 getF32Constant(DAG, 0x3f1c0789));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003487 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3488 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003489 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003490
Scott Michelfdc40a02009-02-17 22:15:04 +00003491 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003492 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003493 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3494 // For floating-point precision of 12:
3495 //
3496 // Log10ofMantissa =
3497 // -0.64831180f +
3498 // (0.91751397f +
3499 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3500 //
3501 // error 0.00019228036, which is better than 12 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003502 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003503 getF32Constant(DAG, 0x3d431f31));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003504 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003505 getF32Constant(DAG, 0x3ea21fb2));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003506 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3507 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003508 getF32Constant(DAG, 0x3f6ae232));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003509 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3510 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003511 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00003512
Scott Michelfdc40a02009-02-17 22:15:04 +00003513 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003514 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003515 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003516 // For floating-point precision of 18:
3517 //
3518 // Log10ofMantissa =
3519 // -0.84299375f +
3520 // (1.5327582f +
3521 // (-1.0688956f +
3522 // (0.49102474f +
3523 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3524 //
3525 // error 0.0000037995730, which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003526 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003527 getF32Constant(DAG, 0x3c5d51ce));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003528 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003529 getF32Constant(DAG, 0x3e00685a));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003530 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3531 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003532 getF32Constant(DAG, 0x3efb6798));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003533 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3534 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003535 getF32Constant(DAG, 0x3f88d192));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003536 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3537 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003538 getF32Constant(DAG, 0x3fc4316c));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003539 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3540 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003541 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003542
Scott Michelfdc40a02009-02-17 22:15:04 +00003543 result = DAG.getNode(ISD::FADD, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003544 MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003545 }
Dale Johannesen852680a2008-09-05 21:27:19 +00003546 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003547 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003548 result = DAG.getNode(ISD::FLOG10, dl,
Dale Johannesen852680a2008-09-05 21:27:19 +00003549 getValue(I.getOperand(1)).getValueType(),
3550 getValue(I.getOperand(1)));
3551 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003552
Dale Johannesen59e577f2008-09-05 18:38:42 +00003553 setValue(&I, result);
3554}
3555
Bill Wendlinge10c8142008-09-09 22:39:21 +00003556/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3557/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003558void
3559SelectionDAGLowering::visitExp2(CallInst &I) {
3560 SDValue result;
Dale Johannesen66978ee2009-01-31 02:22:37 +00003561 DebugLoc dl = getCurDebugLoc();
Bill Wendlinge10c8142008-09-09 22:39:21 +00003562
Dale Johannesen601d3c02008-09-05 01:48:15 +00003563 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00003564 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3565 SDValue Op = getValue(I.getOperand(1));
3566
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003567 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003568
3569 // FractionalPartOfX = x - (float)IntegerPartOfX;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003570 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3571 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003572
3573 // IntegerPartOfX <<= 23;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003574 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003575 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003576
3577 if (LimitFloatPrecision <= 6) {
3578 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003579 //
Bill Wendlinge10c8142008-09-09 22:39:21 +00003580 // TwoToFractionalPartOfX =
3581 // 0.997535578f +
3582 // (0.735607626f + 0.252464424f * x) * x;
3583 //
3584 // error 0.0144103317, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003585 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003586 getF32Constant(DAG, 0x3e814304));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003587 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003588 getF32Constant(DAG, 0x3f3c50c8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003589 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3590 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003591 getF32Constant(DAG, 0x3f7f5e7e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003592 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003593 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003594 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003595
Scott Michelfdc40a02009-02-17 22:15:04 +00003596 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003597 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003598 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3599 // For floating-point precision of 12:
3600 //
3601 // TwoToFractionalPartOfX =
3602 // 0.999892986f +
3603 // (0.696457318f +
3604 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3605 //
3606 // error 0.000107046256, which is 13 to 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003607 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003608 getF32Constant(DAG, 0x3da235e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003609 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003610 getF32Constant(DAG, 0x3e65b8f3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003611 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3612 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003613 getF32Constant(DAG, 0x3f324b07));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003614 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3615 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003616 getF32Constant(DAG, 0x3f7ff8fd));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003617 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003618 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003619 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003620
Scott Michelfdc40a02009-02-17 22:15:04 +00003621 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003622 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003623 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3624 // For floating-point precision of 18:
3625 //
3626 // TwoToFractionalPartOfX =
3627 // 0.999999982f +
3628 // (0.693148872f +
3629 // (0.240227044f +
3630 // (0.554906021e-1f +
3631 // (0.961591928e-2f +
3632 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3633 // error 2.47208000*10^(-7), which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003634 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003635 getF32Constant(DAG, 0x3924b03e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003636 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003637 getF32Constant(DAG, 0x3ab24b87));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003638 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3639 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003640 getF32Constant(DAG, 0x3c1d8c17));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003641 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3642 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003643 getF32Constant(DAG, 0x3d634a1d));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003644 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3645 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003646 getF32Constant(DAG, 0x3e75fe14));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003647 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3648 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003649 getF32Constant(DAG, 0x3f317234));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003650 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3651 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003652 getF32Constant(DAG, 0x3f800000));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003653 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003654 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003655 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003656
Scott Michelfdc40a02009-02-17 22:15:04 +00003657 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003658 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlinge10c8142008-09-09 22:39:21 +00003659 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00003660 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003661 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003662 result = DAG.getNode(ISD::FEXP2, dl,
Dale Johannesen601d3c02008-09-05 01:48:15 +00003663 getValue(I.getOperand(1)).getValueType(),
3664 getValue(I.getOperand(1)));
3665 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00003666
Dale Johannesen601d3c02008-09-05 01:48:15 +00003667 setValue(&I, result);
3668}
3669
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003670/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3671/// limited-precision mode with x == 10.0f.
3672void
3673SelectionDAGLowering::visitPow(CallInst &I) {
3674 SDValue result;
3675 Value *Val = I.getOperand(1);
Dale Johannesen66978ee2009-01-31 02:22:37 +00003676 DebugLoc dl = getCurDebugLoc();
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003677 bool IsExp10 = false;
3678
3679 if (getValue(Val).getValueType() == MVT::f32 &&
Bill Wendling277fc242008-09-10 00:24:59 +00003680 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003681 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3682 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3683 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3684 APFloat Ten(10.0f);
3685 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3686 }
3687 }
3688 }
3689
3690 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3691 SDValue Op = getValue(I.getOperand(2));
3692
3693 // Put the exponent in the right bit position for later addition to the
3694 // final result:
3695 //
3696 // #define LOG2OF10 3.3219281f
3697 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003698 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003699 getF32Constant(DAG, 0x40549a78));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003700 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003701
3702 // FractionalPartOfX = x - (float)IntegerPartOfX;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003703 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3704 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003705
3706 // IntegerPartOfX <<= 23;
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003707 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
Duncan Sands92abc622009-01-31 15:50:11 +00003708 DAG.getConstant(23, TLI.getPointerTy()));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003709
3710 if (LimitFloatPrecision <= 6) {
3711 // For floating-point precision of 6:
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003712 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003713 // twoToFractionalPartOfX =
3714 // 0.997535578f +
3715 // (0.735607626f + 0.252464424f * x) * x;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00003716 //
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003717 // error 0.0144103317, which is 6 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003718 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003719 getF32Constant(DAG, 0x3e814304));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003720 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003721 getF32Constant(DAG, 0x3f3c50c8));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003722 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3723 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003724 getF32Constant(DAG, 0x3f7f5e7e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003725 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003726 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003727 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003728
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003729 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3730 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003731 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3732 // For floating-point precision of 12:
3733 //
3734 // TwoToFractionalPartOfX =
3735 // 0.999892986f +
3736 // (0.696457318f +
3737 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3738 //
3739 // error 0.000107046256, which is 13 to 14 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003740 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003741 getF32Constant(DAG, 0x3da235e3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003742 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003743 getF32Constant(DAG, 0x3e65b8f3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003744 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3745 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003746 getF32Constant(DAG, 0x3f324b07));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003747 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3748 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003749 getF32Constant(DAG, 0x3f7ff8fd));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003750 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003751 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003752 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003753
Scott Michelfdc40a02009-02-17 22:15:04 +00003754 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003755 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003756 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3757 // For floating-point precision of 18:
3758 //
3759 // TwoToFractionalPartOfX =
3760 // 0.999999982f +
3761 // (0.693148872f +
3762 // (0.240227044f +
3763 // (0.554906021e-1f +
3764 // (0.961591928e-2f +
3765 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3766 // error 2.47208000*10^(-7), which is better than 18 bits
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003767 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003768 getF32Constant(DAG, 0x3924b03e));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003769 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003770 getF32Constant(DAG, 0x3ab24b87));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003771 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3772 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003773 getF32Constant(DAG, 0x3c1d8c17));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003774 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3775 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003776 getF32Constant(DAG, 0x3d634a1d));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003777 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3778 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003779 getF32Constant(DAG, 0x3e75fe14));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003780 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3781 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003782 getF32Constant(DAG, 0x3f317234));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003783 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3784 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003785 getF32Constant(DAG, 0x3f800000));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003786 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003787 SDValue TwoToFractionalPartOfX =
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003788 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003789
Scott Michelfdc40a02009-02-17 22:15:04 +00003790 result = DAG.getNode(ISD::BIT_CONVERT, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003791 MVT::f32, TwoToFractionalPartOfX);
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003792 }
3793 } else {
3794 // No special expansion.
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003795 result = DAG.getNode(ISD::FPOW, dl,
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003796 getValue(I.getOperand(1)).getValueType(),
3797 getValue(I.getOperand(1)),
3798 getValue(I.getOperand(2)));
3799 }
3800
3801 setValue(&I, result);
3802}
3803
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003804/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3805/// we want to emit this as a call to a named external function, return the name
3806/// otherwise lower it and return null.
3807const char *
3808SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00003809 DebugLoc dl = getCurDebugLoc();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003810 switch (Intrinsic) {
3811 default:
3812 // By default, turn this into a target intrinsic node.
3813 visitTargetIntrinsic(I, Intrinsic);
3814 return 0;
3815 case Intrinsic::vastart: visitVAStart(I); return 0;
3816 case Intrinsic::vaend: visitVAEnd(I); return 0;
3817 case Intrinsic::vacopy: visitVACopy(I); return 0;
3818 case Intrinsic::returnaddress:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003819 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003820 getValue(I.getOperand(1))));
3821 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00003822 case Intrinsic::frameaddress:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003823 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003824 getValue(I.getOperand(1))));
3825 return 0;
3826 case Intrinsic::setjmp:
3827 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3828 break;
3829 case Intrinsic::longjmp:
3830 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3831 break;
Chris Lattner824b9582008-11-21 16:42:48 +00003832 case Intrinsic::memcpy: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003833 SDValue Op1 = getValue(I.getOperand(1));
3834 SDValue Op2 = getValue(I.getOperand(2));
3835 SDValue Op3 = getValue(I.getOperand(3));
3836 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Dale Johannesena04b7572009-02-03 23:04:43 +00003837 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003838 I.getOperand(1), 0, I.getOperand(2), 0));
3839 return 0;
3840 }
Chris Lattner824b9582008-11-21 16:42:48 +00003841 case Intrinsic::memset: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003842 SDValue Op1 = getValue(I.getOperand(1));
3843 SDValue Op2 = getValue(I.getOperand(2));
3844 SDValue Op3 = getValue(I.getOperand(3));
3845 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
Dale Johannesena04b7572009-02-03 23:04:43 +00003846 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003847 I.getOperand(1), 0));
3848 return 0;
3849 }
Chris Lattner824b9582008-11-21 16:42:48 +00003850 case Intrinsic::memmove: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003851 SDValue Op1 = getValue(I.getOperand(1));
3852 SDValue Op2 = getValue(I.getOperand(2));
3853 SDValue Op3 = getValue(I.getOperand(3));
3854 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3855
3856 // If the source and destination are known to not be aliases, we can
3857 // lower memmove as memcpy.
3858 uint64_t Size = -1ULL;
3859 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003860 Size = C->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003861 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3862 AliasAnalysis::NoAlias) {
Dale Johannesena04b7572009-02-03 23:04:43 +00003863 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003864 I.getOperand(1), 0, I.getOperand(2), 0));
3865 return 0;
3866 }
3867
Dale Johannesena04b7572009-02-03 23:04:43 +00003868 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003869 I.getOperand(1), 0, I.getOperand(2), 0));
3870 return 0;
3871 }
3872 case Intrinsic::dbg_stoppoint: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003873 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
Devang Patel7e1e31f2009-07-02 22:43:26 +00003874 if (isValidDebugInfoIntrinsic(SPI, CodeGenOpt::Default)) {
Evan Chenge3d42322009-02-25 07:04:34 +00003875 MachineFunction &MF = DAG.getMachineFunction();
Devang Patel7e1e31f2009-07-02 22:43:26 +00003876 DebugLoc Loc = ExtractDebugLocation(SPI, MF.getDebugLocInfo());
Chris Lattneraf29a522009-05-04 22:10:05 +00003877 setCurDebugLoc(Loc);
Devang Patel7e1e31f2009-07-02 22:43:26 +00003878
Bill Wendling98a366d2009-04-29 23:29:43 +00003879 if (OptLevel == CodeGenOpt::None)
Chris Lattneraf29a522009-05-04 22:10:05 +00003880 DAG.setRoot(DAG.getDbgStopPoint(Loc, getRoot(),
Dale Johannesenbeaec4c2009-03-25 17:36:08 +00003881 SPI.getLine(),
3882 SPI.getColumn(),
3883 SPI.getContext()));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003884 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003885 return 0;
3886 }
3887 case Intrinsic::dbg_region_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003888 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003889 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
Devang Patel7e1e31f2009-07-02 22:43:26 +00003890 if (isValidDebugInfoIntrinsic(RSI, OptLevel) && DW
3891 && DW->ShouldEmitDwarfDebug()) {
Bill Wendlingdf7d5d32009-05-21 00:04:55 +00003892 unsigned LabelID =
3893 DW->RecordRegionStart(cast<GlobalVariable>(RSI.getContext()));
Devang Patel48c7fa22009-04-13 18:13:16 +00003894 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3895 getRoot(), LabelID));
Bill Wendling92c1e122009-02-13 02:16:35 +00003896 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003897 return 0;
3898 }
3899 case Intrinsic::dbg_region_end: {
Devang Patel83489bb2009-01-13 00:35:13 +00003900 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003901 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
Devang Patel0f7fef32009-04-13 17:02:03 +00003902
Devang Patel7e1e31f2009-07-02 22:43:26 +00003903 if (!isValidDebugInfoIntrinsic(REI, OptLevel) || !DW
3904 || !DW->ShouldEmitDwarfDebug())
3905 return 0;
Bill Wendling6c4311d2009-05-08 21:14:49 +00003906
Devang Patel7e1e31f2009-07-02 22:43:26 +00003907 MachineFunction &MF = DAG.getMachineFunction();
3908 DISubprogram Subprogram(cast<GlobalVariable>(REI.getContext()));
3909
3910 if (isInlinedFnEnd(REI, MF.getFunction())) {
3911 // This is end of inlined function. Debugging information for inlined
3912 // function is not handled yet (only supported by FastISel).
3913 if (OptLevel == CodeGenOpt::None) {
3914 unsigned ID = DW->RecordInlinedFnEnd(Subprogram);
3915 if (ID != 0)
3916 // Returned ID is 0 if this is unbalanced "end of inlined
3917 // scope". This could happen if optimizer eats dbg intrinsics or
3918 // "beginning of inlined scope" is not recoginized due to missing
3919 // location info. In such cases, do ignore this region.end.
3920 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3921 getRoot(), ID));
Devang Patel0f7fef32009-04-13 17:02:03 +00003922 }
Devang Patel7e1e31f2009-07-02 22:43:26 +00003923 return 0;
3924 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003925
Devang Patel7e1e31f2009-07-02 22:43:26 +00003926 unsigned LabelID =
3927 DW->RecordRegionEnd(cast<GlobalVariable>(REI.getContext()));
3928 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3929 getRoot(), LabelID));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003930 return 0;
3931 }
3932 case Intrinsic::dbg_func_start: {
Devang Patel83489bb2009-01-13 00:35:13 +00003933 DwarfWriter *DW = DAG.getDwarfWriter();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003934 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
Devang Patel7e1e31f2009-07-02 22:43:26 +00003935 if (!isValidDebugInfoIntrinsic(FSI, CodeGenOpt::None) || !DW
3936 || !DW->ShouldEmitDwarfDebug())
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00003937 return 0;
Devang Patel16f2ffd2009-04-16 02:33:41 +00003938
Argyrios Kyrtzidis77eaa682009-05-03 08:50:41 +00003939 MachineFunction &MF = DAG.getMachineFunction();
Devang Patel7e1e31f2009-07-02 22:43:26 +00003940 // This is a beginning of an inlined function.
3941 if (isInlinedFnStart(FSI, MF.getFunction())) {
3942 if (OptLevel != CodeGenOpt::None)
3943 // FIXME: Debugging informaation for inlined function is only
3944 // supported at CodeGenOpt::Node.
3945 return 0;
3946
Bill Wendlingc677fe52009-05-10 00:10:50 +00003947 DebugLoc PrevLoc = CurDebugLoc;
Devang Patel07b0ec02009-07-02 00:08:09 +00003948 // If llvm.dbg.func.start is seen in a new block before any
3949 // llvm.dbg.stoppoint intrinsic then the location info is unknown.
3950 // FIXME : Why DebugLoc is reset at the beginning of each block ?
3951 if (PrevLoc.isUnknown())
3952 return 0;
Devang Patel07b0ec02009-07-02 00:08:09 +00003953
Devang Patel7e1e31f2009-07-02 22:43:26 +00003954 // Record the source line.
3955 setCurDebugLoc(ExtractDebugLocation(FSI, MF.getDebugLocInfo()));
3956
3957 DebugLocTuple PrevLocTpl = MF.getDebugLocTuple(PrevLoc);
3958 DISubprogram SP(cast<GlobalVariable>(FSI.getSubprogram()));
3959 DICompileUnit CU(PrevLocTpl.CompileUnit);
3960 unsigned LabelID = DW->RecordInlinedFnStart(SP, CU,
3961 PrevLocTpl.Line,
3962 PrevLocTpl.Col);
3963 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3964 getRoot(), LabelID));
Devang Patel07b0ec02009-07-02 00:08:09 +00003965 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003966 }
3967
Devang Patel07b0ec02009-07-02 00:08:09 +00003968 // This is a beginning of a new function.
Devang Patel7e1e31f2009-07-02 22:43:26 +00003969 MF.setDefaultDebugLoc(ExtractDebugLocation(FSI, MF.getDebugLocInfo()));
Devang Patel07b0ec02009-07-02 00:08:09 +00003970
Devang Patel7e1e31f2009-07-02 22:43:26 +00003971 // llvm.dbg.func_start also defines beginning of function scope.
3972 DW->RecordRegionStart(cast<GlobalVariable>(FSI.getSubprogram()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003973 return 0;
3974 }
Bill Wendling92c1e122009-02-13 02:16:35 +00003975 case Intrinsic::dbg_declare: {
Devang Patel7e1e31f2009-07-02 22:43:26 +00003976 if (OptLevel != CodeGenOpt::None)
3977 // FIXME: Variable debug info is not supported here.
3978 return 0;
3979
3980 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3981 if (!isValidDebugInfoIntrinsic(DI, CodeGenOpt::None))
3982 return 0;
3983
3984 Value *Variable = DI.getVariable();
3985 DAG.setRoot(DAG.getNode(ISD::DECLARE, dl, MVT::Other, getRoot(),
3986 getValue(DI.getAddress()), getValue(Variable)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003987 return 0;
Bill Wendling92c1e122009-02-13 02:16:35 +00003988 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003989 case Intrinsic::eh_exception: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003990 // Insert the EXCEPTIONADDR instruction.
Duncan Sandsb0f1e172009-05-22 20:36:31 +00003991 assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003992 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3993 SDValue Ops[1];
3994 Ops[0] = DAG.getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00003995 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003996 setValue(&I, Op);
3997 DAG.setRoot(Op.getValue(1));
3998 return 0;
3999 }
4000
4001 case Intrinsic::eh_selector_i32:
4002 case Intrinsic::eh_selector_i64: {
4003 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4004 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
4005 MVT::i32 : MVT::i64);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004006
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004007 if (MMI) {
4008 if (CurMBB->isLandingPad())
4009 AddCatchInfo(I, MMI, CurMBB);
4010 else {
4011#ifndef NDEBUG
4012 FuncInfo.CatchInfoLost.insert(&I);
4013#endif
4014 // FIXME: Mark exception selector register as live in. Hack for PR1508.
4015 unsigned Reg = TLI.getExceptionSelectorRegister();
4016 if (Reg) CurMBB->addLiveIn(Reg);
4017 }
4018
4019 // Insert the EHSELECTION instruction.
4020 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
4021 SDValue Ops[2];
4022 Ops[0] = getValue(I.getOperand(1));
4023 Ops[1] = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004024 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004025 setValue(&I, Op);
4026 DAG.setRoot(Op.getValue(1));
4027 } else {
4028 setValue(&I, DAG.getConstant(0, VT));
4029 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004030
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004031 return 0;
4032 }
4033
4034 case Intrinsic::eh_typeid_for_i32:
4035 case Intrinsic::eh_typeid_for_i64: {
4036 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4037 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
4038 MVT::i32 : MVT::i64);
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004039
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004040 if (MMI) {
4041 // Find the type id for the given typeinfo.
4042 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
4043
4044 unsigned TypeID = MMI->getTypeIDFor(GV);
4045 setValue(&I, DAG.getConstant(TypeID, VT));
4046 } else {
4047 // Return something different to eh_selector.
4048 setValue(&I, DAG.getConstant(1, VT));
4049 }
4050
4051 return 0;
4052 }
4053
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004054 case Intrinsic::eh_return_i32:
4055 case Intrinsic::eh_return_i64:
4056 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004057 MMI->setCallsEHReturn(true);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004058 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004059 MVT::Other,
4060 getControlRoot(),
4061 getValue(I.getOperand(1)),
4062 getValue(I.getOperand(2))));
4063 } else {
4064 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
4065 }
4066
4067 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004068 case Intrinsic::eh_unwind_init:
4069 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4070 MMI->setCallsUnwindInit(true);
4071 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004072
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004073 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004074
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004075 case Intrinsic::eh_dwarf_cfa: {
4076 MVT VT = getValue(I.getOperand(1)).getValueType();
4077 SDValue CfaArg;
4078 if (VT.bitsGT(TLI.getPointerTy()))
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004079 CfaArg = DAG.getNode(ISD::TRUNCATE, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004080 TLI.getPointerTy(), getValue(I.getOperand(1)));
4081 else
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004082 CfaArg = DAG.getNode(ISD::SIGN_EXTEND, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004083 TLI.getPointerTy(), getValue(I.getOperand(1)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004084
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004085 SDValue Offset = DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004086 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004087 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004088 TLI.getPointerTy()),
4089 CfaArg);
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004090 setValue(&I, DAG.getNode(ISD::ADD, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004091 TLI.getPointerTy(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004092 DAG.getNode(ISD::FRAMEADDR, dl,
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00004093 TLI.getPointerTy(),
4094 DAG.getConstant(0,
4095 TLI.getPointerTy())),
4096 Offset));
4097 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004098 }
4099
Mon P Wang77cdf302008-11-10 20:54:11 +00004100 case Intrinsic::convertff:
4101 case Intrinsic::convertfsi:
4102 case Intrinsic::convertfui:
4103 case Intrinsic::convertsif:
4104 case Intrinsic::convertuif:
4105 case Intrinsic::convertss:
4106 case Intrinsic::convertsu:
4107 case Intrinsic::convertus:
4108 case Intrinsic::convertuu: {
4109 ISD::CvtCode Code = ISD::CVT_INVALID;
4110 switch (Intrinsic) {
4111 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4112 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4113 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4114 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4115 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4116 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4117 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4118 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4119 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4120 }
4121 MVT DestVT = TLI.getValueType(I.getType());
4122 Value* Op1 = I.getOperand(1);
Dale Johannesena04b7572009-02-03 23:04:43 +00004123 setValue(&I, DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
Mon P Wang77cdf302008-11-10 20:54:11 +00004124 DAG.getValueType(DestVT),
4125 DAG.getValueType(getValue(Op1).getValueType()),
4126 getValue(I.getOperand(2)),
4127 getValue(I.getOperand(3)),
4128 Code));
4129 return 0;
4130 }
4131
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004132 case Intrinsic::sqrt:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004133 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004134 getValue(I.getOperand(1)).getValueType(),
4135 getValue(I.getOperand(1))));
4136 return 0;
4137 case Intrinsic::powi:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004138 setValue(&I, DAG.getNode(ISD::FPOWI, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004139 getValue(I.getOperand(1)).getValueType(),
4140 getValue(I.getOperand(1)),
4141 getValue(I.getOperand(2))));
4142 return 0;
4143 case Intrinsic::sin:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004144 setValue(&I, DAG.getNode(ISD::FSIN, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004145 getValue(I.getOperand(1)).getValueType(),
4146 getValue(I.getOperand(1))));
4147 return 0;
4148 case Intrinsic::cos:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004149 setValue(&I, DAG.getNode(ISD::FCOS, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004150 getValue(I.getOperand(1)).getValueType(),
4151 getValue(I.getOperand(1))));
4152 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004153 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004154 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004155 return 0;
4156 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004157 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004158 return 0;
4159 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004160 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004161 return 0;
4162 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00004163 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004164 return 0;
4165 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00004166 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00004167 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004168 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00004169 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004170 return 0;
4171 case Intrinsic::pcmarker: {
4172 SDValue Tmp = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004173 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004174 return 0;
4175 }
4176 case Intrinsic::readcyclecounter: {
4177 SDValue Op = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004178 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER, dl,
Dan Gohmanfc166572009-04-09 23:54:40 +00004179 DAG.getVTList(MVT::i64, MVT::Other),
4180 &Op, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004181 setValue(&I, Tmp);
4182 DAG.setRoot(Tmp.getValue(1));
4183 return 0;
4184 }
4185 case Intrinsic::part_select: {
4186 // Currently not implemented: just abort
4187 assert(0 && "part_select intrinsic not implemented");
4188 abort();
4189 }
4190 case Intrinsic::part_set: {
4191 // Currently not implemented: just abort
4192 assert(0 && "part_set intrinsic not implemented");
4193 abort();
4194 }
4195 case Intrinsic::bswap:
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004196 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004197 getValue(I.getOperand(1)).getValueType(),
4198 getValue(I.getOperand(1))));
4199 return 0;
4200 case Intrinsic::cttz: {
4201 SDValue Arg = getValue(I.getOperand(1));
4202 MVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004203 SDValue result = DAG.getNode(ISD::CTTZ, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004204 setValue(&I, result);
4205 return 0;
4206 }
4207 case Intrinsic::ctlz: {
4208 SDValue Arg = getValue(I.getOperand(1));
4209 MVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004210 SDValue result = DAG.getNode(ISD::CTLZ, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004211 setValue(&I, result);
4212 return 0;
4213 }
4214 case Intrinsic::ctpop: {
4215 SDValue Arg = getValue(I.getOperand(1));
4216 MVT Ty = Arg.getValueType();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004217 SDValue result = DAG.getNode(ISD::CTPOP, dl, Ty, Arg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004218 setValue(&I, result);
4219 return 0;
4220 }
4221 case Intrinsic::stacksave: {
4222 SDValue Op = getRoot();
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004223 SDValue Tmp = DAG.getNode(ISD::STACKSAVE, dl,
Dan Gohmanfc166572009-04-09 23:54:40 +00004224 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004225 setValue(&I, Tmp);
4226 DAG.setRoot(Tmp.getValue(1));
4227 return 0;
4228 }
4229 case Intrinsic::stackrestore: {
4230 SDValue Tmp = getValue(I.getOperand(1));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004231 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004232 return 0;
4233 }
Bill Wendling57344502008-11-18 11:01:33 +00004234 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00004235 // Emit code into the DAG to store the stack guard onto the stack.
4236 MachineFunction &MF = DAG.getMachineFunction();
4237 MachineFrameInfo *MFI = MF.getFrameInfo();
4238 MVT PtrTy = TLI.getPointerTy();
4239
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004240 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4241 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
Bill Wendlingb2a42982008-11-06 02:29:10 +00004242
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004243 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00004244 MFI->setStackProtectorIndex(FI);
4245
4246 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4247
4248 // Store the stack protector onto the stack.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004249 SDValue Result = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
Bill Wendlingb2a42982008-11-06 02:29:10 +00004250 PseudoSourceValue::getFixedStack(FI),
4251 0, true);
4252 setValue(&I, Result);
4253 DAG.setRoot(Result);
4254 return 0;
4255 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004256 case Intrinsic::var_annotation:
4257 // Discard annotate attributes
4258 return 0;
4259
4260 case Intrinsic::init_trampoline: {
4261 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4262
4263 SDValue Ops[6];
4264 Ops[0] = getRoot();
4265 Ops[1] = getValue(I.getOperand(1));
4266 Ops[2] = getValue(I.getOperand(2));
4267 Ops[3] = getValue(I.getOperand(3));
4268 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4269 Ops[5] = DAG.getSrcValue(F);
4270
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004271 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE, dl,
Dan Gohmanfc166572009-04-09 23:54:40 +00004272 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4273 Ops, 6);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004274
4275 setValue(&I, Tmp);
4276 DAG.setRoot(Tmp.getValue(1));
4277 return 0;
4278 }
4279
4280 case Intrinsic::gcroot:
4281 if (GFI) {
4282 Value *Alloca = I.getOperand(1);
4283 Constant *TypeMap = cast<Constant>(I.getOperand(2));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004284
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004285 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4286 GFI->addStackRoot(FI->getIndex(), TypeMap);
4287 }
4288 return 0;
4289
4290 case Intrinsic::gcread:
4291 case Intrinsic::gcwrite:
4292 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
4293 return 0;
4294
4295 case Intrinsic::flt_rounds: {
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004296 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004297 return 0;
4298 }
4299
4300 case Intrinsic::trap: {
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004301 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004302 return 0;
4303 }
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004304
Bill Wendlingef375462008-11-21 02:38:44 +00004305 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00004306 return implVisitAluOverflow(I, ISD::UADDO);
4307 case Intrinsic::sadd_with_overflow:
4308 return implVisitAluOverflow(I, ISD::SADDO);
4309 case Intrinsic::usub_with_overflow:
4310 return implVisitAluOverflow(I, ISD::USUBO);
4311 case Intrinsic::ssub_with_overflow:
4312 return implVisitAluOverflow(I, ISD::SSUBO);
4313 case Intrinsic::umul_with_overflow:
4314 return implVisitAluOverflow(I, ISD::UMULO);
4315 case Intrinsic::smul_with_overflow:
4316 return implVisitAluOverflow(I, ISD::SMULO);
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004317
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004318 case Intrinsic::prefetch: {
4319 SDValue Ops[4];
4320 Ops[0] = getRoot();
4321 Ops[1] = getValue(I.getOperand(1));
4322 Ops[2] = getValue(I.getOperand(2));
4323 Ops[3] = getValue(I.getOperand(3));
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004324 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004325 return 0;
4326 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004327
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004328 case Intrinsic::memory_barrier: {
4329 SDValue Ops[6];
4330 Ops[0] = getRoot();
4331 for (int x = 1; x < 6; ++x)
4332 Ops[x] = getValue(I.getOperand(x));
4333
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004334 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004335 return 0;
4336 }
4337 case Intrinsic::atomic_cmp_swap: {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004338 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004339 SDValue L =
Dale Johannesen66978ee2009-01-31 02:22:37 +00004340 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004341 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4342 Root,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004343 getValue(I.getOperand(1)),
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004344 getValue(I.getOperand(2)),
4345 getValue(I.getOperand(3)),
4346 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004347 setValue(&I, L);
4348 DAG.setRoot(L.getValue(1));
4349 return 0;
4350 }
4351 case Intrinsic::atomic_load_add:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004352 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004353 case Intrinsic::atomic_load_sub:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004354 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004355 case Intrinsic::atomic_load_or:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004356 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004357 case Intrinsic::atomic_load_xor:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004358 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004359 case Intrinsic::atomic_load_and:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004360 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004361 case Intrinsic::atomic_load_nand:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004362 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004363 case Intrinsic::atomic_load_max:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004364 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004365 case Intrinsic::atomic_load_min:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004366 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004367 case Intrinsic::atomic_load_umin:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004368 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004369 case Intrinsic::atomic_load_umax:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004370 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004371 case Intrinsic::atomic_swap:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004372 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004373 }
4374}
4375
4376
4377void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4378 bool IsTailCall,
4379 MachineBasicBlock *LandingPad) {
4380 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4381 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4382 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4383 unsigned BeginLabel = 0, EndLabel = 0;
4384
4385 TargetLowering::ArgListTy Args;
4386 TargetLowering::ArgListEntry Entry;
4387 Args.reserve(CS.arg_size());
4388 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4389 i != e; ++i) {
4390 SDValue ArgNode = getValue(*i);
4391 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4392
4393 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00004394 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4395 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4396 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4397 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4398 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4399 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004400 Entry.Alignment = CS.getParamAlignment(attrInd);
4401 Args.push_back(Entry);
4402 }
4403
4404 if (LandingPad && MMI) {
4405 // Insert a label before the invoke call to mark the try range. This can be
4406 // used to detect deletion of the invoke via the MachineModuleInfo.
4407 BeginLabel = MMI->NextLabelID();
4408 // Both PendingLoads and PendingExports must be flushed here;
4409 // this call might not return.
4410 (void)getRoot();
Dale Johannesen8ad9b432009-02-04 01:17:06 +00004411 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4412 getControlRoot(), BeginLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004413 }
4414
4415 std::pair<SDValue,SDValue> Result =
4416 TLI.LowerCallTo(getRoot(), CS.getType(),
Devang Patel05988662008-09-25 21:00:45 +00004417 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004418 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
Tilmann Scheller6b61cd12009-07-03 06:44:53 +00004419 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004420 CS.getCallingConv(),
Dan Gohman1937e2f2008-09-16 01:42:28 +00004421 IsTailCall && PerformTailCallOpt,
Dale Johannesen66978ee2009-01-31 02:22:37 +00004422 Callee, Args, DAG, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004423 if (CS.getType() != Type::VoidTy)
4424 setValue(CS.getInstruction(), Result.first);
4425 DAG.setRoot(Result.second);
4426
4427 if (LandingPad && MMI) {
4428 // Insert a label at the end of the invoke call to mark the try range. This
4429 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4430 EndLabel = MMI->NextLabelID();
Dale Johannesen8ad9b432009-02-04 01:17:06 +00004431 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4432 getRoot(), EndLabel));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004433
4434 // Inform MachineModuleInfo of range.
4435 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4436 }
4437}
4438
4439
4440void SelectionDAGLowering::visitCall(CallInst &I) {
4441 const char *RenameFn = 0;
4442 if (Function *F = I.getCalledFunction()) {
4443 if (F->isDeclaration()) {
Dale Johannesen49de9822009-02-05 01:49:45 +00004444 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4445 if (II) {
4446 if (unsigned IID = II->getIntrinsicID(F)) {
4447 RenameFn = visitIntrinsicCall(I, IID);
4448 if (!RenameFn)
4449 return;
4450 }
4451 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004452 if (unsigned IID = F->getIntrinsicID()) {
4453 RenameFn = visitIntrinsicCall(I, IID);
4454 if (!RenameFn)
4455 return;
4456 }
4457 }
4458
4459 // Check for well-known libc/libm calls. If the function is internal, it
4460 // can't be a library call.
4461 unsigned NameLen = F->getNameLen();
Rafael Espindolabb46f522009-01-15 20:18:42 +00004462 if (!F->hasLocalLinkage() && NameLen) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004463 const char *NameStr = F->getNameStart();
4464 if (NameStr[0] == 'c' &&
4465 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4466 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4467 if (I.getNumOperands() == 3 && // Basic sanity checks.
4468 I.getOperand(1)->getType()->isFloatingPoint() &&
4469 I.getType() == I.getOperand(1)->getType() &&
4470 I.getType() == I.getOperand(2)->getType()) {
4471 SDValue LHS = getValue(I.getOperand(1));
4472 SDValue RHS = getValue(I.getOperand(2));
Scott Michelfdc40a02009-02-17 22:15:04 +00004473 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004474 LHS.getValueType(), LHS, RHS));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004475 return;
4476 }
4477 } else if (NameStr[0] == 'f' &&
4478 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4479 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4480 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4481 if (I.getNumOperands() == 2 && // Basic sanity checks.
4482 I.getOperand(1)->getType()->isFloatingPoint() &&
4483 I.getType() == I.getOperand(1)->getType()) {
4484 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004485 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004486 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004487 return;
4488 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004489 } else if (NameStr[0] == 's' &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004490 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4491 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4492 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4493 if (I.getNumOperands() == 2 && // Basic sanity checks.
4494 I.getOperand(1)->getType()->isFloatingPoint() &&
4495 I.getType() == I.getOperand(1)->getType()) {
4496 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004497 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004498 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004499 return;
4500 }
4501 } else if (NameStr[0] == 'c' &&
4502 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4503 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4504 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4505 if (I.getNumOperands() == 2 && // Basic sanity checks.
4506 I.getOperand(1)->getType()->isFloatingPoint() &&
4507 I.getType() == I.getOperand(1)->getType()) {
4508 SDValue Tmp = getValue(I.getOperand(1));
Scott Michelfdc40a02009-02-17 22:15:04 +00004509 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004510 Tmp.getValueType(), Tmp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004511 return;
4512 }
4513 }
4514 }
4515 } else if (isa<InlineAsm>(I.getOperand(0))) {
4516 visitInlineAsm(&I);
4517 return;
4518 }
4519
4520 SDValue Callee;
4521 if (!RenameFn)
4522 Callee = getValue(I.getOperand(0));
4523 else
Bill Wendling056292f2008-09-16 21:48:12 +00004524 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004525
4526 LowerCallTo(&I, Callee, I.isTailCall());
4527}
4528
4529
4530/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004531/// this value and returns the result as a ValueVT value. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004532/// Chain/Flag as the input and updates them for the output Chain/Flag.
4533/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004534SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004535 SDValue &Chain,
4536 SDValue *Flag) const {
4537 // Assemble the legal parts into the final values.
4538 SmallVector<SDValue, 4> Values(ValueVTs.size());
4539 SmallVector<SDValue, 8> Parts;
4540 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4541 // Copy the legal parts from the registers.
4542 MVT ValueVT = ValueVTs[Value];
4543 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4544 MVT RegisterVT = RegVTs[Value];
4545
4546 Parts.resize(NumRegs);
4547 for (unsigned i = 0; i != NumRegs; ++i) {
4548 SDValue P;
4549 if (Flag == 0)
Dale Johannesena04b7572009-02-03 23:04:43 +00004550 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004551 else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004552 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004553 *Flag = P.getValue(2);
4554 }
4555 Chain = P.getValue(1);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004556
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004557 // If the source register was virtual and if we know something about it,
4558 // add an assert node.
4559 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4560 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4561 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4562 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4563 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4564 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004565
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004566 unsigned RegSize = RegisterVT.getSizeInBits();
4567 unsigned NumSignBits = LOI.NumSignBits;
4568 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004569
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004570 // FIXME: We capture more information than the dag can represent. For
4571 // now, just use the tightest assertzext/assertsext possible.
4572 bool isSExt = true;
4573 MVT FromVT(MVT::Other);
4574 if (NumSignBits == RegSize)
4575 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4576 else if (NumZeroBits >= RegSize-1)
4577 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4578 else if (NumSignBits > RegSize-8)
4579 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
Dan Gohman07c26ee2009-03-31 01:38:29 +00004580 else if (NumZeroBits >= RegSize-8)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004581 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4582 else if (NumSignBits > RegSize-16)
Bill Wendling181b6272008-10-19 20:34:04 +00004583 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
Dan Gohman07c26ee2009-03-31 01:38:29 +00004584 else if (NumZeroBits >= RegSize-16)
Bill Wendling181b6272008-10-19 20:34:04 +00004585 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004586 else if (NumSignBits > RegSize-32)
Bill Wendling181b6272008-10-19 20:34:04 +00004587 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
Dan Gohman07c26ee2009-03-31 01:38:29 +00004588 else if (NumZeroBits >= RegSize-32)
Bill Wendling181b6272008-10-19 20:34:04 +00004589 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004590
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004591 if (FromVT != MVT::Other) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00004592 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004593 RegisterVT, P, DAG.getValueType(FromVT));
4594
4595 }
4596 }
4597 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004598
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004599 Parts[i] = P;
4600 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004601
Scott Michelfdc40a02009-02-17 22:15:04 +00004602 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00004603 NumRegs, RegisterVT, ValueVT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004604 Part += NumRegs;
4605 Parts.clear();
4606 }
4607
Dale Johannesen66978ee2009-01-31 02:22:37 +00004608 return DAG.getNode(ISD::MERGE_VALUES, dl,
Duncan Sandsaaffa052008-12-01 11:41:29 +00004609 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4610 &Values[0], ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004611}
4612
4613/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004614/// specified value into the registers specified by this object. This uses
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004615/// Chain/Flag as the input and updates them for the output Chain/Flag.
4616/// If the Flag pointer is NULL, no flag is used.
Dale Johannesen66978ee2009-01-31 02:22:37 +00004617void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004618 SDValue &Chain, SDValue *Flag) const {
4619 // Get the list of the values's legal parts.
4620 unsigned NumRegs = Regs.size();
4621 SmallVector<SDValue, 8> Parts(NumRegs);
4622 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4623 MVT ValueVT = ValueVTs[Value];
4624 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4625 MVT RegisterVT = RegVTs[Value];
4626
Dale Johannesen66978ee2009-01-31 02:22:37 +00004627 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004628 &Parts[Part], NumParts, RegisterVT);
4629 Part += NumParts;
4630 }
4631
4632 // Copy the parts into the registers.
4633 SmallVector<SDValue, 8> Chains(NumRegs);
4634 for (unsigned i = 0; i != NumRegs; ++i) {
4635 SDValue Part;
4636 if (Flag == 0)
Dale Johannesena04b7572009-02-03 23:04:43 +00004637 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004638 else {
Dale Johannesena04b7572009-02-03 23:04:43 +00004639 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004640 *Flag = Part.getValue(1);
4641 }
4642 Chains[i] = Part.getValue(0);
4643 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004644
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004645 if (NumRegs == 1 || Flag)
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004646 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004647 // flagged to it. That is the CopyToReg nodes and the user are considered
4648 // a single scheduling unit. If we create a TokenFactor and return it as
4649 // chain, then the TokenFactor is both a predecessor (operand) of the
4650 // user as well as a successor (the TF operands are flagged to the user).
4651 // c1, f1 = CopyToReg
4652 // c2, f2 = CopyToReg
4653 // c3 = TokenFactor c1, c2
4654 // ...
4655 // = op c3, ..., f2
4656 Chain = Chains[NumRegs-1];
4657 else
Dale Johannesen66978ee2009-01-31 02:22:37 +00004658 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004659}
4660
4661/// AddInlineAsmOperands - Add this value to the specified inlineasm node
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004662/// operand list. This adds the code marker and includes the number of
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004663/// values added into it.
Evan Cheng697cbbf2009-03-20 18:03:34 +00004664void RegsForValue::AddInlineAsmOperands(unsigned Code,
4665 bool HasMatching,unsigned MatchingIdx,
4666 SelectionDAG &DAG,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004667 std::vector<SDValue> &Ops) const {
4668 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
Evan Cheng697cbbf2009-03-20 18:03:34 +00004669 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
4670 unsigned Flag = Code | (Regs.size() << 3);
4671 if (HasMatching)
4672 Flag |= 0x80000000 | (MatchingIdx << 16);
4673 Ops.push_back(DAG.getTargetConstant(Flag, IntPtrTy));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004674 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4675 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4676 MVT RegisterVT = RegVTs[Value];
Chris Lattner58f15c42008-10-17 16:21:11 +00004677 for (unsigned i = 0; i != NumRegs; ++i) {
4678 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004679 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner58f15c42008-10-17 16:21:11 +00004680 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004681 }
4682}
4683
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004684/// isAllocatableRegister - If the specified register is safe to allocate,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004685/// i.e. it isn't a stack pointer or some other special register, return the
4686/// register class for the register. Otherwise, return null.
4687static const TargetRegisterClass *
4688isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4689 const TargetLowering &TLI,
4690 const TargetRegisterInfo *TRI) {
4691 MVT FoundVT = MVT::Other;
4692 const TargetRegisterClass *FoundRC = 0;
4693 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4694 E = TRI->regclass_end(); RCI != E; ++RCI) {
4695 MVT ThisVT = MVT::Other;
4696
4697 const TargetRegisterClass *RC = *RCI;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004698 // If none of the the value types for this register class are valid, we
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004699 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4700 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4701 I != E; ++I) {
4702 if (TLI.isTypeLegal(*I)) {
4703 // If we have already found this register in a different register class,
4704 // choose the one with the largest VT specified. For example, on
4705 // PowerPC, we favor f64 register classes over f32.
4706 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4707 ThisVT = *I;
4708 break;
4709 }
4710 }
4711 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004712
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004713 if (ThisVT == MVT::Other) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004714
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004715 // NOTE: This isn't ideal. In particular, this might allocate the
4716 // frame pointer in functions that need it (due to them not being taken
4717 // out of allocation, because a variable sized allocation hasn't been seen
4718 // yet). This is a slight code pessimization, but should still work.
4719 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4720 E = RC->allocation_order_end(MF); I != E; ++I)
4721 if (*I == Reg) {
4722 // We found a matching register class. Keep looking at others in case
4723 // we find one with larger registers that this physreg is also in.
4724 FoundRC = RC;
4725 FoundVT = ThisVT;
4726 break;
4727 }
4728 }
4729 return FoundRC;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004730}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004731
4732
4733namespace llvm {
4734/// AsmOperandInfo - This contains information for each constraint that we are
4735/// lowering.
Cedric Venetaff9c272009-02-14 16:06:42 +00004736class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
Daniel Dunbarc0c3b9a2008-09-10 04:16:29 +00004737 public TargetLowering::AsmOperandInfo {
Cedric Venetaff9c272009-02-14 16:06:42 +00004738public:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004739 /// CallOperand - If this is the result output operand or a clobber
4740 /// this is null, otherwise it is the incoming operand to the CallInst.
4741 /// This gets modified as the asm is processed.
4742 SDValue CallOperand;
4743
4744 /// AssignedRegs - If this is a register or register class operand, this
4745 /// contains the set of register corresponding to the operand.
4746 RegsForValue AssignedRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004747
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004748 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4749 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4750 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004751
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004752 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4753 /// busy in OutputRegs/InputRegs.
4754 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004755 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004756 std::set<unsigned> &InputRegs,
4757 const TargetRegisterInfo &TRI) const {
4758 if (isOutReg) {
4759 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4760 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4761 }
4762 if (isInReg) {
4763 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4764 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4765 }
4766 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004767
Chris Lattner81249c92008-10-17 17:05:25 +00004768 /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4769 /// corresponds to. If there is no Value* for this operand, it returns
4770 /// MVT::Other.
4771 MVT getCallOperandValMVT(const TargetLowering &TLI,
4772 const TargetData *TD) const {
4773 if (CallOperandVal == 0) return MVT::Other;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004774
Chris Lattner81249c92008-10-17 17:05:25 +00004775 if (isa<BasicBlock>(CallOperandVal))
4776 return TLI.getPointerTy();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004777
Chris Lattner81249c92008-10-17 17:05:25 +00004778 const llvm::Type *OpTy = CallOperandVal->getType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004779
Chris Lattner81249c92008-10-17 17:05:25 +00004780 // If this is an indirect operand, the operand is a pointer to the
4781 // accessed type.
4782 if (isIndirect)
4783 OpTy = cast<PointerType>(OpTy)->getElementType();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004784
Chris Lattner81249c92008-10-17 17:05:25 +00004785 // If OpTy is not a single value, it may be a struct/union that we
4786 // can tile with integers.
4787 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4788 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4789 switch (BitSize) {
4790 default: break;
4791 case 1:
4792 case 8:
4793 case 16:
4794 case 32:
4795 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00004796 case 128:
Chris Lattner81249c92008-10-17 17:05:25 +00004797 OpTy = IntegerType::get(BitSize);
4798 break;
4799 }
4800 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004801
Chris Lattner81249c92008-10-17 17:05:25 +00004802 return TLI.getValueType(OpTy, true);
4803 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004804
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004805private:
4806 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4807 /// specified set.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004808 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004809 const TargetRegisterInfo &TRI) {
4810 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4811 Regs.insert(Reg);
4812 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4813 for (; *Aliases; ++Aliases)
4814 Regs.insert(*Aliases);
4815 }
4816};
4817} // end llvm namespace.
4818
4819
4820/// GetRegistersForValue - Assign registers (virtual or physical) for the
4821/// specified operand. We prefer to assign virtual registers, to allow the
4822/// register allocator handle the assignment process. However, if the asm uses
4823/// features that we can't model on machineinstrs, we have SDISel do the
4824/// allocation. This produces generally horrible, but correct, code.
4825///
4826/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004827/// Input and OutputRegs are the set of already allocated physical registers.
4828///
4829void SelectionDAGLowering::
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004830GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004831 std::set<unsigned> &OutputRegs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004832 std::set<unsigned> &InputRegs) {
4833 // Compute whether this value requires an input register, an output register,
4834 // or both.
4835 bool isOutReg = false;
4836 bool isInReg = false;
4837 switch (OpInfo.Type) {
4838 case InlineAsm::isOutput:
4839 isOutReg = true;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004840
4841 // If there is an input constraint that matches this, we need to reserve
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004842 // the input register so no other inputs allocate to it.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004843 isInReg = OpInfo.hasMatchingInput();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004844 break;
4845 case InlineAsm::isInput:
4846 isInReg = true;
4847 isOutReg = false;
4848 break;
4849 case InlineAsm::isClobber:
4850 isOutReg = true;
4851 isInReg = true;
4852 break;
4853 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004854
4855
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004856 MachineFunction &MF = DAG.getMachineFunction();
4857 SmallVector<unsigned, 4> Regs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004858
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004859 // If this is a constraint for a single physreg, or a constraint for a
4860 // register class, find it.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004861 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004862 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4863 OpInfo.ConstraintVT);
4864
4865 unsigned NumRegs = 1;
Chris Lattner01426e12008-10-21 00:45:36 +00004866 if (OpInfo.ConstraintVT != MVT::Other) {
4867 // If this is a FP input in an integer register (or visa versa) insert a bit
4868 // cast of the input value. More generally, handle any case where the input
4869 // value disagrees with the register class we plan to stick this in.
4870 if (OpInfo.Type == InlineAsm::isInput &&
4871 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4872 // Try to convert to the first MVT that the reg class contains. If the
4873 // types are identical size, use a bitcast to convert (e.g. two differing
4874 // vector types).
4875 MVT RegVT = *PhysReg.second->vt_begin();
4876 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00004877 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004878 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00004879 OpInfo.ConstraintVT = RegVT;
4880 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4881 // If the input is a FP value and we want it in FP registers, do a
4882 // bitcast to the corresponding integer type. This turns an f64 value
4883 // into i64, which can be passed with two i32 values on a 32-bit
4884 // machine.
4885 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
Dale Johannesen66978ee2009-01-31 02:22:37 +00004886 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00004887 RegVT, OpInfo.CallOperand);
Chris Lattner01426e12008-10-21 00:45:36 +00004888 OpInfo.ConstraintVT = RegVT;
4889 }
4890 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004891
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004892 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00004893 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004894
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004895 MVT RegVT;
4896 MVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004897
4898 // If this is a constraint for a specific physical register, like {r17},
4899 // assign it now.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004900 if (unsigned AssignedReg = PhysReg.first) {
4901 const TargetRegisterClass *RC = PhysReg.second;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004902 if (OpInfo.ConstraintVT == MVT::Other)
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004903 ValueVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004904
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004905 // Get the actual register value type. This is important, because the user
4906 // may have asked for (e.g.) the AX register in i32 type. We need to
4907 // remember that AX is actually i16 to get the right extension.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004908 RegVT = *RC->vt_begin();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004909
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004910 // This is a explicit reference to a physical register.
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004911 Regs.push_back(AssignedReg);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004912
4913 // If this is an expanded reference, add the rest of the regs to Regs.
4914 if (NumRegs != 1) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004915 TargetRegisterClass::iterator I = RC->begin();
4916 for (; *I != AssignedReg; ++I)
4917 assert(I != RC->end() && "Didn't find reg!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004918
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004919 // Already added the first reg.
4920 --NumRegs; ++I;
4921 for (; NumRegs; --NumRegs, ++I) {
Chris Lattnere2f7bf82009-03-24 15:27:37 +00004922 assert(I != RC->end() && "Ran out of registers to allocate!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004923 Regs.push_back(*I);
4924 }
4925 }
4926 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4927 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4928 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4929 return;
4930 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004931
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004932 // Otherwise, if this was a reference to an LLVM register class, create vregs
4933 // for this reference.
Chris Lattnerb3b44842009-03-24 15:25:07 +00004934 if (const TargetRegisterClass *RC = PhysReg.second) {
4935 RegVT = *RC->vt_begin();
Evan Chengfb112882009-03-23 08:01:15 +00004936 if (OpInfo.ConstraintVT == MVT::Other)
4937 ValueVT = RegVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004938
Evan Chengfb112882009-03-23 08:01:15 +00004939 // Create the appropriate number of virtual registers.
4940 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4941 for (; NumRegs; --NumRegs)
Chris Lattnerb3b44842009-03-24 15:25:07 +00004942 Regs.push_back(RegInfo.createVirtualRegister(RC));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004943
Evan Chengfb112882009-03-23 08:01:15 +00004944 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4945 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004946 }
Chris Lattnerfc9d1612009-03-24 15:22:11 +00004947
4948 // This is a reference to a register class that doesn't directly correspond
4949 // to an LLVM register class. Allocate NumRegs consecutive, available,
4950 // registers from the class.
4951 std::vector<unsigned> RegClassRegs
4952 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4953 OpInfo.ConstraintVT);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004954
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004955 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4956 unsigned NumAllocated = 0;
4957 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4958 unsigned Reg = RegClassRegs[i];
4959 // See if this register is available.
4960 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4961 (isInReg && InputRegs.count(Reg))) { // Already used.
4962 // Make sure we find consecutive registers.
4963 NumAllocated = 0;
4964 continue;
4965 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004966
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004967 // Check to see if this register is allocatable (i.e. don't give out the
4968 // stack pointer).
Chris Lattnerfc9d1612009-03-24 15:22:11 +00004969 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4970 if (!RC) { // Couldn't allocate this register.
4971 // Reset NumAllocated to make sure we return consecutive registers.
4972 NumAllocated = 0;
4973 continue;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004974 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004975
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004976 // Okay, this register is good, we can use it.
4977 ++NumAllocated;
4978
4979 // If we allocated enough consecutive registers, succeed.
4980 if (NumAllocated == NumRegs) {
4981 unsigned RegStart = (i-NumAllocated)+1;
4982 unsigned RegEnd = i+1;
4983 // Mark all of the allocated registers used.
4984 for (unsigned i = RegStart; i != RegEnd; ++i)
4985 Regs.push_back(RegClassRegs[i]);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004986
4987 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004988 OpInfo.ConstraintVT);
4989 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4990 return;
4991 }
4992 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00004993
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004994 // Otherwise, we couldn't allocate enough registers for this.
4995}
4996
Evan Chengda43bcf2008-09-24 00:05:32 +00004997/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
4998/// processed uses a memory 'm' constraint.
4999static bool
5000hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
Dan Gohmane9530ec2009-01-15 16:58:17 +00005001 const TargetLowering &TLI) {
Evan Chengda43bcf2008-09-24 00:05:32 +00005002 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5003 InlineAsm::ConstraintInfo &CI = CInfos[i];
5004 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5005 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5006 if (CType == TargetLowering::C_Memory)
5007 return true;
5008 }
Chris Lattner6c147292009-04-30 00:48:50 +00005009
5010 // Indirect operand accesses access memory.
5011 if (CI.isIndirect)
5012 return true;
Evan Chengda43bcf2008-09-24 00:05:32 +00005013 }
5014
5015 return false;
5016}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005017
5018/// visitInlineAsm - Handle a call to an InlineAsm object.
5019///
5020void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
5021 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5022
5023 /// ConstraintOperands - Information about all of the constraints.
5024 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005025
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005026 std::set<unsigned> OutputRegs, InputRegs;
5027
5028 // Do a prepass over the constraints, canonicalizing them, and building up the
5029 // ConstraintOperands list.
5030 std::vector<InlineAsm::ConstraintInfo>
5031 ConstraintInfos = IA->ParseConstraints();
5032
Evan Chengda43bcf2008-09-24 00:05:32 +00005033 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Chris Lattner6c147292009-04-30 00:48:50 +00005034
5035 SDValue Chain, Flag;
5036
5037 // We won't need to flush pending loads if this asm doesn't touch
5038 // memory and is nonvolatile.
5039 if (hasMemory || IA->hasSideEffects())
Dale Johannesen97d14fc2009-04-18 00:09:40 +00005040 Chain = getRoot();
Chris Lattner6c147292009-04-30 00:48:50 +00005041 else
5042 Chain = DAG.getRoot();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005043
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005044 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5045 unsigned ResNo = 0; // ResNo - The result number of the next output.
5046 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5047 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5048 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005049
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005050 MVT OpVT = MVT::Other;
5051
5052 // Compute the value type for each operand.
5053 switch (OpInfo.Type) {
5054 case InlineAsm::isOutput:
5055 // Indirect outputs just consume an argument.
5056 if (OpInfo.isIndirect) {
5057 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5058 break;
5059 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005060
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005061 // The return value of the call is this value. As such, there is no
5062 // corresponding argument.
5063 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5064 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5065 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5066 } else {
5067 assert(ResNo == 0 && "Asm only has one result!");
5068 OpVT = TLI.getValueType(CS.getType());
5069 }
5070 ++ResNo;
5071 break;
5072 case InlineAsm::isInput:
5073 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5074 break;
5075 case InlineAsm::isClobber:
5076 // Nothing to do.
5077 break;
5078 }
5079
5080 // If this is an input or an indirect output, process the call argument.
5081 // BasicBlocks are labels, currently appearing only in asm's.
5082 if (OpInfo.CallOperandVal) {
Chris Lattner81249c92008-10-17 17:05:25 +00005083 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005084 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00005085 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005086 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005087 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005088
Chris Lattner81249c92008-10-17 17:05:25 +00005089 OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005090 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005091
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005092 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005093 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005094
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005095 // Second pass over the constraints: compute which constraint option to use
5096 // and assign registers to constraints that want a specific physreg.
5097 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5098 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005099
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005100 // If this is an output operand with a matching input operand, look up the
Evan Cheng09dc9c02008-12-16 18:21:39 +00005101 // matching input. If their types mismatch, e.g. one is an integer, the
5102 // other is floating point, or their sizes are different, flag it as an
5103 // error.
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005104 if (OpInfo.hasMatchingInput()) {
5105 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5106 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Evan Cheng09dc9c02008-12-16 18:21:39 +00005107 if ((OpInfo.ConstraintVT.isInteger() !=
5108 Input.ConstraintVT.isInteger()) ||
5109 (OpInfo.ConstraintVT.getSizeInBits() !=
5110 Input.ConstraintVT.getSizeInBits())) {
Daniel Dunbar4cbb1732009-04-13 22:26:09 +00005111 cerr << "llvm: error: Unsupported asm: input constraint with a "
5112 << "matching output constraint of incompatible type!\n";
Evan Cheng09dc9c02008-12-16 18:21:39 +00005113 exit(1);
5114 }
5115 Input.ConstraintVT = OpInfo.ConstraintVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005116 }
5117 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005118
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005119 // Compute the constraint code and ConstraintType to use.
Evan Chengda43bcf2008-09-24 00:05:32 +00005120 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005121
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005122 // If this is a memory input, and if the operand is not indirect, do what we
5123 // need to to provide an address for the memory input.
5124 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5125 !OpInfo.isIndirect) {
5126 assert(OpInfo.Type == InlineAsm::isInput &&
5127 "Can only indirectify direct input operands!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005128
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005129 // Memory operands really want the address of the value. If we don't have
5130 // an indirect input, put it in the constpool if we can, otherwise spill
5131 // it to a stack slot.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005132
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005133 // If the operand is a float, integer, or vector constant, spill to a
5134 // constant pool entry to get its address.
5135 Value *OpVal = OpInfo.CallOperandVal;
5136 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5137 isa<ConstantVector>(OpVal)) {
5138 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5139 TLI.getPointerTy());
5140 } else {
5141 // Otherwise, create a stack slot and emit a store to it before the
5142 // asm.
5143 const Type *Ty = OpVal->getType();
Duncan Sands777d2302009-05-09 07:06:46 +00005144 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005145 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5146 MachineFunction &MF = DAG.getMachineFunction();
5147 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
5148 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
Dale Johannesen66978ee2009-01-31 02:22:37 +00005149 Chain = DAG.getStore(Chain, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005150 OpInfo.CallOperand, StackSlot, NULL, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005151 OpInfo.CallOperand = StackSlot;
5152 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005153
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005154 // There is no longer a Value* corresponding to this operand.
5155 OpInfo.CallOperandVal = 0;
5156 // It is now an indirect operand.
5157 OpInfo.isIndirect = true;
5158 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005159
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005160 // If this constraint is for a specific register, allocate it before
5161 // anything else.
5162 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005163 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005164 }
5165 ConstraintInfos.clear();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005166
5167
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005168 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00005169 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005170 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5171 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005172
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005173 // C_Register operands have already been allocated, Other/Memory don't need
5174 // to be.
5175 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00005176 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005177 }
5178
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005179 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5180 std::vector<SDValue> AsmNodeOperands;
5181 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5182 AsmNodeOperands.push_back(
Bill Wendling056292f2008-09-16 21:48:12 +00005183 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005184
5185
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005186 // Loop over all of the inputs, copying the operand values into the
5187 // appropriate registers and processing the output regs.
5188 RegsForValue RetValRegs;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005189
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005190 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5191 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005192
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005193 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5194 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5195
5196 switch (OpInfo.Type) {
5197 case InlineAsm::isOutput: {
5198 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5199 OpInfo.ConstraintType != TargetLowering::C_Register) {
5200 // Memory output, or 'other' output (e.g. 'X' constraint).
5201 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5202
5203 // Add information to the INLINEASM node to know about this output.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005204 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5205 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005206 TLI.getPointerTy()));
5207 AsmNodeOperands.push_back(OpInfo.CallOperand);
5208 break;
5209 }
5210
5211 // Otherwise, this is a register or register class output.
5212
5213 // Copy the output from the appropriate register. Find a register that
5214 // we can use.
5215 if (OpInfo.AssignedRegs.Regs.empty()) {
Daniel Dunbar4cbb1732009-04-13 22:26:09 +00005216 cerr << "llvm: error: Couldn't allocate output reg for constraint '"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005217 << OpInfo.ConstraintCode << "'!\n";
5218 exit(1);
5219 }
5220
5221 // If this is an indirect operand, store through the pointer after the
5222 // asm.
5223 if (OpInfo.isIndirect) {
5224 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5225 OpInfo.CallOperandVal));
5226 } else {
5227 // This is the result value of the call.
5228 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5229 // Concatenate this output onto the outputs list.
5230 RetValRegs.append(OpInfo.AssignedRegs);
5231 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005232
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005233 // Add information to the INLINEASM node to know that this register is
5234 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00005235 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5236 6 /* EARLYCLOBBER REGDEF */ :
5237 2 /* REGDEF */ ,
Evan Chengfb112882009-03-23 08:01:15 +00005238 false,
5239 0,
Dale Johannesen913d3df2008-09-12 17:49:03 +00005240 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005241 break;
5242 }
5243 case InlineAsm::isInput: {
5244 SDValue InOperandVal = OpInfo.CallOperand;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005245
Chris Lattner6bdcda32008-10-17 16:47:46 +00005246 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005247 // If this is required to match an output register we have already set,
5248 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00005249 unsigned OperandNo = OpInfo.getMatchedOperand();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005250
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005251 // Scan until we find the definition we already emitted of this operand.
5252 // When we find it, create a RegsForValue operand.
5253 unsigned CurOp = 2; // The first operand.
5254 for (; OperandNo; --OperandNo) {
5255 // Advance to the next operand.
Evan Cheng697cbbf2009-03-20 18:03:34 +00005256 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005257 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005258 assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5259 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5260 (OpFlag & 7) == 4 /*MEM*/) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005261 "Skipped past definitions?");
Evan Cheng697cbbf2009-03-20 18:03:34 +00005262 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005263 }
5264
Evan Cheng697cbbf2009-03-20 18:03:34 +00005265 unsigned OpFlag =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005266 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005267 if ((OpFlag & 7) == 2 /*REGDEF*/
5268 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5269 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
Dan Gohman15480bd2009-06-15 22:32:41 +00005270 if (OpInfo.isIndirect) {
5271 cerr << "llvm: error: "
5272 "Don't know how to handle tied indirect "
5273 "register inputs yet!\n";
5274 exit(1);
5275 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005276 RegsForValue MatchedRegs;
5277 MatchedRegs.TLI = &TLI;
5278 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
Evan Chengfb112882009-03-23 08:01:15 +00005279 MVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5280 MatchedRegs.RegVTs.push_back(RegVT);
5281 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
Evan Cheng697cbbf2009-03-20 18:03:34 +00005282 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
Evan Chengfb112882009-03-23 08:01:15 +00005283 i != e; ++i)
5284 MatchedRegs.Regs.
5285 push_back(RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005286
5287 // Use the produced MatchedRegs object to
Dale Johannesen66978ee2009-01-31 02:22:37 +00005288 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5289 Chain, &Flag);
Evan Chengfb112882009-03-23 08:01:15 +00005290 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5291 true, OpInfo.getMatchedOperand(),
Evan Cheng697cbbf2009-03-20 18:03:34 +00005292 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005293 break;
5294 } else {
Evan Cheng697cbbf2009-03-20 18:03:34 +00005295 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5296 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5297 "Unexpected number of operands");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005298 // Add information to the INLINEASM node to know about this input.
Evan Chengfb112882009-03-23 08:01:15 +00005299 // See InlineAsm.h isUseOperandTiedToDef.
5300 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
Evan Cheng697cbbf2009-03-20 18:03:34 +00005301 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005302 TLI.getPointerTy()));
5303 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5304 break;
5305 }
5306 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005307
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005308 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005309 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005310 "Don't know how to handle indirect other inputs yet!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005311
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005312 std::vector<SDValue> Ops;
5313 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Chengda43bcf2008-09-24 00:05:32 +00005314 hasMemory, Ops, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005315 if (Ops.empty()) {
Daniel Dunbar4cbb1732009-04-13 22:26:09 +00005316 cerr << "llvm: error: Invalid operand for inline asm constraint '"
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005317 << OpInfo.ConstraintCode << "'!\n";
5318 exit(1);
5319 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005320
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005321 // Add information to the INLINEASM node to know about this input.
5322 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005323 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005324 TLI.getPointerTy()));
5325 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5326 break;
5327 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5328 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5329 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5330 "Memory operands expect pointer values");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005331
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005332 // Add information to the INLINEASM node to know about this input.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005333 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5334 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005335 TLI.getPointerTy()));
5336 AsmNodeOperands.push_back(InOperandVal);
5337 break;
5338 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005339
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005340 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5341 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5342 "Unknown constraint type!");
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005343 assert(!OpInfo.isIndirect &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005344 "Don't know how to handle indirect register inputs yet!");
5345
5346 // Copy the input into the appropriate registers.
Evan Chengaa765b82008-09-25 00:14:04 +00005347 if (OpInfo.AssignedRegs.Regs.empty()) {
Daniel Dunbar4cbb1732009-04-13 22:26:09 +00005348 cerr << "llvm: error: Couldn't allocate output reg for constraint '"
Evan Chengaa765b82008-09-25 00:14:04 +00005349 << OpInfo.ConstraintCode << "'!\n";
5350 exit(1);
5351 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005352
Dale Johannesen66978ee2009-01-31 02:22:37 +00005353 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5354 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005355
Evan Cheng697cbbf2009-03-20 18:03:34 +00005356 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
Dale Johannesen86b49f82008-09-24 01:07:17 +00005357 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005358 break;
5359 }
5360 case InlineAsm::isClobber: {
5361 // Add the clobbered value to the operand list, so that the register
5362 // allocator is aware that the physreg got clobbered.
5363 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesen91aac102008-09-17 21:13:11 +00005364 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
Evan Cheng697cbbf2009-03-20 18:03:34 +00005365 false, 0, DAG,AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005366 break;
5367 }
5368 }
5369 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005370
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005371 // Finish up input operands.
5372 AsmNodeOperands[0] = Chain;
5373 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005374
Dale Johannesen66978ee2009-01-31 02:22:37 +00005375 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
Dan Gohmanfc166572009-04-09 23:54:40 +00005376 DAG.getVTList(MVT::Other, MVT::Flag),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005377 &AsmNodeOperands[0], AsmNodeOperands.size());
5378 Flag = Chain.getValue(1);
5379
5380 // If this asm returns a register value, copy the result from that register
5381 // and set it as the value of the call.
5382 if (!RetValRegs.Regs.empty()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00005383 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
Dale Johannesen66978ee2009-01-31 02:22:37 +00005384 Chain, &Flag);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005385
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005386 // FIXME: Why don't we do this for inline asms with MRVs?
5387 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5388 MVT ResultType = TLI.getValueType(CS.getType());
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005389
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005390 // If any of the results of the inline asm is a vector, it may have the
5391 // wrong width/num elts. This can happen for register classes that can
5392 // contain multiple different value types. The preg or vreg allocated may
5393 // not have the same VT as was expected. Convert it to the right type
5394 // with bit_convert.
5395 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005396 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005397 ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005398
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005399 } else if (ResultType != Val.getValueType() &&
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005400 ResultType.isInteger() && Val.getValueType().isInteger()) {
5401 // If a result value was tied to an input value, the computed result may
5402 // have a wider width than the expected result. Extract the relevant
5403 // portion.
Dale Johannesen66978ee2009-01-31 02:22:37 +00005404 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005405 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005406
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005407 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00005408 }
Dan Gohman95915732008-10-18 01:03:45 +00005409
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005410 setValue(CS.getInstruction(), Val);
Dale Johannesenec65a7d2009-04-14 00:56:56 +00005411 // Don't need to use this as a chain in this case.
5412 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5413 return;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005414 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005415
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005416 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005417
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005418 // Process indirect outputs, first output all of the flagged copies out of
5419 // physregs.
5420 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5421 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5422 Value *Ptr = IndirectStoresToEmit[i].second;
Dale Johannesen66978ee2009-01-31 02:22:37 +00005423 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5424 Chain, &Flag);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005425 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
Chris Lattner6c147292009-04-30 00:48:50 +00005426
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005427 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005428
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005429 // Emit the non-flagged stores from the physregs.
5430 SmallVector<SDValue, 8> OutChains;
5431 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
Dale Johannesen66978ee2009-01-31 02:22:37 +00005432 OutChains.push_back(DAG.getStore(Chain, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005433 StoresToEmit[i].first,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005434 getValue(StoresToEmit[i].second),
5435 StoresToEmit[i].second, 0));
5436 if (!OutChains.empty())
Dale Johannesen66978ee2009-01-31 02:22:37 +00005437 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005438 &OutChains[0], OutChains.size());
5439 DAG.setRoot(Chain);
5440}
5441
5442
5443void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5444 SDValue Src = getValue(I.getOperand(0));
5445
Chris Lattner0b18e592009-03-17 19:36:00 +00005446 // Scale up by the type size in the original i32 type width. Various
5447 // mid-level optimizers may make assumptions about demanded bits etc from the
5448 // i32-ness of the optimizer: we do not want to promote to i64 and then
5449 // multiply on 64-bit targets.
5450 // FIXME: Malloc inst should go away: PR715.
Duncan Sands777d2302009-05-09 07:06:46 +00005451 uint64_t ElementSize = TD->getTypeAllocSize(I.getType()->getElementType());
Chris Lattner0b18e592009-03-17 19:36:00 +00005452 if (ElementSize != 1)
5453 Src = DAG.getNode(ISD::MUL, getCurDebugLoc(), Src.getValueType(),
5454 Src, DAG.getConstant(ElementSize, Src.getValueType()));
5455
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005456 MVT IntPtr = TLI.getPointerTy();
5457
5458 if (IntPtr.bitsLT(Src.getValueType()))
Dale Johannesen66978ee2009-01-31 02:22:37 +00005459 Src = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), IntPtr, Src);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005460 else if (IntPtr.bitsGT(Src.getValueType()))
Dale Johannesen66978ee2009-01-31 02:22:37 +00005461 Src = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), IntPtr, Src);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005462
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005463 TargetLowering::ArgListTy Args;
5464 TargetLowering::ArgListEntry Entry;
5465 Entry.Node = Src;
5466 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5467 Args.push_back(Entry);
5468
5469 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005470 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
Tilmann Scheller6b61cd12009-07-03 06:44:53 +00005471 0, CallingConv::C, PerformTailCallOpt,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005472 DAG.getExternalSymbol("malloc", IntPtr),
Dale Johannesen66978ee2009-01-31 02:22:37 +00005473 Args, DAG, getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005474 setValue(&I, Result.first); // Pointers always fit in registers
5475 DAG.setRoot(Result.second);
5476}
5477
5478void SelectionDAGLowering::visitFree(FreeInst &I) {
5479 TargetLowering::ArgListTy Args;
5480 TargetLowering::ArgListEntry Entry;
5481 Entry.Node = getValue(I.getOperand(0));
5482 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5483 Args.push_back(Entry);
5484 MVT IntPtr = TLI.getPointerTy();
5485 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005486 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
Tilmann Scheller6b61cd12009-07-03 06:44:53 +00005487 0, CallingConv::C, PerformTailCallOpt,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005488 DAG.getExternalSymbol("free", IntPtr), Args, DAG,
Dale Johannesen66978ee2009-01-31 02:22:37 +00005489 getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005490 DAG.setRoot(Result.second);
5491}
5492
5493void SelectionDAGLowering::visitVAStart(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005494 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005495 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005496 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005497 DAG.getSrcValue(I.getOperand(1))));
5498}
5499
5500void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
Dale Johannesena04b7572009-02-03 23:04:43 +00005501 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5502 getRoot(), getValue(I.getOperand(0)),
5503 DAG.getSrcValue(I.getOperand(0)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005504 setValue(&I, V);
5505 DAG.setRoot(V.getValue(1));
5506}
5507
5508void SelectionDAGLowering::visitVAEnd(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005509 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005510 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005511 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005512 DAG.getSrcValue(I.getOperand(1))));
5513}
5514
5515void SelectionDAGLowering::visitVACopy(CallInst &I) {
Dale Johannesen66978ee2009-01-31 02:22:37 +00005516 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005517 MVT::Other, getRoot(),
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005518 getValue(I.getOperand(1)),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005519 getValue(I.getOperand(2)),
5520 DAG.getSrcValue(I.getOperand(1)),
5521 DAG.getSrcValue(I.getOperand(2))));
5522}
5523
5524/// TargetLowering::LowerArguments - This is the default LowerArguments
5525/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005526/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005527/// integrated into SDISel.
5528void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005529 SmallVectorImpl<SDValue> &ArgValues,
5530 DebugLoc dl) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005531 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5532 SmallVector<SDValue, 3+16> Ops;
5533 Ops.push_back(DAG.getRoot());
5534 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5535 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5536
5537 // Add one result value for each formal argument.
5538 SmallVector<MVT, 16> RetVals;
5539 unsigned j = 1;
5540 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5541 I != E; ++I, ++j) {
5542 SmallVector<MVT, 4> ValueVTs;
5543 ComputeValueVTs(*this, I->getType(), ValueVTs);
5544 for (unsigned Value = 0, NumValues = ValueVTs.size();
5545 Value != NumValues; ++Value) {
5546 MVT VT = ValueVTs[Value];
5547 const Type *ArgTy = VT.getTypeForMVT();
5548 ISD::ArgFlagsTy Flags;
5549 unsigned OriginalAlignment =
5550 getTargetData()->getABITypeAlignment(ArgTy);
5551
Devang Patel05988662008-09-25 21:00:45 +00005552 if (F.paramHasAttr(j, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005553 Flags.setZExt();
Devang Patel05988662008-09-25 21:00:45 +00005554 if (F.paramHasAttr(j, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005555 Flags.setSExt();
Devang Patel05988662008-09-25 21:00:45 +00005556 if (F.paramHasAttr(j, Attribute::InReg))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005557 Flags.setInReg();
Devang Patel05988662008-09-25 21:00:45 +00005558 if (F.paramHasAttr(j, Attribute::StructRet))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005559 Flags.setSRet();
Devang Patel05988662008-09-25 21:00:45 +00005560 if (F.paramHasAttr(j, Attribute::ByVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005561 Flags.setByVal();
5562 const PointerType *Ty = cast<PointerType>(I->getType());
5563 const Type *ElementTy = Ty->getElementType();
5564 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sands777d2302009-05-09 07:06:46 +00005565 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005566 // For ByVal, alignment should be passed from FE. BE will guess if
5567 // this info is not there but there are cases it cannot get right.
5568 if (F.getParamAlignment(j))
5569 FrameAlign = F.getParamAlignment(j);
5570 Flags.setByValAlign(FrameAlign);
5571 Flags.setByValSize(FrameSize);
5572 }
Devang Patel05988662008-09-25 21:00:45 +00005573 if (F.paramHasAttr(j, Attribute::Nest))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005574 Flags.setNest();
5575 Flags.setOrigAlign(OriginalAlignment);
5576
5577 MVT RegisterVT = getRegisterType(VT);
5578 unsigned NumRegs = getNumRegisters(VT);
5579 for (unsigned i = 0; i != NumRegs; ++i) {
5580 RetVals.push_back(RegisterVT);
5581 ISD::ArgFlagsTy MyFlags = Flags;
5582 if (NumRegs > 1 && i == 0)
5583 MyFlags.setSplit();
5584 // if it isn't first piece, alignment must be 1
5585 else if (i > 0)
5586 MyFlags.setOrigAlign(1);
5587 Ops.push_back(DAG.getArgFlags(MyFlags));
5588 }
5589 }
5590 }
5591
5592 RetVals.push_back(MVT::Other);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005593
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005594 // Create the node.
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005595 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, dl,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005596 DAG.getVTList(&RetVals[0], RetVals.size()),
5597 &Ops[0], Ops.size()).getNode();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005598
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005599 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5600 // allows exposing the loads that may be part of the argument access to the
5601 // first DAGCombiner pass.
5602 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005603
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005604 // The number of results should match up, except that the lowered one may have
5605 // an extra flag result.
5606 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5607 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5608 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5609 && "Lowering produced unexpected number of results!");
5610
5611 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5612 if (Result != TmpRes.getNode() && Result->use_empty()) {
5613 HandleSDNode Dummy(DAG.getRoot());
5614 DAG.RemoveDeadNode(Result);
5615 }
5616
5617 Result = TmpRes.getNode();
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005618
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005619 unsigned NumArgRegs = Result->getNumValues() - 1;
5620 DAG.setRoot(SDValue(Result, NumArgRegs));
5621
5622 // Set up the return result vector.
5623 unsigned i = 0;
5624 unsigned Idx = 1;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005625 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005626 ++I, ++Idx) {
5627 SmallVector<MVT, 4> ValueVTs;
5628 ComputeValueVTs(*this, I->getType(), ValueVTs);
5629 for (unsigned Value = 0, NumValues = ValueVTs.size();
5630 Value != NumValues; ++Value) {
5631 MVT VT = ValueVTs[Value];
5632 MVT PartVT = getRegisterType(VT);
5633
5634 unsigned NumParts = getNumRegisters(VT);
5635 SmallVector<SDValue, 4> Parts(NumParts);
5636 for (unsigned j = 0; j != NumParts; ++j)
5637 Parts[j] = SDValue(Result, i++);
5638
5639 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Devang Patel05988662008-09-25 21:00:45 +00005640 if (F.paramHasAttr(Idx, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005641 AssertOp = ISD::AssertSext;
Devang Patel05988662008-09-25 21:00:45 +00005642 else if (F.paramHasAttr(Idx, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005643 AssertOp = ISD::AssertZext;
5644
Dale Johannesen66978ee2009-01-31 02:22:37 +00005645 ArgValues.push_back(getCopyFromParts(DAG, dl, &Parts[0], NumParts,
5646 PartVT, VT, AssertOp));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005647 }
5648 }
5649 assert(i == NumArgRegs && "Argument register count mismatch!");
5650}
5651
5652
5653/// TargetLowering::LowerCallTo - This is the default LowerCallTo
5654/// implementation, which just inserts an ISD::CALL node, which is later custom
5655/// lowered by the target to something concrete. FIXME: When all targets are
5656/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5657std::pair<SDValue, SDValue>
5658TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5659 bool RetSExt, bool RetZExt, bool isVarArg,
Tilmann Scheller6b61cd12009-07-03 06:44:53 +00005660 bool isInreg, unsigned NumFixedArgs,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005661 unsigned CallingConv, bool isTailCall,
5662 SDValue Callee,
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005663 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
Dan Gohman1937e2f2008-09-16 01:42:28 +00005664 assert((!isTailCall || PerformTailCallOpt) &&
5665 "isTailCall set when tail-call optimizations are disabled!");
5666
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005667 SmallVector<SDValue, 32> Ops;
5668 Ops.push_back(Chain); // Op#0 - Chain
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005669 Ops.push_back(Callee);
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005670
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005671 // Handle all of the outgoing arguments.
5672 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5673 SmallVector<MVT, 4> ValueVTs;
5674 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5675 for (unsigned Value = 0, NumValues = ValueVTs.size();
5676 Value != NumValues; ++Value) {
5677 MVT VT = ValueVTs[Value];
5678 const Type *ArgTy = VT.getTypeForMVT();
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005679 SDValue Op = SDValue(Args[i].Node.getNode(),
5680 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005681 ISD::ArgFlagsTy Flags;
5682 unsigned OriginalAlignment =
5683 getTargetData()->getABITypeAlignment(ArgTy);
5684
5685 if (Args[i].isZExt)
5686 Flags.setZExt();
5687 if (Args[i].isSExt)
5688 Flags.setSExt();
5689 if (Args[i].isInReg)
5690 Flags.setInReg();
5691 if (Args[i].isSRet)
5692 Flags.setSRet();
5693 if (Args[i].isByVal) {
5694 Flags.setByVal();
5695 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5696 const Type *ElementTy = Ty->getElementType();
5697 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
Duncan Sands777d2302009-05-09 07:06:46 +00005698 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005699 // For ByVal, alignment should come from FE. BE will guess if this
5700 // info is not there but there are cases it cannot get right.
5701 if (Args[i].Alignment)
5702 FrameAlign = Args[i].Alignment;
5703 Flags.setByValAlign(FrameAlign);
5704 Flags.setByValSize(FrameSize);
5705 }
5706 if (Args[i].isNest)
5707 Flags.setNest();
5708 Flags.setOrigAlign(OriginalAlignment);
5709
5710 MVT PartVT = getRegisterType(VT);
5711 unsigned NumParts = getNumRegisters(VT);
5712 SmallVector<SDValue, 4> Parts(NumParts);
5713 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5714
5715 if (Args[i].isSExt)
5716 ExtendKind = ISD::SIGN_EXTEND;
5717 else if (Args[i].isZExt)
5718 ExtendKind = ISD::ZERO_EXTEND;
5719
Dale Johannesen66978ee2009-01-31 02:22:37 +00005720 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, PartVT, ExtendKind);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005721
5722 for (unsigned i = 0; i != NumParts; ++i) {
5723 // if it isn't first piece, alignment must be 1
5724 ISD::ArgFlagsTy MyFlags = Flags;
5725 if (NumParts > 1 && i == 0)
5726 MyFlags.setSplit();
5727 else if (i != 0)
5728 MyFlags.setOrigAlign(1);
5729
5730 Ops.push_back(Parts[i]);
5731 Ops.push_back(DAG.getArgFlags(MyFlags));
5732 }
5733 }
5734 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005735
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005736 // Figure out the result value types. We start by making a list of
5737 // the potentially illegal return value types.
5738 SmallVector<MVT, 4> LoweredRetTys;
5739 SmallVector<MVT, 4> RetTys;
5740 ComputeValueVTs(*this, RetTy, RetTys);
5741
5742 // Then we translate that to a list of legal types.
5743 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5744 MVT VT = RetTys[I];
5745 MVT RegisterVT = getRegisterType(VT);
5746 unsigned NumRegs = getNumRegisters(VT);
5747 for (unsigned i = 0; i != NumRegs; ++i)
5748 LoweredRetTys.push_back(RegisterVT);
5749 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005750
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005751 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005752
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005753 // Create the CALL node.
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005754 SDValue Res = DAG.getCall(CallingConv, dl,
Dale Johannesenfa42dea2009-01-30 01:34:22 +00005755 isVarArg, isTailCall, isInreg,
Dan Gohman095cc292008-09-13 01:54:27 +00005756 DAG.getVTList(&LoweredRetTys[0],
5757 LoweredRetTys.size()),
Tilmann Scheller6b61cd12009-07-03 06:44:53 +00005758 &Ops[0], Ops.size(), NumFixedArgs
Dale Johannesen86098bd2008-09-26 19:31:26 +00005759 );
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005760 Chain = Res.getValue(LoweredRetTys.size() - 1);
5761
5762 // Gather up the call result into a single value.
Dan Gohmanb5cc34d2008-10-07 00:12:37 +00005763 if (RetTy != Type::VoidTy && !RetTys.empty()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005764 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5765
5766 if (RetSExt)
5767 AssertOp = ISD::AssertSext;
5768 else if (RetZExt)
5769 AssertOp = ISD::AssertZext;
5770
5771 SmallVector<SDValue, 4> ReturnValues;
5772 unsigned RegNo = 0;
5773 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5774 MVT VT = RetTys[I];
5775 MVT RegisterVT = getRegisterType(VT);
5776 unsigned NumRegs = getNumRegisters(VT);
5777 unsigned RegNoEnd = NumRegs + RegNo;
5778 SmallVector<SDValue, 4> Results;
5779 for (; RegNo != RegNoEnd; ++RegNo)
5780 Results.push_back(Res.getValue(RegNo));
5781 SDValue ReturnValue =
Dale Johannesen66978ee2009-01-31 02:22:37 +00005782 getCopyFromParts(DAG, dl, &Results[0], NumRegs, RegisterVT, VT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005783 AssertOp);
5784 ReturnValues.push_back(ReturnValue);
5785 }
Dale Johannesen7d2ad622009-01-30 23:10:59 +00005786 Res = DAG.getNode(ISD::MERGE_VALUES, dl,
Duncan Sandsaaffa052008-12-01 11:41:29 +00005787 DAG.getVTList(&RetTys[0], RetTys.size()),
5788 &ReturnValues[0], ReturnValues.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005789 }
5790
5791 return std::make_pair(Res, Chain);
5792}
5793
Duncan Sands9fbc7e22009-01-21 09:00:29 +00005794void TargetLowering::LowerOperationWrapper(SDNode *N,
5795 SmallVectorImpl<SDValue> &Results,
5796 SelectionDAG &DAG) {
5797 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
Sanjiv Guptabb326bb2009-01-21 04:48:39 +00005798 if (Res.getNode())
5799 Results.push_back(Res);
5800}
5801
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005802SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5803 assert(0 && "LowerOperation not implemented for this target!");
5804 abort();
5805 return SDValue();
5806}
5807
5808
5809void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5810 SDValue Op = getValue(V);
5811 assert((Op.getOpcode() != ISD::CopyFromReg ||
5812 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5813 "Copy from a reg to the same reg!");
5814 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5815
5816 RegsForValue RFV(TLI, Reg, V->getType());
5817 SDValue Chain = DAG.getEntryNode();
Dale Johannesen66978ee2009-01-31 02:22:37 +00005818 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005819 PendingExports.push_back(Chain);
5820}
5821
5822#include "llvm/CodeGen/SelectionDAGISel.h"
5823
5824void SelectionDAGISel::
5825LowerArguments(BasicBlock *LLVMBB) {
5826 // If this is the entry block, emit arguments.
5827 Function &F = *LLVMBB->getParent();
5828 SDValue OldRoot = SDL->DAG.getRoot();
5829 SmallVector<SDValue, 16> Args;
Dale Johannesen66978ee2009-01-31 02:22:37 +00005830 TLI.LowerArguments(F, SDL->DAG, Args, SDL->getCurDebugLoc());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005831
5832 unsigned a = 0;
5833 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5834 AI != E; ++AI) {
5835 SmallVector<MVT, 4> ValueVTs;
5836 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5837 unsigned NumValues = ValueVTs.size();
5838 if (!AI->use_empty()) {
Scott Michelfdc40a02009-02-17 22:15:04 +00005839 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues,
Dale Johannesen4be0bdf2009-02-05 00:20:09 +00005840 SDL->getCurDebugLoc()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005841 // If this argument is live outside of the entry block, insert a copy from
5842 // whereever we got it to the vreg that other BB's will reference it as.
Dan Gohmanad62f532009-04-23 23:13:24 +00005843 SDL->CopyToExportRegsIfNeeded(AI);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005844 }
5845 a += NumValues;
5846 }
5847
5848 // Finally, if the target has anything special to do, allow it to do so.
5849 // FIXME: this should insert code into the DAG!
5850 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5851}
5852
5853/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5854/// ensure constants are generated when needed. Remember the virtual registers
5855/// that need to be added to the Machine PHI nodes as input. We cannot just
5856/// directly add them, because expansion might result in multiple MBB's for one
5857/// BB. As such, the start of the BB might correspond to a different MBB than
5858/// the end.
5859///
5860void
5861SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5862 TerminatorInst *TI = LLVMBB->getTerminator();
5863
5864 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5865
5866 // Check successor nodes' PHI nodes that expect a constant to be available
5867 // from this block.
5868 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5869 BasicBlock *SuccBB = TI->getSuccessor(succ);
5870 if (!isa<PHINode>(SuccBB->begin())) continue;
5871 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005872
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005873 // If this terminator has multiple identical successors (common for
5874 // switches), only handle each succ once.
5875 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005876
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005877 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5878 PHINode *PN;
5879
5880 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5881 // nodes and Machine PHI nodes, but the incoming operands have not been
5882 // emitted yet.
5883 for (BasicBlock::iterator I = SuccBB->begin();
5884 (PN = dyn_cast<PHINode>(I)); ++I) {
5885 // Ignore dead phi's.
5886 if (PN->use_empty()) continue;
5887
5888 unsigned Reg;
5889 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5890
5891 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5892 unsigned &RegOut = SDL->ConstantsOut[C];
5893 if (RegOut == 0) {
5894 RegOut = FuncInfo->CreateRegForValue(C);
5895 SDL->CopyValueToVirtualRegister(C, RegOut);
5896 }
5897 Reg = RegOut;
5898 } else {
5899 Reg = FuncInfo->ValueMap[PHIOp];
5900 if (Reg == 0) {
5901 assert(isa<AllocaInst>(PHIOp) &&
5902 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5903 "Didn't codegen value into a register!??");
5904 Reg = FuncInfo->CreateRegForValue(PHIOp);
5905 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5906 }
5907 }
5908
5909 // Remember that this register needs to added to the machine PHI node as
5910 // the input for this MBB.
5911 SmallVector<MVT, 4> ValueVTs;
5912 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5913 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5914 MVT VT = ValueVTs[vti];
5915 unsigned NumRegisters = TLI.getNumRegisters(VT);
5916 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5917 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5918 Reg += NumRegisters;
5919 }
5920 }
5921 }
5922 SDL->ConstantsOut.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005923}
5924
Dan Gohman3df24e62008-09-03 23:12:08 +00005925/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5926/// supports legal types, and it emits MachineInstrs directly instead of
5927/// creating SelectionDAG nodes.
5928///
5929bool
5930SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5931 FastISel *F) {
5932 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005933
Dan Gohman3df24e62008-09-03 23:12:08 +00005934 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5935 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5936
5937 // Check successor nodes' PHI nodes that expect a constant to be available
5938 // from this block.
5939 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5940 BasicBlock *SuccBB = TI->getSuccessor(succ);
5941 if (!isa<PHINode>(SuccBB->begin())) continue;
5942 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005943
Dan Gohman3df24e62008-09-03 23:12:08 +00005944 // If this terminator has multiple identical successors (common for
5945 // switches), only handle each succ once.
5946 if (!SuccsHandled.insert(SuccMBB)) continue;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +00005947
Dan Gohman3df24e62008-09-03 23:12:08 +00005948 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5949 PHINode *PN;
5950
5951 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5952 // nodes and Machine PHI nodes, but the incoming operands have not been
5953 // emitted yet.
5954 for (BasicBlock::iterator I = SuccBB->begin();
5955 (PN = dyn_cast<PHINode>(I)); ++I) {
5956 // Ignore dead phi's.
5957 if (PN->use_empty()) continue;
5958
5959 // Only handle legal types. Two interesting things to note here. First,
5960 // by bailing out early, we may leave behind some dead instructions,
5961 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5962 // own moves. Second, this check is necessary becuase FastISel doesn't
5963 // use CreateRegForValue to create registers, so it always creates
5964 // exactly one register for each non-void instruction.
5965 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5966 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
Dan Gohman74321ab2008-09-10 21:01:31 +00005967 // Promote MVT::i1.
5968 if (VT == MVT::i1)
5969 VT = TLI.getTypeToTransformTo(VT);
5970 else {
5971 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5972 return false;
5973 }
Dan Gohman3df24e62008-09-03 23:12:08 +00005974 }
5975
5976 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5977
5978 unsigned Reg = F->getRegForValue(PHIOp);
5979 if (Reg == 0) {
5980 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5981 return false;
5982 }
5983 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
5984 }
5985 }
5986
5987 return true;
5988}