blob: 920cca4ea4dfa59c81f2118f7b865f79a98eb883 [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"
40#include "llvm/Target/TargetRegisterInfo.h"
41#include "llvm/Target/TargetData.h"
42#include "llvm/Target/TargetFrameInfo.h"
43#include "llvm/Target/TargetInstrInfo.h"
44#include "llvm/Target/TargetLowering.h"
45#include "llvm/Target/TargetMachine.h"
46#include "llvm/Target/TargetOptions.h"
47#include "llvm/Support/Compiler.h"
48#include "llvm/Support/Debug.h"
49#include "llvm/Support/MathExtras.h"
50#include <algorithm>
51using namespace llvm;
52
Dale Johannesen601d3c02008-09-05 01:48:15 +000053/// LimitFloatPrecision - Generate low-precision inline sequences for
54/// some float libcalls (6, 8 or 12 bits).
55static unsigned LimitFloatPrecision;
56
57static cl::opt<unsigned, true>
58LimitFPPrecision("limit-float-precision",
59 cl::desc("Generate low-precision inline sequences "
60 "for some float libcalls"),
61 cl::location(LimitFloatPrecision),
62 cl::init(0));
63
Dan Gohmanf0cbcd42008-09-03 16:12:24 +000064/// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
65/// insertvalue or extractvalue indices that identify a member, return
66/// the linearized index of the start of the member.
67///
68static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
69 const unsigned *Indices,
70 const unsigned *IndicesEnd,
71 unsigned CurIndex = 0) {
72 // Base case: We're done.
73 if (Indices && Indices == IndicesEnd)
74 return CurIndex;
75
76 // Given a struct type, recursively traverse the elements.
77 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
78 for (StructType::element_iterator EB = STy->element_begin(),
79 EI = EB,
80 EE = STy->element_end();
81 EI != EE; ++EI) {
82 if (Indices && *Indices == unsigned(EI - EB))
83 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
84 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
85 }
86 }
87 // Given an array type, recursively traverse the elements.
88 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
89 const Type *EltTy = ATy->getElementType();
90 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
91 if (Indices && *Indices == i)
92 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
93 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
94 }
95 }
96 // We haven't found the type we're looking for, so keep searching.
97 return CurIndex + 1;
98}
99
100/// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
101/// MVTs that represent all the individual underlying
102/// non-aggregate types that comprise it.
103///
104/// If Offsets is non-null, it points to a vector to be filled in
105/// with the in-memory offsets of each of the individual values.
106///
107static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
108 SmallVectorImpl<MVT> &ValueVTs,
109 SmallVectorImpl<uint64_t> *Offsets = 0,
110 uint64_t StartingOffset = 0) {
111 // Given a struct type, recursively traverse the elements.
112 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
113 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
114 for (StructType::element_iterator EB = STy->element_begin(),
115 EI = EB,
116 EE = STy->element_end();
117 EI != EE; ++EI)
118 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
119 StartingOffset + SL->getElementOffset(EI - EB));
120 return;
121 }
122 // Given an array type, recursively traverse the elements.
123 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
124 const Type *EltTy = ATy->getElementType();
125 uint64_t EltSize = TLI.getTargetData()->getABITypeSize(EltTy);
126 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
127 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
128 StartingOffset + i * EltSize);
129 return;
130 }
131 // Base case: we can get an MVT for this LLVM IR type.
132 ValueVTs.push_back(TLI.getValueType(Ty));
133 if (Offsets)
134 Offsets->push_back(StartingOffset);
135}
136
Dan Gohman2a7c6712008-09-03 23:18:39 +0000137namespace llvm {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000138 /// RegsForValue - This struct represents the registers (physical or virtual)
139 /// that a particular set of values is assigned, and the type information about
140 /// the value. The most common situation is to represent one value at a time,
141 /// but struct or array values are handled element-wise as multiple values.
142 /// The splitting of aggregates is performed recursively, so that we never
143 /// have aggregate-typed registers. The values at this point do not necessarily
144 /// have legal types, so each value may require one or more registers of some
145 /// legal type.
146 ///
147 struct VISIBILITY_HIDDEN RegsForValue {
148 /// TLI - The TargetLowering object.
149 ///
150 const TargetLowering *TLI;
151
152 /// ValueVTs - The value types of the values, which may not be legal, and
153 /// may need be promoted or synthesized from one or more registers.
154 ///
155 SmallVector<MVT, 4> ValueVTs;
156
157 /// RegVTs - The value types of the registers. This is the same size as
158 /// ValueVTs and it records, for each value, what the type of the assigned
159 /// register or registers are. (Individual values are never synthesized
160 /// from more than one type of register.)
161 ///
162 /// With virtual registers, the contents of RegVTs is redundant with TLI's
163 /// getRegisterType member function, however when with physical registers
164 /// it is necessary to have a separate record of the types.
165 ///
166 SmallVector<MVT, 4> RegVTs;
167
168 /// Regs - This list holds the registers assigned to the values.
169 /// Each legal or promoted value requires one register, and each
170 /// expanded value requires multiple registers.
171 ///
172 SmallVector<unsigned, 4> Regs;
173
174 RegsForValue() : TLI(0) {}
175
176 RegsForValue(const TargetLowering &tli,
177 const SmallVector<unsigned, 4> &regs,
178 MVT regvt, MVT valuevt)
179 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
180 RegsForValue(const TargetLowering &tli,
181 const SmallVector<unsigned, 4> &regs,
182 const SmallVector<MVT, 4> &regvts,
183 const SmallVector<MVT, 4> &valuevts)
184 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
185 RegsForValue(const TargetLowering &tli,
186 unsigned Reg, const Type *Ty) : TLI(&tli) {
187 ComputeValueVTs(tli, Ty, ValueVTs);
188
189 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
190 MVT ValueVT = ValueVTs[Value];
191 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
192 MVT RegisterVT = TLI->getRegisterType(ValueVT);
193 for (unsigned i = 0; i != NumRegs; ++i)
194 Regs.push_back(Reg + i);
195 RegVTs.push_back(RegisterVT);
196 Reg += NumRegs;
197 }
198 }
199
200 /// append - Add the specified values to this one.
201 void append(const RegsForValue &RHS) {
202 TLI = RHS.TLI;
203 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
204 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
205 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
206 }
207
208
209 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
210 /// this value and returns the result as a ValueVTs value. This uses
211 /// Chain/Flag as the input and updates them for the output Chain/Flag.
212 /// If the Flag pointer is NULL, no flag is used.
213 SDValue getCopyFromRegs(SelectionDAG &DAG,
214 SDValue &Chain, SDValue *Flag) const;
215
216 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
217 /// specified value into the registers specified by this object. This uses
218 /// Chain/Flag as the input and updates them for the output Chain/Flag.
219 /// If the Flag pointer is NULL, no flag is used.
220 void getCopyToRegs(SDValue Val, SelectionDAG &DAG,
221 SDValue &Chain, SDValue *Flag) const;
222
223 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
224 /// operand list. This adds the code marker and includes the number of
225 /// values added into it.
226 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
227 std::vector<SDValue> &Ops) const;
228 };
229}
230
231/// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
232/// PHI nodes or outside of the basic block that defines it, or used by a
233/// switch or atomic instruction, which may expand to multiple basic blocks.
234static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
235 if (isa<PHINode>(I)) return true;
236 BasicBlock *BB = I->getParent();
237 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
238 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
239 // FIXME: Remove switchinst special case.
240 isa<SwitchInst>(*UI))
241 return true;
242 return false;
243}
244
245/// isOnlyUsedInEntryBlock - If the specified argument is only used in the
246/// entry block, return true. This includes arguments used by switches, since
247/// the switch may expand into multiple basic blocks.
248static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
249 // With FastISel active, we may be splitting blocks, so force creation
250 // of virtual registers for all non-dead arguments.
Dan Gohman33134c42008-09-25 17:05:24 +0000251 // Don't force virtual registers for byval arguments though, because
252 // fast-isel can't handle those in all cases.
253 if (EnableFastISel && !A->hasByValAttr())
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000254 return A->use_empty();
255
256 BasicBlock *Entry = A->getParent()->begin();
257 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
258 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
259 return false; // Use not in entry block.
260 return true;
261}
262
263FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
264 : TLI(tli) {
265}
266
267void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
268 bool EnableFastISel) {
269 Fn = &fn;
270 MF = &mf;
271 RegInfo = &MF->getRegInfo();
272
273 // Create a vreg for each argument register that is not dead and is used
274 // outside of the entry block for the function.
275 for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
276 AI != E; ++AI)
277 if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
278 InitializeRegForValue(AI);
279
280 // Initialize the mapping of values to registers. This is only set up for
281 // instruction values that are used outside of the block that defines
282 // them.
283 Function::iterator BB = Fn->begin(), EB = Fn->end();
284 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
285 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
286 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
287 const Type *Ty = AI->getAllocatedType();
288 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
289 unsigned Align =
290 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
291 AI->getAlignment());
292
293 TySize *= CUI->getZExtValue(); // Get total allocated size.
294 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
295 StaticAllocaMap[AI] =
296 MF->getFrameInfo()->CreateStackObject(TySize, Align);
297 }
298
299 for (; BB != EB; ++BB)
300 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
301 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
302 if (!isa<AllocaInst>(I) ||
303 !StaticAllocaMap.count(cast<AllocaInst>(I)))
304 InitializeRegForValue(I);
305
306 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
307 // also creates the initial PHI MachineInstrs, though none of the input
308 // operands are populated.
309 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
310 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
311 MBBMap[BB] = MBB;
312 MF->push_back(MBB);
313
314 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
315 // appropriate.
316 PHINode *PN;
317 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
318 if (PN->use_empty()) continue;
319
320 unsigned PHIReg = ValueMap[PN];
321 assert(PHIReg && "PHI node does not have an assigned virtual register!");
322
323 SmallVector<MVT, 4> ValueVTs;
324 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
325 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
326 MVT VT = ValueVTs[vti];
327 unsigned NumRegisters = TLI.getNumRegisters(VT);
Dan Gohman6448d912008-09-04 15:39:15 +0000328 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000329 for (unsigned i = 0; i != NumRegisters; ++i)
330 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
331 PHIReg += NumRegisters;
332 }
333 }
334 }
335}
336
337unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
338 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
339}
340
341/// CreateRegForValue - Allocate the appropriate number of virtual registers of
342/// the correctly promoted or expanded types. Assign these registers
343/// consecutive vreg numbers and return the first assigned number.
344///
345/// In the case that the given value has struct or array type, this function
346/// will assign registers for each member or element.
347///
348unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
349 SmallVector<MVT, 4> ValueVTs;
350 ComputeValueVTs(TLI, V->getType(), ValueVTs);
351
352 unsigned FirstReg = 0;
353 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
354 MVT ValueVT = ValueVTs[Value];
355 MVT RegisterVT = TLI.getRegisterType(ValueVT);
356
357 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
358 for (unsigned i = 0; i != NumRegs; ++i) {
359 unsigned R = MakeReg(RegisterVT);
360 if (!FirstReg) FirstReg = R;
361 }
362 }
363 return FirstReg;
364}
365
366/// getCopyFromParts - Create a value that contains the specified legal parts
367/// combined into the value they represent. If the parts combine to a type
368/// larger then ValueVT then AssertOp can be used to specify whether the extra
369/// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
370/// (ISD::AssertSext).
371static SDValue getCopyFromParts(SelectionDAG &DAG,
372 const SDValue *Parts,
373 unsigned NumParts,
374 MVT PartVT,
375 MVT ValueVT,
376 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
377 assert(NumParts > 0 && "No parts to assemble!");
378 TargetLowering &TLI = DAG.getTargetLoweringInfo();
379 SDValue Val = Parts[0];
380
381 if (NumParts > 1) {
382 // Assemble the value from multiple parts.
383 if (!ValueVT.isVector()) {
384 unsigned PartBits = PartVT.getSizeInBits();
385 unsigned ValueBits = ValueVT.getSizeInBits();
386
387 // Assemble the power of 2 part.
388 unsigned RoundParts = NumParts & (NumParts - 1) ?
389 1 << Log2_32(NumParts) : NumParts;
390 unsigned RoundBits = PartBits * RoundParts;
391 MVT RoundVT = RoundBits == ValueBits ?
392 ValueVT : MVT::getIntegerVT(RoundBits);
393 SDValue Lo, Hi;
394
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000395 MVT HalfVT = ValueVT.isInteger() ?
396 MVT::getIntegerVT(RoundBits/2) :
397 MVT::getFloatingPointVT(RoundBits/2);
398
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000399 if (RoundParts > 2) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000400 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
401 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
402 PartVT, HalfVT);
403 } else {
Duncan Sandsd22ec5f2008-10-29 14:22:20 +0000404 Lo = DAG.getNode(ISD::BIT_CONVERT, HalfVT, Parts[0]);
405 Hi = DAG.getNode(ISD::BIT_CONVERT, HalfVT, Parts[1]);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000406 }
407 if (TLI.isBigEndian())
408 std::swap(Lo, Hi);
409 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
410
411 if (RoundParts < NumParts) {
412 // Assemble the trailing non-power-of-2 part.
413 unsigned OddParts = NumParts - RoundParts;
414 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
415 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
416
417 // Combine the round and odd parts.
418 Lo = Val;
419 if (TLI.isBigEndian())
420 std::swap(Lo, Hi);
421 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
422 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
423 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
424 DAG.getConstant(Lo.getValueType().getSizeInBits(),
425 TLI.getShiftAmountTy()));
426 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
427 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
428 }
429 } else {
430 // Handle a multi-element vector.
431 MVT IntermediateVT, RegisterVT;
432 unsigned NumIntermediates;
433 unsigned NumRegs =
434 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
435 RegisterVT);
436 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
437 NumParts = NumRegs; // Silence a compiler warning.
438 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
439 assert(RegisterVT == Parts[0].getValueType() &&
440 "Part type doesn't match part!");
441
442 // Assemble the parts into intermediate operands.
443 SmallVector<SDValue, 8> Ops(NumIntermediates);
444 if (NumIntermediates == NumParts) {
445 // If the register was not expanded, truncate or copy the value,
446 // as appropriate.
447 for (unsigned i = 0; i != NumParts; ++i)
448 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
449 PartVT, IntermediateVT);
450 } else if (NumParts > 0) {
451 // If the intermediate type was expanded, build the intermediate operands
452 // from the parts.
453 assert(NumParts % NumIntermediates == 0 &&
454 "Must expand into a divisible number of parts!");
455 unsigned Factor = NumParts / NumIntermediates;
456 for (unsigned i = 0; i != NumIntermediates; ++i)
457 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
458 PartVT, IntermediateVT);
459 }
460
461 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
462 // operands.
463 Val = DAG.getNode(IntermediateVT.isVector() ?
464 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
465 ValueVT, &Ops[0], NumIntermediates);
466 }
467 }
468
469 // There is now one part, held in Val. Correct it to match ValueVT.
470 PartVT = Val.getValueType();
471
472 if (PartVT == ValueVT)
473 return Val;
474
475 if (PartVT.isVector()) {
476 assert(ValueVT.isVector() && "Unknown vector conversion!");
477 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
478 }
479
480 if (ValueVT.isVector()) {
481 assert(ValueVT.getVectorElementType() == PartVT &&
482 ValueVT.getVectorNumElements() == 1 &&
483 "Only trivial scalar-to-vector conversions should get here!");
484 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
485 }
486
487 if (PartVT.isInteger() &&
488 ValueVT.isInteger()) {
489 if (ValueVT.bitsLT(PartVT)) {
490 // For a truncate, see if we have any information to
491 // indicate whether the truncated bits will always be
492 // zero or sign-extension.
493 if (AssertOp != ISD::DELETED_NODE)
494 Val = DAG.getNode(AssertOp, PartVT, Val,
495 DAG.getValueType(ValueVT));
496 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
497 } else {
498 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
499 }
500 }
501
502 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
503 if (ValueVT.bitsLT(Val.getValueType()))
504 // FP_ROUND's are always exact here.
505 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
506 DAG.getIntPtrConstant(1));
507 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
508 }
509
510 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
511 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
512
513 assert(0 && "Unknown mismatch!");
514 return SDValue();
515}
516
517/// getCopyToParts - Create a series of nodes that contain the specified value
518/// split into legal parts. If the parts contain more bits than Val, then, for
519/// integers, ExtendKind can be used to specify how to generate the extra bits.
Chris Lattner01426e12008-10-21 00:45:36 +0000520static void getCopyToParts(SelectionDAG &DAG, SDValue Val,
521 SDValue *Parts, unsigned NumParts, MVT PartVT,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000522 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
523 TargetLowering &TLI = DAG.getTargetLoweringInfo();
524 MVT PtrVT = TLI.getPointerTy();
525 MVT ValueVT = Val.getValueType();
526 unsigned PartBits = PartVT.getSizeInBits();
527 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
528
529 if (!NumParts)
530 return;
531
532 if (!ValueVT.isVector()) {
533 if (PartVT == ValueVT) {
534 assert(NumParts == 1 && "No-op copy with multiple parts!");
535 Parts[0] = Val;
536 return;
537 }
538
539 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
540 // If the parts cover more bits than the value has, promote the value.
541 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
542 assert(NumParts == 1 && "Do not know what to promote to!");
543 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
544 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
545 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
546 Val = DAG.getNode(ExtendKind, ValueVT, Val);
547 } else {
548 assert(0 && "Unknown mismatch!");
549 }
550 } else if (PartBits == ValueVT.getSizeInBits()) {
551 // Different types of the same size.
552 assert(NumParts == 1 && PartVT != ValueVT);
553 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
554 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
555 // If the parts cover less bits than value has, truncate the value.
556 if (PartVT.isInteger() && ValueVT.isInteger()) {
557 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
558 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
559 } else {
560 assert(0 && "Unknown mismatch!");
561 }
562 }
563
564 // The value may have changed - recompute ValueVT.
565 ValueVT = Val.getValueType();
566 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
567 "Failed to tile the value with PartVT!");
568
569 if (NumParts == 1) {
570 assert(PartVT == ValueVT && "Type conversion failed!");
571 Parts[0] = Val;
572 return;
573 }
574
575 // Expand the value into multiple parts.
576 if (NumParts & (NumParts - 1)) {
577 // The number of parts is not a power of 2. Split off and copy the tail.
578 assert(PartVT.isInteger() && ValueVT.isInteger() &&
579 "Do not know what to expand to!");
580 unsigned RoundParts = 1 << Log2_32(NumParts);
581 unsigned RoundBits = RoundParts * PartBits;
582 unsigned OddParts = NumParts - RoundParts;
583 SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
584 DAG.getConstant(RoundBits,
585 TLI.getShiftAmountTy()));
586 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
587 if (TLI.isBigEndian())
588 // The odd parts were reversed by getCopyToParts - unreverse them.
589 std::reverse(Parts + RoundParts, Parts + NumParts);
590 NumParts = RoundParts;
591 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
592 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
593 }
594
595 // The number of parts is a power of 2. Repeatedly bisect the value using
596 // EXTRACT_ELEMENT.
597 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
598 MVT::getIntegerVT(ValueVT.getSizeInBits()),
599 Val);
600 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
601 for (unsigned i = 0; i < NumParts; i += StepSize) {
602 unsigned ThisBits = StepSize * PartBits / 2;
603 MVT ThisVT = MVT::getIntegerVT (ThisBits);
604 SDValue &Part0 = Parts[i];
605 SDValue &Part1 = Parts[i+StepSize/2];
606
607 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
608 DAG.getConstant(1, PtrVT));
609 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
610 DAG.getConstant(0, PtrVT));
611
612 if (ThisBits == PartBits && ThisVT != PartVT) {
613 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
614 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
615 }
616 }
617 }
618
619 if (TLI.isBigEndian())
620 std::reverse(Parts, Parts + NumParts);
621
622 return;
623 }
624
625 // Vector ValueVT.
626 if (NumParts == 1) {
627 if (PartVT != ValueVT) {
628 if (PartVT.isVector()) {
629 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
630 } else {
631 assert(ValueVT.getVectorElementType() == PartVT &&
632 ValueVT.getVectorNumElements() == 1 &&
633 "Only trivial vector-to-scalar conversions should get here!");
634 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
635 DAG.getConstant(0, PtrVT));
636 }
637 }
638
639 Parts[0] = Val;
640 return;
641 }
642
643 // Handle a multi-element vector.
644 MVT IntermediateVT, RegisterVT;
645 unsigned NumIntermediates;
646 unsigned NumRegs =
647 DAG.getTargetLoweringInfo()
648 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
649 RegisterVT);
650 unsigned NumElements = ValueVT.getVectorNumElements();
651
652 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
653 NumParts = NumRegs; // Silence a compiler warning.
654 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
655
656 // Split the vector into intermediate operands.
657 SmallVector<SDValue, 8> Ops(NumIntermediates);
658 for (unsigned i = 0; i != NumIntermediates; ++i)
659 if (IntermediateVT.isVector())
660 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
661 IntermediateVT, Val,
662 DAG.getConstant(i * (NumElements / NumIntermediates),
663 PtrVT));
664 else
665 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
666 IntermediateVT, Val,
667 DAG.getConstant(i, PtrVT));
668
669 // Split the intermediate operands into legal parts.
670 if (NumParts == NumIntermediates) {
671 // If the register was not expanded, promote or copy the value,
672 // as appropriate.
673 for (unsigned i = 0; i != NumParts; ++i)
674 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
675 } else if (NumParts > 0) {
676 // If the intermediate type was expanded, split each the value into
677 // legal parts.
678 assert(NumParts % NumIntermediates == 0 &&
679 "Must expand into a divisible number of parts!");
680 unsigned Factor = NumParts / NumIntermediates;
681 for (unsigned i = 0; i != NumIntermediates; ++i)
682 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
683 }
684}
685
686
687void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
688 AA = &aa;
689 GFI = gfi;
690 TD = DAG.getTarget().getTargetData();
691}
692
693/// clear - Clear out the curret SelectionDAG and the associated
694/// state and prepare this SelectionDAGLowering object to be used
695/// for a new block. This doesn't clear out information about
696/// additional blocks that are needed to complete switch lowering
697/// or PHI node updating; that information is cleared out as it is
698/// consumed.
699void SelectionDAGLowering::clear() {
700 NodeMap.clear();
701 PendingLoads.clear();
702 PendingExports.clear();
703 DAG.clear();
704}
705
706/// getRoot - Return the current virtual root of the Selection DAG,
707/// flushing any PendingLoad items. This must be done before emitting
708/// a store or any other node that may need to be ordered after any
709/// prior load instructions.
710///
711SDValue SelectionDAGLowering::getRoot() {
712 if (PendingLoads.empty())
713 return DAG.getRoot();
714
715 if (PendingLoads.size() == 1) {
716 SDValue Root = PendingLoads[0];
717 DAG.setRoot(Root);
718 PendingLoads.clear();
719 return Root;
720 }
721
722 // Otherwise, we have to make a token factor node.
723 SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
724 &PendingLoads[0], PendingLoads.size());
725 PendingLoads.clear();
726 DAG.setRoot(Root);
727 return Root;
728}
729
730/// getControlRoot - Similar to getRoot, but instead of flushing all the
731/// PendingLoad items, flush all the PendingExports items. It is necessary
732/// to do this before emitting a terminator instruction.
733///
734SDValue SelectionDAGLowering::getControlRoot() {
735 SDValue Root = DAG.getRoot();
736
737 if (PendingExports.empty())
738 return Root;
739
740 // Turn all of the CopyToReg chains into one factored node.
741 if (Root.getOpcode() != ISD::EntryToken) {
742 unsigned i = 0, e = PendingExports.size();
743 for (; i != e; ++i) {
744 assert(PendingExports[i].getNode()->getNumOperands() > 1);
745 if (PendingExports[i].getNode()->getOperand(0) == Root)
746 break; // Don't add the root if we already indirectly depend on it.
747 }
748
749 if (i == e)
750 PendingExports.push_back(Root);
751 }
752
753 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
754 &PendingExports[0],
755 PendingExports.size());
756 PendingExports.clear();
757 DAG.setRoot(Root);
758 return Root;
759}
760
761void SelectionDAGLowering::visit(Instruction &I) {
762 visit(I.getOpcode(), I);
763}
764
765void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
766 // Note: this doesn't use InstVisitor, because it has to work with
767 // ConstantExpr's in addition to instructions.
768 switch (Opcode) {
769 default: assert(0 && "Unknown instruction type encountered!");
770 abort();
771 // Build the switch statement using the Instruction.def file.
772#define HANDLE_INST(NUM, OPCODE, CLASS) \
773 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
774#include "llvm/Instruction.def"
775 }
776}
777
778void SelectionDAGLowering::visitAdd(User &I) {
779 if (I.getType()->isFPOrFPVector())
780 visitBinary(I, ISD::FADD);
781 else
782 visitBinary(I, ISD::ADD);
783}
784
785void SelectionDAGLowering::visitMul(User &I) {
786 if (I.getType()->isFPOrFPVector())
787 visitBinary(I, ISD::FMUL);
788 else
789 visitBinary(I, ISD::MUL);
790}
791
792SDValue SelectionDAGLowering::getValue(const Value *V) {
793 SDValue &N = NodeMap[V];
794 if (N.getNode()) return N;
795
796 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
797 MVT VT = TLI.getValueType(V->getType(), true);
798
799 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000800 return N = DAG.getConstant(*CI, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000801
802 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
803 return N = DAG.getGlobalAddress(GV, VT);
804
805 if (isa<ConstantPointerNull>(C))
806 return N = DAG.getConstant(0, TLI.getPointerTy());
807
808 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
Dan Gohman4fbd7962008-09-12 18:08:03 +0000809 return N = DAG.getConstantFP(*CFP, VT);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000810
811 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
812 !V->getType()->isAggregateType())
813 return N = DAG.getNode(ISD::UNDEF, VT);
814
815 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
816 visit(CE->getOpcode(), *CE);
817 SDValue N1 = NodeMap[V];
818 assert(N1.getNode() && "visit didn't populate the ValueMap!");
819 return N1;
820 }
821
822 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
823 SmallVector<SDValue, 4> Constants;
824 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
825 OI != OE; ++OI) {
826 SDNode *Val = getValue(*OI).getNode();
827 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
828 Constants.push_back(SDValue(Val, i));
829 }
830 return DAG.getMergeValues(&Constants[0], Constants.size());
831 }
832
833 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
834 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
835 "Unknown struct or array constant!");
836
837 SmallVector<MVT, 4> ValueVTs;
838 ComputeValueVTs(TLI, C->getType(), ValueVTs);
839 unsigned NumElts = ValueVTs.size();
840 if (NumElts == 0)
841 return SDValue(); // empty struct
842 SmallVector<SDValue, 4> Constants(NumElts);
843 for (unsigned i = 0; i != NumElts; ++i) {
844 MVT EltVT = ValueVTs[i];
845 if (isa<UndefValue>(C))
846 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
847 else if (EltVT.isFloatingPoint())
848 Constants[i] = DAG.getConstantFP(0, EltVT);
849 else
850 Constants[i] = DAG.getConstant(0, EltVT);
851 }
852 return DAG.getMergeValues(&Constants[0], NumElts);
853 }
854
855 const VectorType *VecTy = cast<VectorType>(V->getType());
856 unsigned NumElements = VecTy->getNumElements();
857
858 // Now that we know the number and type of the elements, get that number of
859 // elements into the Ops array based on what kind of constant it is.
860 SmallVector<SDValue, 16> Ops;
861 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
862 for (unsigned i = 0; i != NumElements; ++i)
863 Ops.push_back(getValue(CP->getOperand(i)));
864 } else {
865 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
866 "Unknown vector constant!");
867 MVT EltVT = TLI.getValueType(VecTy->getElementType());
868
869 SDValue Op;
870 if (isa<UndefValue>(C))
871 Op = DAG.getNode(ISD::UNDEF, EltVT);
872 else if (EltVT.isFloatingPoint())
873 Op = DAG.getConstantFP(0, EltVT);
874 else
875 Op = DAG.getConstant(0, EltVT);
876 Ops.assign(NumElements, Op);
877 }
878
879 // Create a BUILD_VECTOR node.
880 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
881 }
882
883 // If this is a static alloca, generate it as the frameindex instead of
884 // computation.
885 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
886 DenseMap<const AllocaInst*, int>::iterator SI =
887 FuncInfo.StaticAllocaMap.find(AI);
888 if (SI != FuncInfo.StaticAllocaMap.end())
889 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
890 }
891
892 unsigned InReg = FuncInfo.ValueMap[V];
893 assert(InReg && "Value not in map!");
894
895 RegsForValue RFV(TLI, InReg, V->getType());
896 SDValue Chain = DAG.getEntryNode();
897 return RFV.getCopyFromRegs(DAG, Chain, NULL);
898}
899
900
901void SelectionDAGLowering::visitRet(ReturnInst &I) {
902 if (I.getNumOperands() == 0) {
903 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
904 return;
905 }
906
907 SmallVector<SDValue, 8> NewValues;
908 NewValues.push_back(getControlRoot());
909 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000910 SmallVector<MVT, 4> ValueVTs;
911 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
Dan Gohman7ea1ca62008-10-21 20:00:42 +0000912 unsigned NumValues = ValueVTs.size();
913 if (NumValues == 0) continue;
914
915 SDValue RetOp = getValue(I.getOperand(i));
916 for (unsigned j = 0, f = NumValues; j != f; ++j) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000917 MVT VT = ValueVTs[j];
918
919 // FIXME: C calling convention requires the return type to be promoted to
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000920 // at least 32-bit. But this is not necessary for non-C calling
921 // conventions.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000922 if (VT.isInteger()) {
923 MVT MinVT = TLI.getRegisterType(MVT::i32);
924 if (VT.bitsLT(MinVT))
925 VT = MinVT;
926 }
927
928 unsigned NumParts = TLI.getNumRegisters(VT);
929 MVT PartVT = TLI.getRegisterType(VT);
930 SmallVector<SDValue, 4> Parts(NumParts);
931 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
932
933 const Function *F = I.getParent()->getParent();
Devang Patel05988662008-09-25 21:00:45 +0000934 if (F->paramHasAttr(0, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000935 ExtendKind = ISD::SIGN_EXTEND;
Devang Patel05988662008-09-25 21:00:45 +0000936 else if (F->paramHasAttr(0, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000937 ExtendKind = ISD::ZERO_EXTEND;
938
939 getCopyToParts(DAG, SDValue(RetOp.getNode(), RetOp.getResNo() + j),
940 &Parts[0], NumParts, PartVT, ExtendKind);
941
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000942 // 'inreg' on function refers to return value
943 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
Devang Patel05988662008-09-25 21:00:45 +0000944 if (F->paramHasAttr(0, Attribute::InReg))
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000945 Flags.setInReg();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000946 for (unsigned i = 0; i < NumParts; ++i) {
947 NewValues.push_back(Parts[i]);
Dale Johannesenc9c6da62008-09-25 20:47:45 +0000948 NewValues.push_back(DAG.getArgFlags(Flags));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +0000949 }
950 }
951 }
952 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
953 &NewValues[0], NewValues.size()));
954}
955
956/// ExportFromCurrentBlock - If this condition isn't known to be exported from
957/// the current basic block, add it to ValueMap now so that we'll get a
958/// CopyTo/FromReg.
959void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
960 // No need to export constants.
961 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
962
963 // Already exported?
964 if (FuncInfo.isExportedInst(V)) return;
965
966 unsigned Reg = FuncInfo.InitializeRegForValue(V);
967 CopyValueToVirtualRegister(V, Reg);
968}
969
970bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
971 const BasicBlock *FromBB) {
972 // The operands of the setcc have to be in this block. We don't know
973 // how to export them from some other block.
974 if (Instruction *VI = dyn_cast<Instruction>(V)) {
975 // Can export from current BB.
976 if (VI->getParent() == FromBB)
977 return true;
978
979 // Is already exported, noop.
980 return FuncInfo.isExportedInst(V);
981 }
982
983 // If this is an argument, we can export it if the BB is the entry block or
984 // if it is already exported.
985 if (isa<Argument>(V)) {
986 if (FromBB == &FromBB->getParent()->getEntryBlock())
987 return true;
988
989 // Otherwise, can only export this if it is already exported.
990 return FuncInfo.isExportedInst(V);
991 }
992
993 // Otherwise, constants can always be exported.
994 return true;
995}
996
997static bool InBlock(const Value *V, const BasicBlock *BB) {
998 if (const Instruction *I = dyn_cast<Instruction>(V))
999 return I->getParent() == BB;
1000 return true;
1001}
1002
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001003/// getFCmpCondCode - Return the ISD condition code corresponding to
1004/// the given LLVM IR floating-point condition code. This includes
1005/// consideration of global floating-point math flags.
1006///
1007static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1008 ISD::CondCode FPC, FOC;
1009 switch (Pred) {
1010 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1011 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1012 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1013 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1014 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1015 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1016 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1017 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1018 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1019 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1020 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1021 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1022 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1023 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1024 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1025 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1026 default:
1027 assert(0 && "Invalid FCmp predicate opcode!");
1028 FOC = FPC = ISD::SETFALSE;
1029 break;
1030 }
1031 if (FiniteOnlyFPMath())
1032 return FOC;
1033 else
1034 return FPC;
1035}
1036
1037/// getICmpCondCode - Return the ISD condition code corresponding to
1038/// the given LLVM IR integer condition code.
1039///
1040static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1041 switch (Pred) {
1042 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1043 case ICmpInst::ICMP_NE: return ISD::SETNE;
1044 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1045 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1046 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1047 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1048 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1049 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1050 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1051 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1052 default:
1053 assert(0 && "Invalid ICmp predicate opcode!");
1054 return ISD::SETNE;
1055 }
1056}
1057
Dan Gohmanc2277342008-10-17 21:16:08 +00001058/// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1059/// This function emits a branch and is used at the leaves of an OR or an
1060/// AND operator tree.
1061///
1062void
1063SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1064 MachineBasicBlock *TBB,
1065 MachineBasicBlock *FBB,
1066 MachineBasicBlock *CurBB) {
1067 const BasicBlock *BB = CurBB->getBasicBlock();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001068
Dan Gohmanc2277342008-10-17 21:16:08 +00001069 // If the leaf of the tree is a comparison, merge the condition into
1070 // the caseblock.
1071 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1072 // The operands of the cmp have to be in this block. We don't know
1073 // how to export them from some other block. If this is the first block
1074 // of the sequence, no exporting is needed.
1075 if (CurBB == CurMBB ||
1076 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1077 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001078 ISD::CondCode Condition;
1079 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001080 Condition = getICmpCondCode(IC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001081 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00001082 Condition = getFCmpCondCode(FC->getPredicate());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001083 } else {
1084 Condition = ISD::SETEQ; // silence warning.
1085 assert(0 && "Unknown compare instruction");
1086 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001087
1088 CaseBlock CB(Condition, BOp->getOperand(0),
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001089 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1090 SwitchCases.push_back(CB);
1091 return;
1092 }
Dan Gohmanc2277342008-10-17 21:16:08 +00001093 }
1094
1095 // Create a CaseBlock record representing this branch.
1096 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1097 NULL, TBB, FBB, CurBB);
1098 SwitchCases.push_back(CB);
1099}
1100
1101/// FindMergedConditions - If Cond is an expression like
1102void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1103 MachineBasicBlock *TBB,
1104 MachineBasicBlock *FBB,
1105 MachineBasicBlock *CurBB,
1106 unsigned Opc) {
1107 // If this node is not part of the or/and tree, emit it as a branch.
1108 Instruction *BOp = dyn_cast<Instruction>(Cond);
1109 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1110 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1111 BOp->getParent() != CurBB->getBasicBlock() ||
1112 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1113 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1114 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001115 return;
1116 }
1117
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00001118 // Create TmpBB after CurBB.
1119 MachineFunction::iterator BBI = CurBB;
1120 MachineFunction &MF = DAG.getMachineFunction();
1121 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1122 CurBB->getParent()->insert(++BBI, TmpBB);
1123
1124 if (Opc == Instruction::Or) {
1125 // Codegen X | Y as:
1126 // jmp_if_X TBB
1127 // jmp TmpBB
1128 // TmpBB:
1129 // jmp_if_Y TBB
1130 // jmp FBB
1131 //
1132
1133 // Emit the LHS condition.
1134 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1135
1136 // Emit the RHS condition into TmpBB.
1137 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1138 } else {
1139 assert(Opc == Instruction::And && "Unknown merge op!");
1140 // Codegen X & Y as:
1141 // jmp_if_X TmpBB
1142 // jmp FBB
1143 // TmpBB:
1144 // jmp_if_Y TBB
1145 // jmp FBB
1146 //
1147 // This requires creation of TmpBB after CurBB.
1148
1149 // Emit the LHS condition.
1150 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1151
1152 // Emit the RHS condition into TmpBB.
1153 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1154 }
1155}
1156
1157/// If the set of cases should be emitted as a series of branches, return true.
1158/// If we should emit this as a bunch of and/or'd together conditions, return
1159/// false.
1160bool
1161SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1162 if (Cases.size() != 2) return true;
1163
1164 // If this is two comparisons of the same values or'd or and'd together, they
1165 // will get folded into a single comparison, so don't emit two blocks.
1166 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1167 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1168 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1169 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1170 return false;
1171 }
1172
1173 return true;
1174}
1175
1176void SelectionDAGLowering::visitBr(BranchInst &I) {
1177 // Update machine-CFG edges.
1178 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1179
1180 // Figure out which block is immediately after the current one.
1181 MachineBasicBlock *NextBlock = 0;
1182 MachineFunction::iterator BBI = CurMBB;
1183 if (++BBI != CurMBB->getParent()->end())
1184 NextBlock = BBI;
1185
1186 if (I.isUnconditional()) {
1187 // Update machine-CFG edges.
1188 CurMBB->addSuccessor(Succ0MBB);
1189
1190 // If this is not a fall-through branch, emit the branch.
1191 if (Succ0MBB != NextBlock)
1192 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1193 DAG.getBasicBlock(Succ0MBB)));
1194 return;
1195 }
1196
1197 // If this condition is one of the special cases we handle, do special stuff
1198 // now.
1199 Value *CondVal = I.getCondition();
1200 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1201
1202 // If this is a series of conditions that are or'd or and'd together, emit
1203 // this as a sequence of branches instead of setcc's with and/or operations.
1204 // For example, instead of something like:
1205 // cmp A, B
1206 // C = seteq
1207 // cmp D, E
1208 // F = setle
1209 // or C, F
1210 // jnz foo
1211 // Emit:
1212 // cmp A, B
1213 // je foo
1214 // cmp D, E
1215 // jle foo
1216 //
1217 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1218 if (BOp->hasOneUse() &&
1219 (BOp->getOpcode() == Instruction::And ||
1220 BOp->getOpcode() == Instruction::Or)) {
1221 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1222 // If the compares in later blocks need to use values not currently
1223 // exported from this block, export them now. This block should always
1224 // be the first entry.
1225 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1226
1227 // Allow some cases to be rejected.
1228 if (ShouldEmitAsBranches(SwitchCases)) {
1229 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1230 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1231 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1232 }
1233
1234 // Emit the branch for this block.
1235 visitSwitchCase(SwitchCases[0]);
1236 SwitchCases.erase(SwitchCases.begin());
1237 return;
1238 }
1239
1240 // Okay, we decided not to do this, remove any inserted MBB's and clear
1241 // SwitchCases.
1242 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1243 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
1244
1245 SwitchCases.clear();
1246 }
1247 }
1248
1249 // Create a CaseBlock record representing this branch.
1250 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1251 NULL, Succ0MBB, Succ1MBB, CurMBB);
1252 // Use visitSwitchCase to actually insert the fast branch sequence for this
1253 // cond branch.
1254 visitSwitchCase(CB);
1255}
1256
1257/// visitSwitchCase - Emits the necessary code to represent a single node in
1258/// the binary search tree resulting from lowering a switch instruction.
1259void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1260 SDValue Cond;
1261 SDValue CondLHS = getValue(CB.CmpLHS);
1262
1263 // Build the setcc now.
1264 if (CB.CmpMHS == NULL) {
1265 // Fold "(X == true)" to X and "(X == false)" to !X to
1266 // handle common cases produced by branch lowering.
1267 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1268 Cond = CondLHS;
1269 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1270 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1271 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1272 } else
1273 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1274 } else {
1275 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1276
1277 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1278 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1279
1280 SDValue CmpOp = getValue(CB.CmpMHS);
1281 MVT VT = CmpOp.getValueType();
1282
1283 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1284 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1285 } else {
1286 SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1287 Cond = DAG.getSetCC(MVT::i1, SUB,
1288 DAG.getConstant(High-Low, VT), ISD::SETULE);
1289 }
1290 }
1291
1292 // Update successor info
1293 CurMBB->addSuccessor(CB.TrueBB);
1294 CurMBB->addSuccessor(CB.FalseBB);
1295
1296 // Set NextBlock to be the MBB immediately after the current one, if any.
1297 // This is used to avoid emitting unnecessary branches to the next block.
1298 MachineBasicBlock *NextBlock = 0;
1299 MachineFunction::iterator BBI = CurMBB;
1300 if (++BBI != CurMBB->getParent()->end())
1301 NextBlock = BBI;
1302
1303 // If the lhs block is the next block, invert the condition so that we can
1304 // fall through to the lhs instead of the rhs block.
1305 if (CB.TrueBB == NextBlock) {
1306 std::swap(CB.TrueBB, CB.FalseBB);
1307 SDValue True = DAG.getConstant(1, Cond.getValueType());
1308 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1309 }
1310 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1311 DAG.getBasicBlock(CB.TrueBB));
1312
1313 // If the branch was constant folded, fix up the CFG.
1314 if (BrCond.getOpcode() == ISD::BR) {
1315 CurMBB->removeSuccessor(CB.FalseBB);
1316 DAG.setRoot(BrCond);
1317 } else {
1318 // Otherwise, go ahead and insert the false branch.
1319 if (BrCond == getControlRoot())
1320 CurMBB->removeSuccessor(CB.TrueBB);
1321
1322 if (CB.FalseBB == NextBlock)
1323 DAG.setRoot(BrCond);
1324 else
1325 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1326 DAG.getBasicBlock(CB.FalseBB)));
1327 }
1328}
1329
1330/// visitJumpTable - Emit JumpTable node in the current MBB
1331void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1332 // Emit the code for the jump table
1333 assert(JT.Reg != -1U && "Should lower JT Header first!");
1334 MVT PTy = TLI.getPointerTy();
1335 SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1336 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1337 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1338 Table, Index));
1339 return;
1340}
1341
1342/// visitJumpTableHeader - This function emits necessary code to produce index
1343/// in the JumpTable from switch case.
1344void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1345 JumpTableHeader &JTH) {
1346 // Subtract the lowest switch case value from the value being switched on
1347 // and conditional branch to default mbb if the result is greater than the
1348 // difference between smallest and largest cases.
1349 SDValue SwitchOp = getValue(JTH.SValue);
1350 MVT VT = SwitchOp.getValueType();
1351 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1352 DAG.getConstant(JTH.First, VT));
1353
1354 // The SDNode we just created, which holds the value being switched on
1355 // minus the the smallest case value, needs to be copied to a virtual
1356 // register so it can be used as an index into the jump table in a
1357 // subsequent basic block. This value may be smaller or larger than the
1358 // target's pointer type, and therefore require extension or truncating.
1359 if (VT.bitsGT(TLI.getPointerTy()))
1360 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1361 else
1362 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1363
1364 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1365 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1366 JT.Reg = JumpTableReg;
1367
1368 // Emit the range check for the jump table, and branch to the default
1369 // block for the switch statement if the value being switched on exceeds
1370 // the largest case in the switch.
1371 SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1372 DAG.getConstant(JTH.Last-JTH.First,VT),
1373 ISD::SETUGT);
1374
1375 // Set NextBlock to be the MBB immediately after the current one, if any.
1376 // This is used to avoid emitting unnecessary branches to the next block.
1377 MachineBasicBlock *NextBlock = 0;
1378 MachineFunction::iterator BBI = CurMBB;
1379 if (++BBI != CurMBB->getParent()->end())
1380 NextBlock = BBI;
1381
1382 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1383 DAG.getBasicBlock(JT.Default));
1384
1385 if (JT.MBB == NextBlock)
1386 DAG.setRoot(BrCond);
1387 else
1388 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1389 DAG.getBasicBlock(JT.MBB)));
1390
1391 return;
1392}
1393
1394/// visitBitTestHeader - This function emits necessary code to produce value
1395/// suitable for "bit tests"
1396void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1397 // Subtract the minimum value
1398 SDValue SwitchOp = getValue(B.SValue);
1399 MVT VT = SwitchOp.getValueType();
1400 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1401 DAG.getConstant(B.First, VT));
1402
1403 // Check range
1404 SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1405 DAG.getConstant(B.Range, VT),
1406 ISD::SETUGT);
1407
1408 SDValue ShiftOp;
1409 if (VT.bitsGT(TLI.getShiftAmountTy()))
1410 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1411 else
1412 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1413
1414 // Make desired shift
1415 SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1416 DAG.getConstant(1, TLI.getPointerTy()),
1417 ShiftOp);
1418
1419 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1420 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1421 B.Reg = SwitchReg;
1422
1423 // Set NextBlock to be the MBB immediately after the current one, if any.
1424 // This is used to avoid emitting unnecessary branches to the next block.
1425 MachineBasicBlock *NextBlock = 0;
1426 MachineFunction::iterator BBI = CurMBB;
1427 if (++BBI != CurMBB->getParent()->end())
1428 NextBlock = BBI;
1429
1430 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1431
1432 CurMBB->addSuccessor(B.Default);
1433 CurMBB->addSuccessor(MBB);
1434
1435 SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1436 DAG.getBasicBlock(B.Default));
1437
1438 if (MBB == NextBlock)
1439 DAG.setRoot(BrRange);
1440 else
1441 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1442 DAG.getBasicBlock(MBB)));
1443
1444 return;
1445}
1446
1447/// visitBitTestCase - this function produces one "bit test"
1448void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1449 unsigned Reg,
1450 BitTestCase &B) {
1451 // Emit bit tests and jumps
1452 SDValue SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg,
1453 TLI.getPointerTy());
1454
1455 SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
1456 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1457 SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1458 DAG.getConstant(0, TLI.getPointerTy()),
1459 ISD::SETNE);
1460
1461 CurMBB->addSuccessor(B.TargetBB);
1462 CurMBB->addSuccessor(NextMBB);
1463
1464 SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1465 AndCmp, DAG.getBasicBlock(B.TargetBB));
1466
1467 // Set NextBlock to be the MBB immediately after the current one, if any.
1468 // This is used to avoid emitting unnecessary branches to the next block.
1469 MachineBasicBlock *NextBlock = 0;
1470 MachineFunction::iterator BBI = CurMBB;
1471 if (++BBI != CurMBB->getParent()->end())
1472 NextBlock = BBI;
1473
1474 if (NextMBB == NextBlock)
1475 DAG.setRoot(BrAnd);
1476 else
1477 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1478 DAG.getBasicBlock(NextMBB)));
1479
1480 return;
1481}
1482
1483void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1484 // Retrieve successors.
1485 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1486 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1487
1488 if (isa<InlineAsm>(I.getCalledValue()))
1489 visitInlineAsm(&I);
1490 else
1491 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1492
1493 // If the value of the invoke is used outside of its defining block, make it
1494 // available as a virtual register.
1495 if (!I.use_empty()) {
1496 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1497 if (VMI != FuncInfo.ValueMap.end())
1498 CopyValueToVirtualRegister(&I, VMI->second);
1499 }
1500
1501 // Update successor info
1502 CurMBB->addSuccessor(Return);
1503 CurMBB->addSuccessor(LandingPad);
1504
1505 // Drop into normal successor.
1506 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1507 DAG.getBasicBlock(Return)));
1508}
1509
1510void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1511}
1512
1513/// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1514/// small case ranges).
1515bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1516 CaseRecVector& WorkList,
1517 Value* SV,
1518 MachineBasicBlock* Default) {
1519 Case& BackCase = *(CR.Range.second-1);
1520
1521 // Size is the number of Cases represented by this range.
1522 unsigned Size = CR.Range.second - CR.Range.first;
1523 if (Size > 3)
1524 return false;
1525
1526 // Get the MachineFunction which holds the current MBB. This is used when
1527 // inserting any additional MBBs necessary to represent the switch.
1528 MachineFunction *CurMF = CurMBB->getParent();
1529
1530 // Figure out which block is immediately after the current one.
1531 MachineBasicBlock *NextBlock = 0;
1532 MachineFunction::iterator BBI = CR.CaseBB;
1533
1534 if (++BBI != CurMBB->getParent()->end())
1535 NextBlock = BBI;
1536
1537 // TODO: If any two of the cases has the same destination, and if one value
1538 // is the same as the other, but has one bit unset that the other has set,
1539 // use bit manipulation to do two compares at once. For example:
1540 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1541
1542 // Rearrange the case blocks so that the last one falls through if possible.
1543 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1544 // The last case block won't fall through into 'NextBlock' if we emit the
1545 // branches in this order. See if rearranging a case value would help.
1546 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1547 if (I->BB == NextBlock) {
1548 std::swap(*I, BackCase);
1549 break;
1550 }
1551 }
1552 }
1553
1554 // Create a CaseBlock record representing a conditional branch to
1555 // the Case's target mbb if the value being switched on SV is equal
1556 // to C.
1557 MachineBasicBlock *CurBlock = CR.CaseBB;
1558 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1559 MachineBasicBlock *FallThrough;
1560 if (I != E-1) {
1561 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1562 CurMF->insert(BBI, FallThrough);
1563 } else {
1564 // If the last case doesn't match, go to the default block.
1565 FallThrough = Default;
1566 }
1567
1568 Value *RHS, *LHS, *MHS;
1569 ISD::CondCode CC;
1570 if (I->High == I->Low) {
1571 // This is just small small case range :) containing exactly 1 case
1572 CC = ISD::SETEQ;
1573 LHS = SV; RHS = I->High; MHS = NULL;
1574 } else {
1575 CC = ISD::SETLE;
1576 LHS = I->Low; MHS = SV; RHS = I->High;
1577 }
1578 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1579
1580 // If emitting the first comparison, just call visitSwitchCase to emit the
1581 // code into the current block. Otherwise, push the CaseBlock onto the
1582 // vector to be later processed by SDISel, and insert the node's MBB
1583 // before the next MBB.
1584 if (CurBlock == CurMBB)
1585 visitSwitchCase(CB);
1586 else
1587 SwitchCases.push_back(CB);
1588
1589 CurBlock = FallThrough;
1590 }
1591
1592 return true;
1593}
1594
1595static inline bool areJTsAllowed(const TargetLowering &TLI) {
1596 return !DisableJumpTables &&
1597 (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1598 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1599}
1600
1601/// handleJTSwitchCase - Emit jumptable for current switch case range
1602bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1603 CaseRecVector& WorkList,
1604 Value* SV,
1605 MachineBasicBlock* Default) {
1606 Case& FrontCase = *CR.Range.first;
1607 Case& BackCase = *(CR.Range.second-1);
1608
1609 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1610 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1611
1612 uint64_t TSize = 0;
1613 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1614 I!=E; ++I)
1615 TSize += I->size();
1616
1617 if (!areJTsAllowed(TLI) || TSize <= 3)
1618 return false;
1619
1620 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1621 if (Density < 0.4)
1622 return false;
1623
1624 DOUT << "Lowering jump table\n"
1625 << "First entry: " << First << ". Last entry: " << Last << "\n"
1626 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1627
1628 // Get the MachineFunction which holds the current MBB. This is used when
1629 // inserting any additional MBBs necessary to represent the switch.
1630 MachineFunction *CurMF = CurMBB->getParent();
1631
1632 // Figure out which block is immediately after the current one.
1633 MachineBasicBlock *NextBlock = 0;
1634 MachineFunction::iterator BBI = CR.CaseBB;
1635
1636 if (++BBI != CurMBB->getParent()->end())
1637 NextBlock = BBI;
1638
1639 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1640
1641 // Create a new basic block to hold the code for loading the address
1642 // of the jump table, and jumping to it. Update successor information;
1643 // we will either branch to the default case for the switch, or the jump
1644 // table.
1645 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1646 CurMF->insert(BBI, JumpTableBB);
1647 CR.CaseBB->addSuccessor(Default);
1648 CR.CaseBB->addSuccessor(JumpTableBB);
1649
1650 // Build a vector of destination BBs, corresponding to each target
1651 // of the jump table. If the value of the jump table slot corresponds to
1652 // a case statement, push the case's BB onto the vector, otherwise, push
1653 // the default BB.
1654 std::vector<MachineBasicBlock*> DestBBs;
1655 int64_t TEI = First;
1656 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1657 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1658 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1659
1660 if ((Low <= TEI) && (TEI <= High)) {
1661 DestBBs.push_back(I->BB);
1662 if (TEI==High)
1663 ++I;
1664 } else {
1665 DestBBs.push_back(Default);
1666 }
1667 }
1668
1669 // Update successor info. Add one edge to each unique successor.
1670 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1671 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1672 E = DestBBs.end(); I != E; ++I) {
1673 if (!SuccsHandled[(*I)->getNumber()]) {
1674 SuccsHandled[(*I)->getNumber()] = true;
1675 JumpTableBB->addSuccessor(*I);
1676 }
1677 }
1678
1679 // Create a jump table index for this jump table, or return an existing
1680 // one.
1681 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1682
1683 // Set the jump table information so that we can codegen it as a second
1684 // MachineBasicBlock
1685 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1686 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1687 if (CR.CaseBB == CurMBB)
1688 visitJumpTableHeader(JT, JTH);
1689
1690 JTCases.push_back(JumpTableBlock(JTH, JT));
1691
1692 return true;
1693}
1694
1695/// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1696/// 2 subtrees.
1697bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1698 CaseRecVector& WorkList,
1699 Value* SV,
1700 MachineBasicBlock* Default) {
1701 // Get the MachineFunction which holds the current MBB. This is used when
1702 // inserting any additional MBBs necessary to represent the switch.
1703 MachineFunction *CurMF = CurMBB->getParent();
1704
1705 // Figure out which block is immediately after the current one.
1706 MachineBasicBlock *NextBlock = 0;
1707 MachineFunction::iterator BBI = CR.CaseBB;
1708
1709 if (++BBI != CurMBB->getParent()->end())
1710 NextBlock = BBI;
1711
1712 Case& FrontCase = *CR.Range.first;
1713 Case& BackCase = *(CR.Range.second-1);
1714 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1715
1716 // Size is the number of Cases represented by this range.
1717 unsigned Size = CR.Range.second - CR.Range.first;
1718
1719 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1720 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1721 double FMetric = 0;
1722 CaseItr Pivot = CR.Range.first + Size/2;
1723
1724 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1725 // (heuristically) allow us to emit JumpTable's later.
1726 uint64_t TSize = 0;
1727 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1728 I!=E; ++I)
1729 TSize += I->size();
1730
1731 uint64_t LSize = FrontCase.size();
1732 uint64_t RSize = TSize-LSize;
1733 DOUT << "Selecting best pivot: \n"
1734 << "First: " << First << ", Last: " << Last <<"\n"
1735 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1736 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1737 J!=E; ++I, ++J) {
1738 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1739 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1740 assert((RBegin-LEnd>=1) && "Invalid case distance");
1741 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1742 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1743 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1744 // Should always split in some non-trivial place
1745 DOUT <<"=>Step\n"
1746 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1747 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1748 << "Metric: " << Metric << "\n";
1749 if (FMetric < Metric) {
1750 Pivot = J;
1751 FMetric = Metric;
1752 DOUT << "Current metric set to: " << FMetric << "\n";
1753 }
1754
1755 LSize += J->size();
1756 RSize -= J->size();
1757 }
1758 if (areJTsAllowed(TLI)) {
1759 // If our case is dense we *really* should handle it earlier!
1760 assert((FMetric > 0) && "Should handle dense range earlier!");
1761 } else {
1762 Pivot = CR.Range.first + Size/2;
1763 }
1764
1765 CaseRange LHSR(CR.Range.first, Pivot);
1766 CaseRange RHSR(Pivot, CR.Range.second);
1767 Constant *C = Pivot->Low;
1768 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1769
1770 // We know that we branch to the LHS if the Value being switched on is
1771 // less than the Pivot value, C. We use this to optimize our binary
1772 // tree a bit, by recognizing that if SV is greater than or equal to the
1773 // LHS's Case Value, and that Case Value is exactly one less than the
1774 // Pivot's Value, then we can branch directly to the LHS's Target,
1775 // rather than creating a leaf node for it.
1776 if ((LHSR.second - LHSR.first) == 1 &&
1777 LHSR.first->High == CR.GE &&
1778 cast<ConstantInt>(C)->getSExtValue() ==
1779 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1780 TrueBB = LHSR.first->BB;
1781 } else {
1782 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1783 CurMF->insert(BBI, TrueBB);
1784 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1785 }
1786
1787 // Similar to the optimization above, if the Value being switched on is
1788 // known to be less than the Constant CR.LT, and the current Case Value
1789 // is CR.LT - 1, then we can branch directly to the target block for
1790 // the current Case Value, rather than emitting a RHS leaf node for it.
1791 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1792 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1793 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1794 FalseBB = RHSR.first->BB;
1795 } else {
1796 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1797 CurMF->insert(BBI, FalseBB);
1798 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1799 }
1800
1801 // Create a CaseBlock record representing a conditional branch to
1802 // the LHS node if the value being switched on SV is less than C.
1803 // Otherwise, branch to LHS.
1804 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1805
1806 if (CR.CaseBB == CurMBB)
1807 visitSwitchCase(CB);
1808 else
1809 SwitchCases.push_back(CB);
1810
1811 return true;
1812}
1813
1814/// handleBitTestsSwitchCase - if current case range has few destination and
1815/// range span less, than machine word bitwidth, encode case range into series
1816/// of masks and emit bit tests with these masks.
1817bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1818 CaseRecVector& WorkList,
1819 Value* SV,
1820 MachineBasicBlock* Default){
1821 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1822
1823 Case& FrontCase = *CR.Range.first;
1824 Case& BackCase = *(CR.Range.second-1);
1825
1826 // Get the MachineFunction which holds the current MBB. This is used when
1827 // inserting any additional MBBs necessary to represent the switch.
1828 MachineFunction *CurMF = CurMBB->getParent();
1829
1830 unsigned numCmps = 0;
1831 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1832 I!=E; ++I) {
1833 // Single case counts one, case range - two.
1834 if (I->Low == I->High)
1835 numCmps +=1;
1836 else
1837 numCmps +=2;
1838 }
1839
1840 // Count unique destinations
1841 SmallSet<MachineBasicBlock*, 4> Dests;
1842 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1843 Dests.insert(I->BB);
1844 if (Dests.size() > 3)
1845 // Don't bother the code below, if there are too much unique destinations
1846 return false;
1847 }
1848 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1849 << "Total number of comparisons: " << numCmps << "\n";
1850
1851 // Compute span of values.
1852 Constant* minValue = FrontCase.Low;
1853 Constant* maxValue = BackCase.High;
1854 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1855 cast<ConstantInt>(minValue)->getSExtValue();
1856 DOUT << "Compare range: " << range << "\n"
1857 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1858 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1859
1860 if (range>=IntPtrBits ||
1861 (!(Dests.size() == 1 && numCmps >= 3) &&
1862 !(Dests.size() == 2 && numCmps >= 5) &&
1863 !(Dests.size() >= 3 && numCmps >= 6)))
1864 return false;
1865
1866 DOUT << "Emitting bit tests\n";
1867 int64_t lowBound = 0;
1868
1869 // Optimize the case where all the case values fit in a
1870 // word without having to subtract minValue. In this case,
1871 // we can optimize away the subtraction.
1872 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
1873 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
1874 range = cast<ConstantInt>(maxValue)->getSExtValue();
1875 } else {
1876 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1877 }
1878
1879 CaseBitsVector CasesBits;
1880 unsigned i, count = 0;
1881
1882 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1883 MachineBasicBlock* Dest = I->BB;
1884 for (i = 0; i < count; ++i)
1885 if (Dest == CasesBits[i].BB)
1886 break;
1887
1888 if (i == count) {
1889 assert((count < 3) && "Too much destinations to test!");
1890 CasesBits.push_back(CaseBits(0, Dest, 0));
1891 count++;
1892 }
1893
1894 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1895 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1896
1897 for (uint64_t j = lo; j <= hi; j++) {
1898 CasesBits[i].Mask |= 1ULL << j;
1899 CasesBits[i].Bits++;
1900 }
1901
1902 }
1903 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1904
1905 BitTestInfo BTC;
1906
1907 // Figure out which block is immediately after the current one.
1908 MachineFunction::iterator BBI = CR.CaseBB;
1909 ++BBI;
1910
1911 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1912
1913 DOUT << "Cases:\n";
1914 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1915 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1916 << ", BB: " << CasesBits[i].BB << "\n";
1917
1918 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1919 CurMF->insert(BBI, CaseBB);
1920 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1921 CaseBB,
1922 CasesBits[i].BB));
1923 }
1924
1925 BitTestBlock BTB(lowBound, range, SV,
1926 -1U, (CR.CaseBB == CurMBB),
1927 CR.CaseBB, Default, BTC);
1928
1929 if (CR.CaseBB == CurMBB)
1930 visitBitTestHeader(BTB);
1931
1932 BitTestCases.push_back(BTB);
1933
1934 return true;
1935}
1936
1937
1938/// Clusterify - Transform simple list of Cases into list of CaseRange's
1939unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1940 const SwitchInst& SI) {
1941 unsigned numCmps = 0;
1942
1943 // Start with "simple" cases
1944 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1945 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1946 Cases.push_back(Case(SI.getSuccessorValue(i),
1947 SI.getSuccessorValue(i),
1948 SMBB));
1949 }
1950 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1951
1952 // Merge case into clusters
1953 if (Cases.size()>=2)
1954 // Must recompute end() each iteration because it may be
1955 // invalidated by erase if we hold on to it
1956 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
1957 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1958 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1959 MachineBasicBlock* nextBB = J->BB;
1960 MachineBasicBlock* currentBB = I->BB;
1961
1962 // If the two neighboring cases go to the same destination, merge them
1963 // into a single case.
1964 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1965 I->High = J->High;
1966 J = Cases.erase(J);
1967 } else {
1968 I = J++;
1969 }
1970 }
1971
1972 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1973 if (I->Low != I->High)
1974 // A range counts double, since it requires two compares.
1975 ++numCmps;
1976 }
1977
1978 return numCmps;
1979}
1980
1981void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
1982 // Figure out which block is immediately after the current one.
1983 MachineBasicBlock *NextBlock = 0;
1984 MachineFunction::iterator BBI = CurMBB;
1985
1986 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1987
1988 // If there is only the default destination, branch to it if it is not the
1989 // next basic block. Otherwise, just fall through.
1990 if (SI.getNumOperands() == 2) {
1991 // Update machine-CFG edges.
1992
1993 // If this is not a fall-through branch, emit the branch.
1994 CurMBB->addSuccessor(Default);
1995 if (Default != NextBlock)
1996 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1997 DAG.getBasicBlock(Default)));
1998
1999 return;
2000 }
2001
2002 // If there are any non-default case statements, create a vector of Cases
2003 // representing each one, and sort the vector so that we can efficiently
2004 // create a binary search tree from them.
2005 CaseVector Cases;
2006 unsigned numCmps = Clusterify(Cases, SI);
2007 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2008 << ". Total compares: " << numCmps << "\n";
2009
2010 // Get the Value to be switched on and default basic blocks, which will be
2011 // inserted into CaseBlock records, representing basic blocks in the binary
2012 // search tree.
2013 Value *SV = SI.getOperand(0);
2014
2015 // Push the initial CaseRec onto the worklist
2016 CaseRecVector WorkList;
2017 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2018
2019 while (!WorkList.empty()) {
2020 // Grab a record representing a case range to process off the worklist
2021 CaseRec CR = WorkList.back();
2022 WorkList.pop_back();
2023
2024 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2025 continue;
2026
2027 // If the range has few cases (two or less) emit a series of specific
2028 // tests.
2029 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2030 continue;
2031
2032 // If the switch has more than 5 blocks, and at least 40% dense, and the
2033 // target supports indirect branches, then emit a jump table rather than
2034 // lowering the switch to a binary tree of conditional branches.
2035 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2036 continue;
2037
2038 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2039 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2040 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2041 }
2042}
2043
2044
2045void SelectionDAGLowering::visitSub(User &I) {
2046 // -0.0 - X --> fneg
2047 const Type *Ty = I.getType();
2048 if (isa<VectorType>(Ty)) {
2049 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2050 const VectorType *DestTy = cast<VectorType>(I.getType());
2051 const Type *ElTy = DestTy->getElementType();
2052 if (ElTy->isFloatingPoint()) {
2053 unsigned VL = DestTy->getNumElements();
2054 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2055 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2056 if (CV == CNZ) {
2057 SDValue Op2 = getValue(I.getOperand(1));
2058 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2059 return;
2060 }
2061 }
2062 }
2063 }
2064 if (Ty->isFloatingPoint()) {
2065 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2066 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2067 SDValue Op2 = getValue(I.getOperand(1));
2068 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2069 return;
2070 }
2071 }
2072
2073 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2074}
2075
2076void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2077 SDValue Op1 = getValue(I.getOperand(0));
2078 SDValue Op2 = getValue(I.getOperand(1));
2079
2080 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2081}
2082
2083void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2084 SDValue Op1 = getValue(I.getOperand(0));
2085 SDValue Op2 = getValue(I.getOperand(1));
2086 if (!isa<VectorType>(I.getType())) {
2087 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2088 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2089 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2090 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2091 }
2092
2093 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2094}
2095
2096void SelectionDAGLowering::visitICmp(User &I) {
2097 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2098 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2099 predicate = IC->getPredicate();
2100 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2101 predicate = ICmpInst::Predicate(IC->getPredicate());
2102 SDValue Op1 = getValue(I.getOperand(0));
2103 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002104 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002105 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2106}
2107
2108void SelectionDAGLowering::visitFCmp(User &I) {
2109 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2110 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2111 predicate = FC->getPredicate();
2112 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2113 predicate = FCmpInst::Predicate(FC->getPredicate());
2114 SDValue Op1 = getValue(I.getOperand(0));
2115 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002116 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002117 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2118}
2119
2120void SelectionDAGLowering::visitVICmp(User &I) {
2121 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2122 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2123 predicate = IC->getPredicate();
2124 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2125 predicate = ICmpInst::Predicate(IC->getPredicate());
2126 SDValue Op1 = getValue(I.getOperand(0));
2127 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002128 ISD::CondCode Opcode = getICmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002129 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2130}
2131
2132void SelectionDAGLowering::visitVFCmp(User &I) {
2133 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2134 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2135 predicate = FC->getPredicate();
2136 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2137 predicate = FCmpInst::Predicate(FC->getPredicate());
2138 SDValue Op1 = getValue(I.getOperand(0));
2139 SDValue Op2 = getValue(I.getOperand(1));
Dan Gohman8c1a6ca2008-10-17 18:18:45 +00002140 ISD::CondCode Condition = getFCmpCondCode(predicate);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002141 MVT DestVT = TLI.getValueType(I.getType());
2142
2143 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2144}
2145
2146void SelectionDAGLowering::visitSelect(User &I) {
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002147 SmallVector<MVT, 4> ValueVTs;
2148 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2149 unsigned NumValues = ValueVTs.size();
2150 if (NumValues != 0) {
2151 SmallVector<SDValue, 4> Values(NumValues);
2152 SDValue Cond = getValue(I.getOperand(0));
2153 SDValue TrueVal = getValue(I.getOperand(1));
2154 SDValue FalseVal = getValue(I.getOperand(2));
2155
2156 for (unsigned i = 0; i != NumValues; ++i)
2157 Values[i] = DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2158 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2159 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2160
Duncan Sandsaaffa052008-12-01 11:41:29 +00002161 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2162 DAG.getVTList(&ValueVTs[0], NumValues),
2163 &Values[0], NumValues));
Dan Gohman7ea1ca62008-10-21 20:00:42 +00002164 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002165}
2166
2167
2168void SelectionDAGLowering::visitTrunc(User &I) {
2169 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2170 SDValue N = getValue(I.getOperand(0));
2171 MVT DestVT = TLI.getValueType(I.getType());
2172 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2173}
2174
2175void SelectionDAGLowering::visitZExt(User &I) {
2176 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2177 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2178 SDValue N = getValue(I.getOperand(0));
2179 MVT DestVT = TLI.getValueType(I.getType());
2180 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2181}
2182
2183void SelectionDAGLowering::visitSExt(User &I) {
2184 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2185 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2186 SDValue N = getValue(I.getOperand(0));
2187 MVT DestVT = TLI.getValueType(I.getType());
2188 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2189}
2190
2191void SelectionDAGLowering::visitFPTrunc(User &I) {
2192 // FPTrunc is never a no-op cast, no need to check
2193 SDValue N = getValue(I.getOperand(0));
2194 MVT DestVT = TLI.getValueType(I.getType());
2195 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2196}
2197
2198void SelectionDAGLowering::visitFPExt(User &I){
2199 // FPTrunc is never a no-op cast, no need to check
2200 SDValue N = getValue(I.getOperand(0));
2201 MVT DestVT = TLI.getValueType(I.getType());
2202 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2203}
2204
2205void SelectionDAGLowering::visitFPToUI(User &I) {
2206 // FPToUI is never a no-op cast, no need to check
2207 SDValue N = getValue(I.getOperand(0));
2208 MVT DestVT = TLI.getValueType(I.getType());
2209 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2210}
2211
2212void SelectionDAGLowering::visitFPToSI(User &I) {
2213 // FPToSI is never a no-op cast, no need to check
2214 SDValue N = getValue(I.getOperand(0));
2215 MVT DestVT = TLI.getValueType(I.getType());
2216 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2217}
2218
2219void SelectionDAGLowering::visitUIToFP(User &I) {
2220 // UIToFP is never a no-op cast, no need to check
2221 SDValue N = getValue(I.getOperand(0));
2222 MVT DestVT = TLI.getValueType(I.getType());
2223 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2224}
2225
2226void SelectionDAGLowering::visitSIToFP(User &I){
Bill Wendling181b6272008-10-19 20:34:04 +00002227 // SIToFP is never a no-op cast, no need to check
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002228 SDValue N = getValue(I.getOperand(0));
2229 MVT DestVT = TLI.getValueType(I.getType());
2230 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2231}
2232
2233void SelectionDAGLowering::visitPtrToInt(User &I) {
2234 // What to do depends on the size of the integer and the size of the pointer.
2235 // We can either truncate, zero extend, or no-op, accordingly.
2236 SDValue N = getValue(I.getOperand(0));
2237 MVT SrcVT = N.getValueType();
2238 MVT DestVT = TLI.getValueType(I.getType());
2239 SDValue Result;
2240 if (DestVT.bitsLT(SrcVT))
2241 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2242 else
2243 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2244 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2245 setValue(&I, Result);
2246}
2247
2248void SelectionDAGLowering::visitIntToPtr(User &I) {
2249 // What to do depends on the size of the integer and the size of the pointer.
2250 // We can either truncate, zero extend, or no-op, accordingly.
2251 SDValue N = getValue(I.getOperand(0));
2252 MVT SrcVT = N.getValueType();
2253 MVT DestVT = TLI.getValueType(I.getType());
2254 if (DestVT.bitsLT(SrcVT))
2255 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2256 else
2257 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2258 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2259}
2260
2261void SelectionDAGLowering::visitBitCast(User &I) {
2262 SDValue N = getValue(I.getOperand(0));
2263 MVT DestVT = TLI.getValueType(I.getType());
2264
2265 // BitCast assures us that source and destination are the same size so this
2266 // is either a BIT_CONVERT or a no-op.
2267 if (DestVT != N.getValueType())
2268 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2269 else
2270 setValue(&I, N); // noop cast.
2271}
2272
2273void SelectionDAGLowering::visitInsertElement(User &I) {
2274 SDValue InVec = getValue(I.getOperand(0));
2275 SDValue InVal = getValue(I.getOperand(1));
2276 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2277 getValue(I.getOperand(2)));
2278
2279 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2280 TLI.getValueType(I.getType()),
2281 InVec, InVal, InIdx));
2282}
2283
2284void SelectionDAGLowering::visitExtractElement(User &I) {
2285 SDValue InVec = getValue(I.getOperand(0));
2286 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2287 getValue(I.getOperand(1)));
2288 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2289 TLI.getValueType(I.getType()), InVec, InIdx));
2290}
2291
Mon P Wangaeb06d22008-11-10 04:46:22 +00002292
2293// Utility for visitShuffleVector - Returns true if the mask is mask starting
2294// from SIndx and increasing to the element length (undefs are allowed).
2295static bool SequentialMask(SDValue Mask, unsigned SIndx) {
Mon P Wangc7849c22008-11-16 05:06:27 +00002296 unsigned MaskNumElts = Mask.getNumOperands();
2297 for (unsigned i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002298 if (Mask.getOperand(i).getOpcode() != ISD::UNDEF) {
2299 unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2300 if (Idx != i + SIndx)
2301 return false;
2302 }
2303 }
2304 return true;
2305}
2306
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002307void SelectionDAGLowering::visitShuffleVector(User &I) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002308 SDValue Src1 = getValue(I.getOperand(0));
2309 SDValue Src2 = getValue(I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002310 SDValue Mask = getValue(I.getOperand(2));
2311
Mon P Wangaeb06d22008-11-10 04:46:22 +00002312 MVT VT = TLI.getValueType(I.getType());
Mon P Wang230e4fa2008-11-21 04:25:21 +00002313 MVT SrcVT = Src1.getValueType();
Mon P Wangc7849c22008-11-16 05:06:27 +00002314 int MaskNumElts = Mask.getNumOperands();
2315 int SrcNumElts = SrcVT.getVectorNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +00002316
Mon P Wangc7849c22008-11-16 05:06:27 +00002317 if (SrcNumElts == MaskNumElts) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002318 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002319 return;
2320 }
2321
2322 // Normalize the shuffle vector since mask and vector length don't match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002323 MVT MaskEltVT = Mask.getValueType().getVectorElementType();
2324
2325 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2326 // Mask is longer than the source vectors and is a multiple of the source
2327 // vectors. We can use concatenate vector to make the mask and vectors
Mon P Wang230e4fa2008-11-21 04:25:21 +00002328 // lengths match.
Mon P Wangc7849c22008-11-16 05:06:27 +00002329 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2330 // The shuffle is concatenating two vectors together.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002331 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, VT, Src1, Src2));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002332 return;
2333 }
2334
Mon P Wangc7849c22008-11-16 05:06:27 +00002335 // Pad both vectors with undefs to make them the same length as the mask.
2336 unsigned NumConcat = MaskNumElts / SrcNumElts;
2337 SDValue UndefVal = DAG.getNode(ISD::UNDEF, SrcVT);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002338
Mon P Wang230e4fa2008-11-21 04:25:21 +00002339 SDValue* MOps1 = new SDValue[NumConcat];
2340 SDValue* MOps2 = new SDValue[NumConcat];
2341 MOps1[0] = Src1;
2342 MOps2[0] = Src2;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002343 for (unsigned i = 1; i != NumConcat; ++i) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002344 MOps1[i] = UndefVal;
2345 MOps2[i] = UndefVal;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002346 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002347 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, VT, MOps1, NumConcat);
2348 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, VT, MOps2, NumConcat);
2349
2350 delete [] MOps1;
2351 delete [] MOps2;
2352
Mon P Wangaeb06d22008-11-10 04:46:22 +00002353 // Readjust mask for new input vector length.
2354 SmallVector<SDValue, 8> MappedOps;
Mon P Wangc7849c22008-11-16 05:06:27 +00002355 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002356 if (Mask.getOperand(i).getOpcode() == ISD::UNDEF) {
2357 MappedOps.push_back(Mask.getOperand(i));
2358 } else {
Mon P Wangc7849c22008-11-16 05:06:27 +00002359 int Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2360 if (Idx < SrcNumElts)
2361 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2362 else
2363 MappedOps.push_back(DAG.getConstant(Idx + MaskNumElts - SrcNumElts,
2364 MaskEltVT));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002365 }
2366 }
2367 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2368 &MappedOps[0], MappedOps.size());
2369
Mon P Wang230e4fa2008-11-21 04:25:21 +00002370 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002371 return;
2372 }
2373
Mon P Wangc7849c22008-11-16 05:06:27 +00002374 if (SrcNumElts > MaskNumElts) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002375 // Resulting vector is shorter than the incoming vector.
Mon P Wangc7849c22008-11-16 05:06:27 +00002376 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,0)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002377 // Shuffle extracts 1st vector.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002378 setValue(&I, Src1);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002379 return;
2380 }
2381
Mon P Wangc7849c22008-11-16 05:06:27 +00002382 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,MaskNumElts)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002383 // Shuffle extracts 2nd vector.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002384 setValue(&I, Src2);
Mon P Wangaeb06d22008-11-10 04:46:22 +00002385 return;
2386 }
2387
Mon P Wangc7849c22008-11-16 05:06:27 +00002388 // Analyze the access pattern of the vector to see if we can extract
2389 // two subvectors and do the shuffle. The analysis is done by calculating
2390 // the range of elements the mask access on both vectors.
2391 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2392 int MaxRange[2] = {-1, -1};
2393
2394 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002395 SDValue Arg = Mask.getOperand(i);
2396 if (Arg.getOpcode() != ISD::UNDEF) {
2397 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Mon P Wangc7849c22008-11-16 05:06:27 +00002398 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2399 int Input = 0;
2400 if (Idx >= SrcNumElts) {
2401 Input = 1;
2402 Idx -= SrcNumElts;
2403 }
2404 if (Idx > MaxRange[Input])
2405 MaxRange[Input] = Idx;
2406 if (Idx < MinRange[Input])
2407 MinRange[Input] = Idx;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002408 }
2409 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002410
Mon P Wangc7849c22008-11-16 05:06:27 +00002411 // Check if the access is smaller than the vector size and can we find
2412 // a reasonable extract index.
Mon P Wang230e4fa2008-11-21 04:25:21 +00002413 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
Mon P Wangc7849c22008-11-16 05:06:27 +00002414 int StartIdx[2]; // StartIdx to extract from
2415 for (int Input=0; Input < 2; ++Input) {
2416 if (MinRange[Input] == SrcNumElts+1 && MaxRange[Input] == -1) {
2417 RangeUse[Input] = 0; // Unused
2418 StartIdx[Input] = 0;
2419 } else if (MaxRange[Input] - MinRange[Input] < MaskNumElts) {
2420 // Fits within range but we should see if we can find a good
Mon P Wang230e4fa2008-11-21 04:25:21 +00002421 // start index that is a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002422 if (MaxRange[Input] < MaskNumElts) {
2423 RangeUse[Input] = 1; // Extract from beginning of the vector
2424 StartIdx[Input] = 0;
2425 } else {
2426 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
Mon P Wang6cce3da2008-11-23 04:35:05 +00002427 if (MaxRange[Input] - StartIdx[Input] < MaskNumElts &&
2428 StartIdx[Input] + MaskNumElts < SrcNumElts)
Mon P Wangc7849c22008-11-16 05:06:27 +00002429 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
Mon P Wangc7849c22008-11-16 05:06:27 +00002430 }
Mon P Wang230e4fa2008-11-21 04:25:21 +00002431 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002432 }
2433
2434 if (RangeUse[0] == 0 && RangeUse[0] == 0) {
2435 setValue(&I, DAG.getNode(ISD::UNDEF, VT)); // Vectors are not used.
2436 return;
2437 }
2438 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2439 // Extract appropriate subvector and generate a vector shuffle
2440 for (int Input=0; Input < 2; ++Input) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002441 SDValue& Src = Input == 0 ? Src1 : Src2;
Mon P Wangc7849c22008-11-16 05:06:27 +00002442 if (RangeUse[Input] == 0) {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002443 Src = DAG.getNode(ISD::UNDEF, VT);
Mon P Wangc7849c22008-11-16 05:06:27 +00002444 } else {
Mon P Wang230e4fa2008-11-21 04:25:21 +00002445 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, VT, Src,
2446 DAG.getIntPtrConstant(StartIdx[Input]));
Mon P Wangc7849c22008-11-16 05:06:27 +00002447 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00002448 }
Mon P Wangc7849c22008-11-16 05:06:27 +00002449 // Calculate new mask.
2450 SmallVector<SDValue, 8> MappedOps;
2451 for (int i = 0; i != MaskNumElts; ++i) {
2452 SDValue Arg = Mask.getOperand(i);
2453 if (Arg.getOpcode() == ISD::UNDEF) {
2454 MappedOps.push_back(Arg);
2455 } else {
2456 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2457 if (Idx < SrcNumElts)
2458 MappedOps.push_back(DAG.getConstant(Idx - StartIdx[0], MaskEltVT));
2459 else {
2460 Idx = Idx - SrcNumElts - StartIdx[1] + MaskNumElts;
2461 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2462 }
2463 }
2464 }
2465 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2466 &MappedOps[0], MappedOps.size());
Mon P Wang230e4fa2008-11-21 04:25:21 +00002467 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
Mon P Wangc7849c22008-11-16 05:06:27 +00002468 return;
Mon P Wangaeb06d22008-11-10 04:46:22 +00002469 }
2470 }
2471
Mon P Wangc7849c22008-11-16 05:06:27 +00002472 // We can't use either concat vectors or extract subvectors so fall back to
2473 // replacing the shuffle with extract and build vector.
2474 // to insert and build vector.
Mon P Wangaeb06d22008-11-10 04:46:22 +00002475 MVT EltVT = VT.getVectorElementType();
2476 MVT PtrVT = TLI.getPointerTy();
2477 SmallVector<SDValue,8> Ops;
Mon P Wangc7849c22008-11-16 05:06:27 +00002478 for (int i = 0; i != MaskNumElts; ++i) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00002479 SDValue Arg = Mask.getOperand(i);
2480 if (Arg.getOpcode() == ISD::UNDEF) {
2481 Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2482 } else {
2483 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
Mon P Wangc7849c22008-11-16 05:06:27 +00002484 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2485 if (Idx < SrcNumElts)
Mon P Wang230e4fa2008-11-21 04:25:21 +00002486 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Src1,
Mon P Wangaeb06d22008-11-10 04:46:22 +00002487 DAG.getConstant(Idx, PtrVT)));
2488 else
Mon P Wang230e4fa2008-11-21 04:25:21 +00002489 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Src2,
Mon P Wangc7849c22008-11-16 05:06:27 +00002490 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
Mon P Wangaeb06d22008-11-10 04:46:22 +00002491 }
2492 }
2493 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002494}
2495
2496void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2497 const Value *Op0 = I.getOperand(0);
2498 const Value *Op1 = I.getOperand(1);
2499 const Type *AggTy = I.getType();
2500 const Type *ValTy = Op1->getType();
2501 bool IntoUndef = isa<UndefValue>(Op0);
2502 bool FromUndef = isa<UndefValue>(Op1);
2503
2504 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2505 I.idx_begin(), I.idx_end());
2506
2507 SmallVector<MVT, 4> AggValueVTs;
2508 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2509 SmallVector<MVT, 4> ValValueVTs;
2510 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2511
2512 unsigned NumAggValues = AggValueVTs.size();
2513 unsigned NumValValues = ValValueVTs.size();
2514 SmallVector<SDValue, 4> Values(NumAggValues);
2515
2516 SDValue Agg = getValue(Op0);
2517 SDValue Val = getValue(Op1);
2518 unsigned i = 0;
2519 // Copy the beginning value(s) from the original aggregate.
2520 for (; i != LinearIndex; ++i)
2521 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2522 SDValue(Agg.getNode(), Agg.getResNo() + i);
2523 // Copy values from the inserted value(s).
2524 for (; i != LinearIndex + NumValValues; ++i)
2525 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2526 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2527 // Copy remaining value(s) from the original aggregate.
2528 for (; i != NumAggValues; ++i)
2529 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2530 SDValue(Agg.getNode(), Agg.getResNo() + i);
2531
Duncan Sandsaaffa052008-12-01 11:41:29 +00002532 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2533 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2534 &Values[0], NumAggValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002535}
2536
2537void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2538 const Value *Op0 = I.getOperand(0);
2539 const Type *AggTy = Op0->getType();
2540 const Type *ValTy = I.getType();
2541 bool OutOfUndef = isa<UndefValue>(Op0);
2542
2543 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2544 I.idx_begin(), I.idx_end());
2545
2546 SmallVector<MVT, 4> ValValueVTs;
2547 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2548
2549 unsigned NumValValues = ValValueVTs.size();
2550 SmallVector<SDValue, 4> Values(NumValValues);
2551
2552 SDValue Agg = getValue(Op0);
2553 // Copy out the selected value(s).
2554 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2555 Values[i - LinearIndex] =
Bill Wendlingf0a2d0c2008-11-20 07:24:30 +00002556 OutOfUndef ?
2557 DAG.getNode(ISD::UNDEF,
2558 Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2559 SDValue(Agg.getNode(), Agg.getResNo() + i);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002560
Duncan Sandsaaffa052008-12-01 11:41:29 +00002561 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2562 DAG.getVTList(&ValValueVTs[0], NumValValues),
2563 &Values[0], NumValValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002564}
2565
2566
2567void SelectionDAGLowering::visitGetElementPtr(User &I) {
2568 SDValue N = getValue(I.getOperand(0));
2569 const Type *Ty = I.getOperand(0)->getType();
2570
2571 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2572 OI != E; ++OI) {
2573 Value *Idx = *OI;
2574 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2575 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2576 if (Field) {
2577 // N = N + Offset
2578 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2579 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2580 DAG.getIntPtrConstant(Offset));
2581 }
2582 Ty = StTy->getElementType(Field);
2583 } else {
2584 Ty = cast<SequentialType>(Ty)->getElementType();
2585
2586 // If this is a constant subscript, handle it quickly.
2587 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2588 if (CI->getZExtValue() == 0) continue;
2589 uint64_t Offs =
2590 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2591 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2592 DAG.getIntPtrConstant(Offs));
2593 continue;
2594 }
2595
2596 // N = N + Idx * ElementSize;
2597 uint64_t ElementSize = TD->getABITypeSize(Ty);
2598 SDValue IdxN = getValue(Idx);
2599
2600 // If the index is smaller or larger than intptr_t, truncate or extend
2601 // it.
2602 if (IdxN.getValueType().bitsLT(N.getValueType()))
2603 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2604 else if (IdxN.getValueType().bitsGT(N.getValueType()))
2605 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2606
2607 // If this is a multiply by a power of two, turn it into a shl
2608 // immediately. This is a very common case.
2609 if (ElementSize != 1) {
2610 if (isPowerOf2_64(ElementSize)) {
2611 unsigned Amt = Log2_64(ElementSize);
2612 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2613 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2614 } else {
2615 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2616 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2617 }
2618 }
2619
2620 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2621 }
2622 }
2623 setValue(&I, N);
2624}
2625
2626void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2627 // If this is a fixed sized alloca in the entry block of the function,
2628 // allocate it statically on the stack.
2629 if (FuncInfo.StaticAllocaMap.count(&I))
2630 return; // getValue will auto-populate this.
2631
2632 const Type *Ty = I.getAllocatedType();
2633 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2634 unsigned Align =
2635 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2636 I.getAlignment());
2637
2638 SDValue AllocSize = getValue(I.getArraySize());
2639 MVT IntPtr = TLI.getPointerTy();
2640 if (IntPtr.bitsLT(AllocSize.getValueType()))
2641 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2642 else if (IntPtr.bitsGT(AllocSize.getValueType()))
2643 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2644
2645 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2646 DAG.getIntPtrConstant(TySize));
2647
2648 // Handle alignment. If the requested alignment is less than or equal to
2649 // the stack alignment, ignore it. If the size is greater than or equal to
2650 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2651 unsigned StackAlign =
2652 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2653 if (Align <= StackAlign)
2654 Align = 0;
2655
2656 // Round the size of the allocation up to the stack alignment size
2657 // by add SA-1 to the size.
2658 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2659 DAG.getIntPtrConstant(StackAlign-1));
2660 // Mask out the low bits for alignment purposes.
2661 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2662 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2663
2664 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2665 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2666 MVT::Other);
2667 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2668 setValue(&I, DSA);
2669 DAG.setRoot(DSA.getValue(1));
2670
2671 // Inform the Frame Information that we have just allocated a variable-sized
2672 // object.
2673 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2674}
2675
2676void SelectionDAGLowering::visitLoad(LoadInst &I) {
2677 const Value *SV = I.getOperand(0);
2678 SDValue Ptr = getValue(SV);
2679
2680 const Type *Ty = I.getType();
2681 bool isVolatile = I.isVolatile();
2682 unsigned Alignment = I.getAlignment();
2683
2684 SmallVector<MVT, 4> ValueVTs;
2685 SmallVector<uint64_t, 4> Offsets;
2686 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2687 unsigned NumValues = ValueVTs.size();
2688 if (NumValues == 0)
2689 return;
2690
2691 SDValue Root;
2692 bool ConstantMemory = false;
2693 if (I.isVolatile())
2694 // Serialize volatile loads with other side effects.
2695 Root = getRoot();
2696 else if (AA->pointsToConstantMemory(SV)) {
2697 // Do not serialize (non-volatile) loads of constant memory with anything.
2698 Root = DAG.getEntryNode();
2699 ConstantMemory = true;
2700 } else {
2701 // Do not serialize non-volatile loads against each other.
2702 Root = DAG.getRoot();
2703 }
2704
2705 SmallVector<SDValue, 4> Values(NumValues);
2706 SmallVector<SDValue, 4> Chains(NumValues);
2707 MVT PtrVT = Ptr.getValueType();
2708 for (unsigned i = 0; i != NumValues; ++i) {
2709 SDValue L = DAG.getLoad(ValueVTs[i], Root,
2710 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2711 DAG.getConstant(Offsets[i], PtrVT)),
2712 SV, Offsets[i],
2713 isVolatile, Alignment);
2714 Values[i] = L;
2715 Chains[i] = L.getValue(1);
2716 }
2717
2718 if (!ConstantMemory) {
2719 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2720 &Chains[0], NumValues);
2721 if (isVolatile)
2722 DAG.setRoot(Chain);
2723 else
2724 PendingLoads.push_back(Chain);
2725 }
2726
Duncan Sandsaaffa052008-12-01 11:41:29 +00002727 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2728 DAG.getVTList(&ValueVTs[0], NumValues),
2729 &Values[0], NumValues));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002730}
2731
2732
2733void SelectionDAGLowering::visitStore(StoreInst &I) {
2734 Value *SrcV = I.getOperand(0);
2735 Value *PtrV = I.getOperand(1);
2736
2737 SmallVector<MVT, 4> ValueVTs;
2738 SmallVector<uint64_t, 4> Offsets;
2739 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2740 unsigned NumValues = ValueVTs.size();
2741 if (NumValues == 0)
2742 return;
2743
2744 // Get the lowered operands. Note that we do this after
2745 // checking if NumResults is zero, because with zero results
2746 // the operands won't have values in the map.
2747 SDValue Src = getValue(SrcV);
2748 SDValue Ptr = getValue(PtrV);
2749
2750 SDValue Root = getRoot();
2751 SmallVector<SDValue, 4> Chains(NumValues);
2752 MVT PtrVT = Ptr.getValueType();
2753 bool isVolatile = I.isVolatile();
2754 unsigned Alignment = I.getAlignment();
2755 for (unsigned i = 0; i != NumValues; ++i)
2756 Chains[i] = DAG.getStore(Root, SDValue(Src.getNode(), Src.getResNo() + i),
2757 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2758 DAG.getConstant(Offsets[i], PtrVT)),
2759 PtrV, Offsets[i],
2760 isVolatile, Alignment);
2761
2762 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2763}
2764
2765/// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2766/// node.
2767void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2768 unsigned Intrinsic) {
2769 bool HasChain = !I.doesNotAccessMemory();
2770 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2771
2772 // Build the operand list.
2773 SmallVector<SDValue, 8> Ops;
2774 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2775 if (OnlyLoad) {
2776 // We don't need to serialize loads against other loads.
2777 Ops.push_back(DAG.getRoot());
2778 } else {
2779 Ops.push_back(getRoot());
2780 }
2781 }
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002782
2783 // Info is set by getTgtMemInstrinsic
2784 TargetLowering::IntrinsicInfo Info;
2785 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2786
2787 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
2788 if (!IsTgtIntrinsic)
2789 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002790
2791 // Add all operands of the call to the operand list.
2792 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2793 SDValue Op = getValue(I.getOperand(i));
2794 assert(TLI.isTypeLegal(Op.getValueType()) &&
2795 "Intrinsic uses a non-legal type?");
2796 Ops.push_back(Op);
2797 }
2798
2799 std::vector<MVT> VTs;
2800 if (I.getType() != Type::VoidTy) {
2801 MVT VT = TLI.getValueType(I.getType());
2802 if (VT.isVector()) {
2803 const VectorType *DestTy = cast<VectorType>(I.getType());
2804 MVT EltVT = TLI.getValueType(DestTy->getElementType());
2805
2806 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2807 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2808 }
2809
2810 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2811 VTs.push_back(VT);
2812 }
2813 if (HasChain)
2814 VTs.push_back(MVT::Other);
2815
2816 const MVT *VTList = DAG.getNodeValueTypes(VTs);
2817
2818 // Create the node.
2819 SDValue Result;
Mon P Wang3efcd4a2008-11-01 20:24:53 +00002820 if (IsTgtIntrinsic) {
2821 // This is target intrinsic that touches memory
2822 Result = DAG.getMemIntrinsicNode(Info.opc, VTList, VTs.size(),
2823 &Ops[0], Ops.size(),
2824 Info.memVT, Info.ptrVal, Info.offset,
2825 Info.align, Info.vol,
2826 Info.readMem, Info.writeMem);
2827 }
2828 else if (!HasChain)
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002829 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2830 &Ops[0], Ops.size());
2831 else if (I.getType() != Type::VoidTy)
2832 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2833 &Ops[0], Ops.size());
2834 else
2835 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2836 &Ops[0], Ops.size());
2837
2838 if (HasChain) {
2839 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2840 if (OnlyLoad)
2841 PendingLoads.push_back(Chain);
2842 else
2843 DAG.setRoot(Chain);
2844 }
2845 if (I.getType() != Type::VoidTy) {
2846 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2847 MVT VT = TLI.getValueType(PTy);
2848 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2849 }
2850 setValue(&I, Result);
2851 }
2852}
2853
2854/// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2855static GlobalVariable *ExtractTypeInfo(Value *V) {
2856 V = V->stripPointerCasts();
2857 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2858 assert ((GV || isa<ConstantPointerNull>(V)) &&
2859 "TypeInfo must be a global variable or NULL");
2860 return GV;
2861}
2862
2863namespace llvm {
2864
2865/// AddCatchInfo - Extract the personality and type infos from an eh.selector
2866/// call, and add them to the specified machine basic block.
2867void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2868 MachineBasicBlock *MBB) {
2869 // Inform the MachineModuleInfo of the personality for this landing pad.
2870 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2871 assert(CE->getOpcode() == Instruction::BitCast &&
2872 isa<Function>(CE->getOperand(0)) &&
2873 "Personality should be a function");
2874 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2875
2876 // Gather all the type infos for this landing pad and pass them along to
2877 // MachineModuleInfo.
2878 std::vector<GlobalVariable *> TyInfo;
2879 unsigned N = I.getNumOperands();
2880
2881 for (unsigned i = N - 1; i > 2; --i) {
2882 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2883 unsigned FilterLength = CI->getZExtValue();
2884 unsigned FirstCatch = i + FilterLength + !FilterLength;
2885 assert (FirstCatch <= N && "Invalid filter length");
2886
2887 if (FirstCatch < N) {
2888 TyInfo.reserve(N - FirstCatch);
2889 for (unsigned j = FirstCatch; j < N; ++j)
2890 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2891 MMI->addCatchTypeInfo(MBB, TyInfo);
2892 TyInfo.clear();
2893 }
2894
2895 if (!FilterLength) {
2896 // Cleanup.
2897 MMI->addCleanup(MBB);
2898 } else {
2899 // Filter.
2900 TyInfo.reserve(FilterLength - 1);
2901 for (unsigned j = i + 1; j < FirstCatch; ++j)
2902 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2903 MMI->addFilterTypeInfo(MBB, TyInfo);
2904 TyInfo.clear();
2905 }
2906
2907 N = i;
2908 }
2909 }
2910
2911 if (N > 3) {
2912 TyInfo.reserve(N - 3);
2913 for (unsigned j = 3; j < N; ++j)
2914 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2915 MMI->addCatchTypeInfo(MBB, TyInfo);
2916 }
2917}
2918
2919}
2920
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002921/// GetSignificand - Get the significand and build it into a floating-point
2922/// number with exponent of 1:
2923///
2924/// Op = (Op & 0x007fffff) | 0x3f800000;
2925///
2926/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002927static SDValue
2928GetSignificand(SelectionDAG &DAG, SDValue Op) {
2929 SDValue t1 = DAG.getNode(ISD::AND, MVT::i32, Op,
2930 DAG.getConstant(0x007fffff, MVT::i32));
2931 SDValue t2 = DAG.getNode(ISD::OR, MVT::i32, t1,
2932 DAG.getConstant(0x3f800000, MVT::i32));
2933 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t2);
2934}
2935
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002936/// GetExponent - Get the exponent:
2937///
2938/// (float)((Op1 >> 23) - 127);
2939///
2940/// where Op is the hexidecimal representation of floating point value.
Bill Wendling39150252008-09-09 20:39:27 +00002941static SDValue
2942GetExponent(SelectionDAG &DAG, SDValue Op) {
Bill Wendlingfc2508e2008-09-10 06:26:10 +00002943 SDValue t1 = DAG.getNode(ISD::SRL, MVT::i32, Op,
Bill Wendling39150252008-09-09 20:39:27 +00002944 DAG.getConstant(23, MVT::i32));
Bill Wendlingfc2508e2008-09-10 06:26:10 +00002945 SDValue t2 = DAG.getNode(ISD::SUB, MVT::i32, t1,
Bill Wendling39150252008-09-09 20:39:27 +00002946 DAG.getConstant(127, MVT::i32));
Bill Wendlingfc2508e2008-09-10 06:26:10 +00002947 return DAG.getNode(ISD::UINT_TO_FP, MVT::f32, t2);
Bill Wendling39150252008-09-09 20:39:27 +00002948}
2949
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00002950/// getF32Constant - Get 32-bit floating point constant.
2951static SDValue
2952getF32Constant(SelectionDAG &DAG, unsigned Flt) {
2953 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
2954}
2955
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002956/// Inlined utility function to implement binary input atomic intrinsics for
2957/// visitIntrinsicCall: I is a call instruction
2958/// Op is the associated NodeType for I
2959const char *
2960SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2961 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00002962 SDValue L =
2963 DAG.getAtomic(Op, getValue(I.getOperand(2)).getValueType().getSimpleVT(),
2964 Root,
2965 getValue(I.getOperand(1)),
2966 getValue(I.getOperand(2)),
2967 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00002968 setValue(&I, L);
2969 DAG.setRoot(L.getValue(1));
2970 return 0;
2971}
2972
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002973// implVisitAluOverflow - Lower arithmetic overflow instrinsics.
Bill Wendling74c37652008-12-09 22:08:41 +00002974const char *
2975SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002976 SDValue Op1 = getValue(I.getOperand(1));
2977 SDValue Op2 = getValue(I.getOperand(2));
Bill Wendling74c37652008-12-09 22:08:41 +00002978
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002979 MVT ValueVTs[] = { Op1.getValueType(), MVT::i1 };
2980 SDValue Ops[] = { Op1, Op2 };
Bill Wendling74c37652008-12-09 22:08:41 +00002981
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002982 SDValue Result = DAG.getNode(Op, DAG.getVTList(&ValueVTs[0], 2), &Ops[0], 2);
Bill Wendling74c37652008-12-09 22:08:41 +00002983
Bill Wendling2ce4e5c2008-12-10 00:28:22 +00002984 setValue(&I, Result);
2985 return 0;
2986}
Bill Wendling74c37652008-12-09 22:08:41 +00002987
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002988/// visitExp - Lower an exp intrinsic. Handles the special sequences for
2989/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00002990void
2991SelectionDAGLowering::visitExp(CallInst &I) {
2992 SDValue result;
Bill Wendlingb4ec2832008-09-09 22:13:54 +00002993
2994 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2995 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2996 SDValue Op = getValue(I.getOperand(1));
2997
2998 // Put the exponent in the right bit position for later addition to the
2999 // final result:
3000 //
3001 // #define LOG2OFe 1.4426950f
3002 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3003 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003004 getF32Constant(DAG, 0x3fb8aa3b));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003005 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3006
3007 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3008 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3009 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3010
3011 // IntegerPartOfX <<= 23;
3012 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3013 DAG.getConstant(23, MVT::i32));
3014
3015 if (LimitFloatPrecision <= 6) {
3016 // For floating-point precision of 6:
3017 //
3018 // TwoToFractionalPartOfX =
3019 // 0.997535578f +
3020 // (0.735607626f + 0.252464424f * x) * x;
3021 //
3022 // error 0.0144103317, which is 6 bits
3023 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003024 getF32Constant(DAG, 0x3e814304));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003025 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003026 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003027 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3028 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003029 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003030 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3031
3032 // Add the exponent into the result in integer domain.
3033 SDValue t6 = DAG.getNode(ISD::ADD, MVT::i32,
3034 TwoToFracPartOfX, IntegerPartOfX);
3035
3036 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t6);
3037 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3038 // For floating-point precision of 12:
3039 //
3040 // TwoToFractionalPartOfX =
3041 // 0.999892986f +
3042 // (0.696457318f +
3043 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3044 //
3045 // 0.000107046256 error, which is 13 to 14 bits
3046 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003047 getF32Constant(DAG, 0x3da235e3));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003048 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003049 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003050 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3051 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003052 getF32Constant(DAG, 0x3f324b07));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003053 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3054 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003055 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003056 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3057
3058 // Add the exponent into the result in integer domain.
3059 SDValue t8 = DAG.getNode(ISD::ADD, MVT::i32,
3060 TwoToFracPartOfX, IntegerPartOfX);
3061
3062 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t8);
3063 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3064 // For floating-point precision of 18:
3065 //
3066 // TwoToFractionalPartOfX =
3067 // 0.999999982f +
3068 // (0.693148872f +
3069 // (0.240227044f +
3070 // (0.554906021e-1f +
3071 // (0.961591928e-2f +
3072 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3073 //
3074 // error 2.47208000*10^(-7), which is better than 18 bits
3075 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003076 getF32Constant(DAG, 0x3924b03e));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003077 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003078 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003079 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3080 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003081 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003082 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3083 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003084 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003085 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3086 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003087 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003088 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3089 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003090 getF32Constant(DAG, 0x3f317234));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003091 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3092 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003093 getF32Constant(DAG, 0x3f800000));
Bill Wendlingb4ec2832008-09-09 22:13:54 +00003094 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3095
3096 // Add the exponent into the result in integer domain.
3097 SDValue t14 = DAG.getNode(ISD::ADD, MVT::i32,
3098 TwoToFracPartOfX, IntegerPartOfX);
3099
3100 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t14);
3101 }
3102 } else {
3103 // No special expansion.
3104 result = DAG.getNode(ISD::FEXP,
3105 getValue(I.getOperand(1)).getValueType(),
3106 getValue(I.getOperand(1)));
3107 }
3108
Dale Johannesen59e577f2008-09-05 18:38:42 +00003109 setValue(&I, result);
3110}
3111
Bill Wendling39150252008-09-09 20:39:27 +00003112/// visitLog - Lower a log intrinsic. Handles the special sequences for
3113/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003114void
3115SelectionDAGLowering::visitLog(CallInst &I) {
3116 SDValue result;
Bill Wendling39150252008-09-09 20:39:27 +00003117
3118 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3119 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3120 SDValue Op = getValue(I.getOperand(1));
3121 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3122
3123 // Scale the exponent by log(2) [0.69314718f].
3124 SDValue Exp = GetExponent(DAG, Op1);
3125 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003126 getF32Constant(DAG, 0x3f317218));
Bill Wendling39150252008-09-09 20:39:27 +00003127
3128 // Get the significand and build it into a floating-point number with
3129 // exponent of 1.
3130 SDValue X = GetSignificand(DAG, Op1);
3131
3132 if (LimitFloatPrecision <= 6) {
3133 // For floating-point precision of 6:
3134 //
3135 // LogofMantissa =
3136 // -1.1609546f +
3137 // (1.4034025f - 0.23903021f * x) * x;
3138 //
3139 // error 0.0034276066, which is better than 8 bits
3140 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003141 getF32Constant(DAG, 0xbe74c456));
Bill Wendling39150252008-09-09 20:39:27 +00003142 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003143 getF32Constant(DAG, 0x3fb3a2b1));
Bill Wendling39150252008-09-09 20:39:27 +00003144 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3145 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003146 getF32Constant(DAG, 0x3f949a29));
Bill Wendling39150252008-09-09 20:39:27 +00003147
3148 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3149 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3150 // For floating-point precision of 12:
3151 //
3152 // LogOfMantissa =
3153 // -1.7417939f +
3154 // (2.8212026f +
3155 // (-1.4699568f +
3156 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3157 //
3158 // error 0.000061011436, which is 14 bits
3159 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003160 getF32Constant(DAG, 0xbd67b6d6));
Bill Wendling39150252008-09-09 20:39:27 +00003161 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003162 getF32Constant(DAG, 0x3ee4f4b8));
Bill Wendling39150252008-09-09 20:39:27 +00003163 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3164 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003165 getF32Constant(DAG, 0x3fbc278b));
Bill Wendling39150252008-09-09 20:39:27 +00003166 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3167 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003168 getF32Constant(DAG, 0x40348e95));
Bill Wendling39150252008-09-09 20:39:27 +00003169 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3170 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003171 getF32Constant(DAG, 0x3fdef31a));
Bill Wendling39150252008-09-09 20:39:27 +00003172
3173 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3174 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3175 // For floating-point precision of 18:
3176 //
3177 // LogOfMantissa =
3178 // -2.1072184f +
3179 // (4.2372794f +
3180 // (-3.7029485f +
3181 // (2.2781945f +
3182 // (-0.87823314f +
3183 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3184 //
3185 // error 0.0000023660568, which is better than 18 bits
3186 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003187 getF32Constant(DAG, 0xbc91e5ac));
Bill Wendling39150252008-09-09 20:39:27 +00003188 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003189 getF32Constant(DAG, 0x3e4350aa));
Bill Wendling39150252008-09-09 20:39:27 +00003190 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3191 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003192 getF32Constant(DAG, 0x3f60d3e3));
Bill Wendling39150252008-09-09 20:39:27 +00003193 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3194 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003195 getF32Constant(DAG, 0x4011cdf0));
Bill Wendling39150252008-09-09 20:39:27 +00003196 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3197 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003198 getF32Constant(DAG, 0x406cfd1c));
Bill Wendling39150252008-09-09 20:39:27 +00003199 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3200 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003201 getF32Constant(DAG, 0x408797cb));
Bill Wendling39150252008-09-09 20:39:27 +00003202 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3203 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003204 getF32Constant(DAG, 0x4006dcab));
Bill Wendling39150252008-09-09 20:39:27 +00003205
3206 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3207 }
3208 } else {
3209 // No special expansion.
3210 result = DAG.getNode(ISD::FLOG,
3211 getValue(I.getOperand(1)).getValueType(),
3212 getValue(I.getOperand(1)));
3213 }
3214
Dale Johannesen59e577f2008-09-05 18:38:42 +00003215 setValue(&I, result);
3216}
3217
Bill Wendling3eb59402008-09-09 00:28:24 +00003218/// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3219/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003220void
3221SelectionDAGLowering::visitLog2(CallInst &I) {
3222 SDValue result;
Bill Wendling3eb59402008-09-09 00:28:24 +00003223
Dale Johannesen853244f2008-09-05 23:49:37 +00003224 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003225 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3226 SDValue Op = getValue(I.getOperand(1));
3227 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3228
Bill Wendling39150252008-09-09 20:39:27 +00003229 // Get the exponent.
3230 SDValue LogOfExponent = GetExponent(DAG, Op1);
Bill Wendling3eb59402008-09-09 00:28:24 +00003231
3232 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003233 // exponent of 1.
3234 SDValue X = GetSignificand(DAG, Op1);
Bill Wendling3eb59402008-09-09 00:28:24 +00003235
3236 // Different possible minimax approximations of significand in
3237 // floating-point for various degrees of accuracy over [1,2].
3238 if (LimitFloatPrecision <= 6) {
3239 // For floating-point precision of 6:
3240 //
3241 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3242 //
3243 // error 0.0049451742, which is more than 7 bits
Bill Wendling39150252008-09-09 20:39:27 +00003244 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003245 getF32Constant(DAG, 0xbeb08fe0));
Bill Wendling39150252008-09-09 20:39:27 +00003246 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003247 getF32Constant(DAG, 0x40019463));
Bill Wendling39150252008-09-09 20:39:27 +00003248 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3249 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003250 getF32Constant(DAG, 0x3fd6633d));
Bill Wendling3eb59402008-09-09 00:28:24 +00003251
3252 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3253 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3254 // For floating-point precision of 12:
3255 //
3256 // Log2ofMantissa =
3257 // -2.51285454f +
3258 // (4.07009056f +
3259 // (-2.12067489f +
3260 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3261 //
3262 // error 0.0000876136000, which is better than 13 bits
Bill Wendling39150252008-09-09 20:39:27 +00003263 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003264 getF32Constant(DAG, 0xbda7262e));
Bill Wendling39150252008-09-09 20:39:27 +00003265 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003266 getF32Constant(DAG, 0x3f25280b));
Bill Wendling39150252008-09-09 20:39:27 +00003267 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3268 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003269 getF32Constant(DAG, 0x4007b923));
Bill Wendling39150252008-09-09 20:39:27 +00003270 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3271 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003272 getF32Constant(DAG, 0x40823e2f));
Bill Wendling39150252008-09-09 20:39:27 +00003273 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3274 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003275 getF32Constant(DAG, 0x4020d29c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003276
3277 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3278 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3279 // For floating-point precision of 18:
3280 //
3281 // Log2ofMantissa =
3282 // -3.0400495f +
3283 // (6.1129976f +
3284 // (-5.3420409f +
3285 // (3.2865683f +
3286 // (-1.2669343f +
3287 // (0.27515199f -
3288 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3289 //
3290 // error 0.0000018516, which is better than 18 bits
Bill Wendling39150252008-09-09 20:39:27 +00003291 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003292 getF32Constant(DAG, 0xbcd2769e));
Bill Wendling39150252008-09-09 20:39:27 +00003293 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003294 getF32Constant(DAG, 0x3e8ce0b9));
Bill Wendling39150252008-09-09 20:39:27 +00003295 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3296 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003297 getF32Constant(DAG, 0x3fa22ae7));
Bill Wendling39150252008-09-09 20:39:27 +00003298 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3299 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003300 getF32Constant(DAG, 0x40525723));
Bill Wendling39150252008-09-09 20:39:27 +00003301 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3302 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003303 getF32Constant(DAG, 0x40aaf200));
Bill Wendling39150252008-09-09 20:39:27 +00003304 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3305 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003306 getF32Constant(DAG, 0x40c39dad));
Bill Wendling3eb59402008-09-09 00:28:24 +00003307 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
Bill Wendling39150252008-09-09 20:39:27 +00003308 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003309 getF32Constant(DAG, 0x4042902c));
Bill Wendling3eb59402008-09-09 00:28:24 +00003310
3311 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3312 }
Dale Johannesen853244f2008-09-05 23:49:37 +00003313 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003314 // No special expansion.
Dale Johannesen853244f2008-09-05 23:49:37 +00003315 result = DAG.getNode(ISD::FLOG2,
3316 getValue(I.getOperand(1)).getValueType(),
3317 getValue(I.getOperand(1)));
3318 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003319
Dale Johannesen59e577f2008-09-05 18:38:42 +00003320 setValue(&I, result);
3321}
3322
Bill Wendling3eb59402008-09-09 00:28:24 +00003323/// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3324/// limited-precision mode.
Dale Johannesen59e577f2008-09-05 18:38:42 +00003325void
3326SelectionDAGLowering::visitLog10(CallInst &I) {
3327 SDValue result;
Bill Wendling181b6272008-10-19 20:34:04 +00003328
Dale Johannesen852680a2008-09-05 21:27:19 +00003329 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendling3eb59402008-09-09 00:28:24 +00003330 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3331 SDValue Op = getValue(I.getOperand(1));
3332 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3333
Bill Wendling39150252008-09-09 20:39:27 +00003334 // Scale the exponent by log10(2) [0.30102999f].
3335 SDValue Exp = GetExponent(DAG, Op1);
3336 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003337 getF32Constant(DAG, 0x3e9a209a));
Bill Wendling3eb59402008-09-09 00:28:24 +00003338
3339 // Get the significand and build it into a floating-point number with
Bill Wendling39150252008-09-09 20:39:27 +00003340 // exponent of 1.
3341 SDValue X = GetSignificand(DAG, Op1);
Bill Wendling3eb59402008-09-09 00:28:24 +00003342
3343 if (LimitFloatPrecision <= 6) {
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003344 // For floating-point precision of 6:
3345 //
3346 // Log10ofMantissa =
3347 // -0.50419619f +
3348 // (0.60948995f - 0.10380950f * x) * x;
3349 //
3350 // error 0.0014886165, which is 6 bits
Bill Wendling39150252008-09-09 20:39:27 +00003351 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003352 getF32Constant(DAG, 0xbdd49a13));
Bill Wendling39150252008-09-09 20:39:27 +00003353 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003354 getF32Constant(DAG, 0x3f1c0789));
Bill Wendling39150252008-09-09 20:39:27 +00003355 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3356 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003357 getF32Constant(DAG, 0x3f011300));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003358
3359 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003360 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3361 // For floating-point precision of 12:
3362 //
3363 // Log10ofMantissa =
3364 // -0.64831180f +
3365 // (0.91751397f +
3366 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3367 //
3368 // error 0.00019228036, which is better than 12 bits
Bill Wendling39150252008-09-09 20:39:27 +00003369 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003370 getF32Constant(DAG, 0x3d431f31));
Bill Wendling39150252008-09-09 20:39:27 +00003371 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003372 getF32Constant(DAG, 0x3ea21fb2));
Bill Wendling39150252008-09-09 20:39:27 +00003373 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3374 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003375 getF32Constant(DAG, 0x3f6ae232));
Bill Wendling39150252008-09-09 20:39:27 +00003376 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3377 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003378 getF32Constant(DAG, 0x3f25f7c3));
Bill Wendling3eb59402008-09-09 00:28:24 +00003379
3380 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3381 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003382 // For floating-point precision of 18:
3383 //
3384 // Log10ofMantissa =
3385 // -0.84299375f +
3386 // (1.5327582f +
3387 // (-1.0688956f +
3388 // (0.49102474f +
3389 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3390 //
3391 // error 0.0000037995730, which is better than 18 bits
Bill Wendling39150252008-09-09 20:39:27 +00003392 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003393 getF32Constant(DAG, 0x3c5d51ce));
Bill Wendling39150252008-09-09 20:39:27 +00003394 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003395 getF32Constant(DAG, 0x3e00685a));
Bill Wendling39150252008-09-09 20:39:27 +00003396 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3397 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003398 getF32Constant(DAG, 0x3efb6798));
Bill Wendling39150252008-09-09 20:39:27 +00003399 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3400 SDValue t5 = DAG.getNode(ISD::FSUB, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003401 getF32Constant(DAG, 0x3f88d192));
Bill Wendling39150252008-09-09 20:39:27 +00003402 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3403 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003404 getF32Constant(DAG, 0x3fc4316c));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003405 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
Bill Wendling39150252008-09-09 20:39:27 +00003406 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003407 getF32Constant(DAG, 0x3f57ce70));
Bill Wendlingbd297bc2008-09-09 18:42:23 +00003408
3409 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
Bill Wendling3eb59402008-09-09 00:28:24 +00003410 }
Dale Johannesen852680a2008-09-05 21:27:19 +00003411 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003412 // No special expansion.
Dale Johannesen852680a2008-09-05 21:27:19 +00003413 result = DAG.getNode(ISD::FLOG10,
3414 getValue(I.getOperand(1)).getValueType(),
3415 getValue(I.getOperand(1)));
3416 }
Bill Wendling3eb59402008-09-09 00:28:24 +00003417
Dale Johannesen59e577f2008-09-05 18:38:42 +00003418 setValue(&I, result);
3419}
3420
Bill Wendlinge10c8142008-09-09 22:39:21 +00003421/// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3422/// limited-precision mode.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003423void
3424SelectionDAGLowering::visitExp2(CallInst &I) {
3425 SDValue result;
Bill Wendlinge10c8142008-09-09 22:39:21 +00003426
Dale Johannesen601d3c02008-09-05 01:48:15 +00003427 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
Bill Wendlinge10c8142008-09-09 22:39:21 +00003428 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3429 SDValue Op = getValue(I.getOperand(1));
3430
3431 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, Op);
3432
3433 // FractionalPartOfX = x - (float)IntegerPartOfX;
3434 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3435 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, Op, t1);
3436
3437 // IntegerPartOfX <<= 23;
3438 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3439 DAG.getConstant(23, MVT::i32));
3440
3441 if (LimitFloatPrecision <= 6) {
3442 // For floating-point precision of 6:
3443 //
3444 // TwoToFractionalPartOfX =
3445 // 0.997535578f +
3446 // (0.735607626f + 0.252464424f * x) * x;
3447 //
3448 // error 0.0144103317, which is 6 bits
3449 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003450 getF32Constant(DAG, 0x3e814304));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003451 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003452 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003453 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3454 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003455 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003456 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3457 SDValue TwoToFractionalPartOfX =
3458 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3459
3460 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3461 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3462 // For floating-point precision of 12:
3463 //
3464 // TwoToFractionalPartOfX =
3465 // 0.999892986f +
3466 // (0.696457318f +
3467 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3468 //
3469 // error 0.000107046256, which is 13 to 14 bits
3470 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003471 getF32Constant(DAG, 0x3da235e3));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003472 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003473 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003474 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3475 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003476 getF32Constant(DAG, 0x3f324b07));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003477 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3478 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003479 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003480 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3481 SDValue TwoToFractionalPartOfX =
3482 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3483
3484 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3485 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3486 // For floating-point precision of 18:
3487 //
3488 // TwoToFractionalPartOfX =
3489 // 0.999999982f +
3490 // (0.693148872f +
3491 // (0.240227044f +
3492 // (0.554906021e-1f +
3493 // (0.961591928e-2f +
3494 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3495 // error 2.47208000*10^(-7), which is better than 18 bits
3496 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003497 getF32Constant(DAG, 0x3924b03e));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003498 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003499 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003500 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3501 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003502 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003503 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3504 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003505 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003506 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3507 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003508 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003509 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3510 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003511 getF32Constant(DAG, 0x3f317234));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003512 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3513 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003514 getF32Constant(DAG, 0x3f800000));
Bill Wendlinge10c8142008-09-09 22:39:21 +00003515 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3516 SDValue TwoToFractionalPartOfX =
3517 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3518
3519 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3520 }
Dale Johannesen601d3c02008-09-05 01:48:15 +00003521 } else {
Bill Wendling3eb59402008-09-09 00:28:24 +00003522 // No special expansion.
Dale Johannesen601d3c02008-09-05 01:48:15 +00003523 result = DAG.getNode(ISD::FEXP2,
3524 getValue(I.getOperand(1)).getValueType(),
3525 getValue(I.getOperand(1)));
3526 }
Bill Wendlinge10c8142008-09-09 22:39:21 +00003527
Dale Johannesen601d3c02008-09-05 01:48:15 +00003528 setValue(&I, result);
3529}
3530
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003531/// visitPow - Lower a pow intrinsic. Handles the special sequences for
3532/// limited-precision mode with x == 10.0f.
3533void
3534SelectionDAGLowering::visitPow(CallInst &I) {
3535 SDValue result;
3536 Value *Val = I.getOperand(1);
3537 bool IsExp10 = false;
3538
3539 if (getValue(Val).getValueType() == MVT::f32 &&
Bill Wendling277fc242008-09-10 00:24:59 +00003540 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003541 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3542 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3543 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3544 APFloat Ten(10.0f);
3545 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3546 }
3547 }
3548 }
3549
3550 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3551 SDValue Op = getValue(I.getOperand(2));
3552
3553 // Put the exponent in the right bit position for later addition to the
3554 // final result:
3555 //
3556 // #define LOG2OF10 3.3219281f
3557 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3558 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003559 getF32Constant(DAG, 0x40549a78));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003560 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3561
3562 // FractionalPartOfX = x - (float)IntegerPartOfX;
3563 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3564 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3565
3566 // IntegerPartOfX <<= 23;
3567 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3568 DAG.getConstant(23, MVT::i32));
3569
3570 if (LimitFloatPrecision <= 6) {
3571 // For floating-point precision of 6:
3572 //
3573 // twoToFractionalPartOfX =
3574 // 0.997535578f +
3575 // (0.735607626f + 0.252464424f * x) * x;
3576 //
3577 // error 0.0144103317, which is 6 bits
3578 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003579 getF32Constant(DAG, 0x3e814304));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003580 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003581 getF32Constant(DAG, 0x3f3c50c8));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003582 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3583 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003584 getF32Constant(DAG, 0x3f7f5e7e));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003585 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3586 SDValue TwoToFractionalPartOfX =
3587 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3588
3589 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3590 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3591 // For floating-point precision of 12:
3592 //
3593 // TwoToFractionalPartOfX =
3594 // 0.999892986f +
3595 // (0.696457318f +
3596 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3597 //
3598 // error 0.000107046256, which is 13 to 14 bits
3599 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003600 getF32Constant(DAG, 0x3da235e3));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003601 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003602 getF32Constant(DAG, 0x3e65b8f3));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003603 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3604 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003605 getF32Constant(DAG, 0x3f324b07));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003606 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3607 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003608 getF32Constant(DAG, 0x3f7ff8fd));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003609 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3610 SDValue TwoToFractionalPartOfX =
3611 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3612
3613 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3614 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3615 // For floating-point precision of 18:
3616 //
3617 // TwoToFractionalPartOfX =
3618 // 0.999999982f +
3619 // (0.693148872f +
3620 // (0.240227044f +
3621 // (0.554906021e-1f +
3622 // (0.961591928e-2f +
3623 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3624 // error 2.47208000*10^(-7), which is better than 18 bits
3625 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003626 getF32Constant(DAG, 0x3924b03e));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003627 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003628 getF32Constant(DAG, 0x3ab24b87));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003629 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3630 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003631 getF32Constant(DAG, 0x3c1d8c17));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003632 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3633 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003634 getF32Constant(DAG, 0x3d634a1d));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003635 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3636 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003637 getF32Constant(DAG, 0x3e75fe14));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003638 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3639 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003640 getF32Constant(DAG, 0x3f317234));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003641 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3642 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
Bill Wendlingcd4c73a2008-09-22 00:44:35 +00003643 getF32Constant(DAG, 0x3f800000));
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003644 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3645 SDValue TwoToFractionalPartOfX =
3646 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3647
3648 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3649 }
3650 } else {
3651 // No special expansion.
3652 result = DAG.getNode(ISD::FPOW,
3653 getValue(I.getOperand(1)).getValueType(),
3654 getValue(I.getOperand(1)),
3655 getValue(I.getOperand(2)));
3656 }
3657
3658 setValue(&I, result);
3659}
3660
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003661/// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3662/// we want to emit this as a call to a named external function, return the name
3663/// otherwise lower it and return null.
3664const char *
3665SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3666 switch (Intrinsic) {
3667 default:
3668 // By default, turn this into a target intrinsic node.
3669 visitTargetIntrinsic(I, Intrinsic);
3670 return 0;
3671 case Intrinsic::vastart: visitVAStart(I); return 0;
3672 case Intrinsic::vaend: visitVAEnd(I); return 0;
3673 case Intrinsic::vacopy: visitVACopy(I); return 0;
3674 case Intrinsic::returnaddress:
3675 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3676 getValue(I.getOperand(1))));
3677 return 0;
Bill Wendlingd5d81912008-09-26 22:10:44 +00003678 case Intrinsic::frameaddress:
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003679 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3680 getValue(I.getOperand(1))));
3681 return 0;
3682 case Intrinsic::setjmp:
3683 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3684 break;
3685 case Intrinsic::longjmp:
3686 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3687 break;
Chris Lattner824b9582008-11-21 16:42:48 +00003688 case Intrinsic::memcpy: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003689 SDValue Op1 = getValue(I.getOperand(1));
3690 SDValue Op2 = getValue(I.getOperand(2));
3691 SDValue Op3 = getValue(I.getOperand(3));
3692 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3693 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3694 I.getOperand(1), 0, I.getOperand(2), 0));
3695 return 0;
3696 }
Chris Lattner824b9582008-11-21 16:42:48 +00003697 case Intrinsic::memset: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003698 SDValue Op1 = getValue(I.getOperand(1));
3699 SDValue Op2 = getValue(I.getOperand(2));
3700 SDValue Op3 = getValue(I.getOperand(3));
3701 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3702 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3703 I.getOperand(1), 0));
3704 return 0;
3705 }
Chris Lattner824b9582008-11-21 16:42:48 +00003706 case Intrinsic::memmove: {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003707 SDValue Op1 = getValue(I.getOperand(1));
3708 SDValue Op2 = getValue(I.getOperand(2));
3709 SDValue Op3 = getValue(I.getOperand(3));
3710 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3711
3712 // If the source and destination are known to not be aliases, we can
3713 // lower memmove as memcpy.
3714 uint64_t Size = -1ULL;
3715 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00003716 Size = C->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003717 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3718 AliasAnalysis::NoAlias) {
3719 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3720 I.getOperand(1), 0, I.getOperand(2), 0));
3721 return 0;
3722 }
3723
3724 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3725 I.getOperand(1), 0, I.getOperand(2), 0));
3726 return 0;
3727 }
3728 case Intrinsic::dbg_stoppoint: {
3729 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3730 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3731 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
3732 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
3733 assert(DD && "Not a debug information descriptor");
3734 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3735 SPI.getLine(),
3736 SPI.getColumn(),
3737 cast<CompileUnitDesc>(DD)));
3738 }
3739
3740 return 0;
3741 }
3742 case Intrinsic::dbg_region_start: {
3743 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3744 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3745 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3746 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
3747 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3748 }
3749
3750 return 0;
3751 }
3752 case Intrinsic::dbg_region_end: {
3753 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3754 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3755 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3756 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
3757 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3758 }
3759
3760 return 0;
3761 }
3762 case Intrinsic::dbg_func_start: {
3763 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3764 if (!MMI) return 0;
3765 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3766 Value *SP = FSI.getSubprogram();
3767 if (SP && MMI->Verify(SP)) {
3768 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3769 // what (most?) gdb expects.
3770 DebugInfoDesc *DD = MMI->getDescFor(SP);
3771 assert(DD && "Not a debug information descriptor");
3772 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3773 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
3774 unsigned SrcFile = MMI->RecordSource(CompileUnit);
Devang Patel20dd0462008-11-06 00:30:09 +00003775 // Record the source line but does not create a label for the normal
3776 // function start. It will be emitted at asm emission time. However,
3777 // create a label if this is a beginning of inlined function.
3778 unsigned LabelID = MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
3779 if (MMI->getSourceLines().size() != 1)
3780 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003781 }
3782
3783 return 0;
3784 }
3785 case Intrinsic::dbg_declare: {
3786 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3787 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3788 Value *Variable = DI.getVariable();
3789 if (MMI && Variable && MMI->Verify(Variable))
3790 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3791 getValue(DI.getAddress()), getValue(Variable)));
3792 return 0;
3793 }
3794
3795 case Intrinsic::eh_exception: {
3796 if (!CurMBB->isLandingPad()) {
3797 // FIXME: Mark exception register as live in. Hack for PR1508.
3798 unsigned Reg = TLI.getExceptionAddressRegister();
3799 if (Reg) CurMBB->addLiveIn(Reg);
3800 }
3801 // Insert the EXCEPTIONADDR instruction.
3802 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3803 SDValue Ops[1];
3804 Ops[0] = DAG.getRoot();
3805 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3806 setValue(&I, Op);
3807 DAG.setRoot(Op.getValue(1));
3808 return 0;
3809 }
3810
3811 case Intrinsic::eh_selector_i32:
3812 case Intrinsic::eh_selector_i64: {
3813 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3814 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3815 MVT::i32 : MVT::i64);
3816
3817 if (MMI) {
3818 if (CurMBB->isLandingPad())
3819 AddCatchInfo(I, MMI, CurMBB);
3820 else {
3821#ifndef NDEBUG
3822 FuncInfo.CatchInfoLost.insert(&I);
3823#endif
3824 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3825 unsigned Reg = TLI.getExceptionSelectorRegister();
3826 if (Reg) CurMBB->addLiveIn(Reg);
3827 }
3828
3829 // Insert the EHSELECTION instruction.
3830 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3831 SDValue Ops[2];
3832 Ops[0] = getValue(I.getOperand(1));
3833 Ops[1] = getRoot();
3834 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3835 setValue(&I, Op);
3836 DAG.setRoot(Op.getValue(1));
3837 } else {
3838 setValue(&I, DAG.getConstant(0, VT));
3839 }
3840
3841 return 0;
3842 }
3843
3844 case Intrinsic::eh_typeid_for_i32:
3845 case Intrinsic::eh_typeid_for_i64: {
3846 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3847 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3848 MVT::i32 : MVT::i64);
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003849
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003850 if (MMI) {
3851 // Find the type id for the given typeinfo.
3852 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3853
3854 unsigned TypeID = MMI->getTypeIDFor(GV);
3855 setValue(&I, DAG.getConstant(TypeID, VT));
3856 } else {
3857 // Return something different to eh_selector.
3858 setValue(&I, DAG.getConstant(1, VT));
3859 }
3860
3861 return 0;
3862 }
3863
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003864 case Intrinsic::eh_return_i32:
3865 case Intrinsic::eh_return_i64:
3866 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003867 MMI->setCallsEHReturn(true);
3868 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3869 MVT::Other,
3870 getControlRoot(),
3871 getValue(I.getOperand(1)),
3872 getValue(I.getOperand(2))));
3873 } else {
3874 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3875 }
3876
3877 return 0;
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003878 case Intrinsic::eh_unwind_init:
3879 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3880 MMI->setCallsUnwindInit(true);
3881 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003882
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003883 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003884
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003885 case Intrinsic::eh_dwarf_cfa: {
3886 MVT VT = getValue(I.getOperand(1)).getValueType();
3887 SDValue CfaArg;
3888 if (VT.bitsGT(TLI.getPointerTy()))
3889 CfaArg = DAG.getNode(ISD::TRUNCATE,
3890 TLI.getPointerTy(), getValue(I.getOperand(1)));
3891 else
3892 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3893 TLI.getPointerTy(), getValue(I.getOperand(1)));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003894
Anton Korobeynikova0e8a1e2008-09-08 21:13:56 +00003895 SDValue Offset = DAG.getNode(ISD::ADD,
3896 TLI.getPointerTy(),
3897 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3898 TLI.getPointerTy()),
3899 CfaArg);
3900 setValue(&I, DAG.getNode(ISD::ADD,
3901 TLI.getPointerTy(),
3902 DAG.getNode(ISD::FRAMEADDR,
3903 TLI.getPointerTy(),
3904 DAG.getConstant(0,
3905 TLI.getPointerTy())),
3906 Offset));
3907 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003908 }
3909
Mon P Wang77cdf302008-11-10 20:54:11 +00003910 case Intrinsic::convertff:
3911 case Intrinsic::convertfsi:
3912 case Intrinsic::convertfui:
3913 case Intrinsic::convertsif:
3914 case Intrinsic::convertuif:
3915 case Intrinsic::convertss:
3916 case Intrinsic::convertsu:
3917 case Intrinsic::convertus:
3918 case Intrinsic::convertuu: {
3919 ISD::CvtCode Code = ISD::CVT_INVALID;
3920 switch (Intrinsic) {
3921 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
3922 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
3923 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
3924 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
3925 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
3926 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
3927 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
3928 case Intrinsic::convertus: Code = ISD::CVT_US; break;
3929 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
3930 }
3931 MVT DestVT = TLI.getValueType(I.getType());
3932 Value* Op1 = I.getOperand(1);
3933 setValue(&I, DAG.getConvertRndSat(DestVT, getValue(Op1),
3934 DAG.getValueType(DestVT),
3935 DAG.getValueType(getValue(Op1).getValueType()),
3936 getValue(I.getOperand(2)),
3937 getValue(I.getOperand(3)),
3938 Code));
3939 return 0;
3940 }
3941
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003942 case Intrinsic::sqrt:
3943 setValue(&I, DAG.getNode(ISD::FSQRT,
3944 getValue(I.getOperand(1)).getValueType(),
3945 getValue(I.getOperand(1))));
3946 return 0;
3947 case Intrinsic::powi:
3948 setValue(&I, DAG.getNode(ISD::FPOWI,
3949 getValue(I.getOperand(1)).getValueType(),
3950 getValue(I.getOperand(1)),
3951 getValue(I.getOperand(2))));
3952 return 0;
3953 case Intrinsic::sin:
3954 setValue(&I, DAG.getNode(ISD::FSIN,
3955 getValue(I.getOperand(1)).getValueType(),
3956 getValue(I.getOperand(1))));
3957 return 0;
3958 case Intrinsic::cos:
3959 setValue(&I, DAG.getNode(ISD::FCOS,
3960 getValue(I.getOperand(1)).getValueType(),
3961 getValue(I.getOperand(1))));
3962 return 0;
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003963 case Intrinsic::log:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003964 visitLog(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003965 return 0;
3966 case Intrinsic::log2:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003967 visitLog2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003968 return 0;
3969 case Intrinsic::log10:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003970 visitLog10(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003971 return 0;
3972 case Intrinsic::exp:
Dale Johannesen59e577f2008-09-05 18:38:42 +00003973 visitExp(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003974 return 0;
3975 case Intrinsic::exp2:
Dale Johannesen601d3c02008-09-05 01:48:15 +00003976 visitExp2(I);
Dale Johannesen7794f2a2008-09-04 00:47:13 +00003977 return 0;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003978 case Intrinsic::pow:
Bill Wendlingaeb5c7b2008-09-10 00:20:20 +00003979 visitPow(I);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00003980 return 0;
3981 case Intrinsic::pcmarker: {
3982 SDValue Tmp = getValue(I.getOperand(1));
3983 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3984 return 0;
3985 }
3986 case Intrinsic::readcyclecounter: {
3987 SDValue Op = getRoot();
3988 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3989 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3990 &Op, 1);
3991 setValue(&I, Tmp);
3992 DAG.setRoot(Tmp.getValue(1));
3993 return 0;
3994 }
3995 case Intrinsic::part_select: {
3996 // Currently not implemented: just abort
3997 assert(0 && "part_select intrinsic not implemented");
3998 abort();
3999 }
4000 case Intrinsic::part_set: {
4001 // Currently not implemented: just abort
4002 assert(0 && "part_set intrinsic not implemented");
4003 abort();
4004 }
4005 case Intrinsic::bswap:
4006 setValue(&I, DAG.getNode(ISD::BSWAP,
4007 getValue(I.getOperand(1)).getValueType(),
4008 getValue(I.getOperand(1))));
4009 return 0;
4010 case Intrinsic::cttz: {
4011 SDValue Arg = getValue(I.getOperand(1));
4012 MVT Ty = Arg.getValueType();
4013 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
4014 setValue(&I, result);
4015 return 0;
4016 }
4017 case Intrinsic::ctlz: {
4018 SDValue Arg = getValue(I.getOperand(1));
4019 MVT Ty = Arg.getValueType();
4020 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
4021 setValue(&I, result);
4022 return 0;
4023 }
4024 case Intrinsic::ctpop: {
4025 SDValue Arg = getValue(I.getOperand(1));
4026 MVT Ty = Arg.getValueType();
4027 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
4028 setValue(&I, result);
4029 return 0;
4030 }
4031 case Intrinsic::stacksave: {
4032 SDValue Op = getRoot();
4033 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
4034 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
4035 setValue(&I, Tmp);
4036 DAG.setRoot(Tmp.getValue(1));
4037 return 0;
4038 }
4039 case Intrinsic::stackrestore: {
4040 SDValue Tmp = getValue(I.getOperand(1));
4041 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
4042 return 0;
4043 }
Bill Wendling57344502008-11-18 11:01:33 +00004044 case Intrinsic::stackprotector: {
Bill Wendlingb2a42982008-11-06 02:29:10 +00004045 // Emit code into the DAG to store the stack guard onto the stack.
4046 MachineFunction &MF = DAG.getMachineFunction();
4047 MachineFrameInfo *MFI = MF.getFrameInfo();
4048 MVT PtrTy = TLI.getPointerTy();
4049
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004050 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4051 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
Bill Wendlingb2a42982008-11-06 02:29:10 +00004052
Bill Wendlingb7c6ebc2008-11-07 01:23:58 +00004053 int FI = FuncInfo.StaticAllocaMap[Slot];
Bill Wendlingb2a42982008-11-06 02:29:10 +00004054 MFI->setStackProtectorIndex(FI);
4055
4056 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4057
4058 // Store the stack protector onto the stack.
4059 SDValue Result = DAG.getStore(getRoot(), Src, FIN,
4060 PseudoSourceValue::getFixedStack(FI),
4061 0, true);
4062 setValue(&I, Result);
4063 DAG.setRoot(Result);
4064 return 0;
4065 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004066 case Intrinsic::var_annotation:
4067 // Discard annotate attributes
4068 return 0;
4069
4070 case Intrinsic::init_trampoline: {
4071 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4072
4073 SDValue Ops[6];
4074 Ops[0] = getRoot();
4075 Ops[1] = getValue(I.getOperand(1));
4076 Ops[2] = getValue(I.getOperand(2));
4077 Ops[3] = getValue(I.getOperand(3));
4078 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4079 Ops[5] = DAG.getSrcValue(F);
4080
4081 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
4082 DAG.getNodeValueTypes(TLI.getPointerTy(),
4083 MVT::Other), 2,
4084 Ops, 6);
4085
4086 setValue(&I, Tmp);
4087 DAG.setRoot(Tmp.getValue(1));
4088 return 0;
4089 }
4090
4091 case Intrinsic::gcroot:
4092 if (GFI) {
4093 Value *Alloca = I.getOperand(1);
4094 Constant *TypeMap = cast<Constant>(I.getOperand(2));
4095
4096 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4097 GFI->addStackRoot(FI->getIndex(), TypeMap);
4098 }
4099 return 0;
4100
4101 case Intrinsic::gcread:
4102 case Intrinsic::gcwrite:
4103 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
4104 return 0;
4105
4106 case Intrinsic::flt_rounds: {
4107 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
4108 return 0;
4109 }
4110
4111 case Intrinsic::trap: {
4112 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
4113 return 0;
4114 }
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004115
Bill Wendlingef375462008-11-21 02:38:44 +00004116 case Intrinsic::uadd_with_overflow:
Bill Wendling74c37652008-12-09 22:08:41 +00004117 return implVisitAluOverflow(I, ISD::UADDO);
4118 case Intrinsic::sadd_with_overflow:
4119 return implVisitAluOverflow(I, ISD::SADDO);
4120 case Intrinsic::usub_with_overflow:
4121 return implVisitAluOverflow(I, ISD::USUBO);
4122 case Intrinsic::ssub_with_overflow:
4123 return implVisitAluOverflow(I, ISD::SSUBO);
4124 case Intrinsic::umul_with_overflow:
4125 return implVisitAluOverflow(I, ISD::UMULO);
4126 case Intrinsic::smul_with_overflow:
4127 return implVisitAluOverflow(I, ISD::SMULO);
Bill Wendling7cdc3c82008-11-21 02:03:52 +00004128
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004129 case Intrinsic::prefetch: {
4130 SDValue Ops[4];
4131 Ops[0] = getRoot();
4132 Ops[1] = getValue(I.getOperand(1));
4133 Ops[2] = getValue(I.getOperand(2));
4134 Ops[3] = getValue(I.getOperand(3));
4135 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
4136 return 0;
4137 }
4138
4139 case Intrinsic::memory_barrier: {
4140 SDValue Ops[6];
4141 Ops[0] = getRoot();
4142 for (int x = 1; x < 6; ++x)
4143 Ops[x] = getValue(I.getOperand(x));
4144
4145 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
4146 return 0;
4147 }
4148 case Intrinsic::atomic_cmp_swap: {
4149 SDValue Root = getRoot();
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004150 SDValue L =
4151 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP,
4152 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4153 Root,
4154 getValue(I.getOperand(1)),
4155 getValue(I.getOperand(2)),
4156 getValue(I.getOperand(3)),
4157 I.getOperand(1));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004158 setValue(&I, L);
4159 DAG.setRoot(L.getValue(1));
4160 return 0;
4161 }
4162 case Intrinsic::atomic_load_add:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004163 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004164 case Intrinsic::atomic_load_sub:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004165 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004166 case Intrinsic::atomic_load_or:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004167 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004168 case Intrinsic::atomic_load_xor:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004169 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004170 case Intrinsic::atomic_load_and:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004171 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004172 case Intrinsic::atomic_load_nand:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004173 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004174 case Intrinsic::atomic_load_max:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004175 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004176 case Intrinsic::atomic_load_min:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004177 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004178 case Intrinsic::atomic_load_umin:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004179 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004180 case Intrinsic::atomic_load_umax:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004181 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004182 case Intrinsic::atomic_swap:
Dan Gohman0b1d4a72008-12-23 21:37:04 +00004183 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004184 }
4185}
4186
4187
4188void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4189 bool IsTailCall,
4190 MachineBasicBlock *LandingPad) {
4191 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4192 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4193 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4194 unsigned BeginLabel = 0, EndLabel = 0;
4195
4196 TargetLowering::ArgListTy Args;
4197 TargetLowering::ArgListEntry Entry;
4198 Args.reserve(CS.arg_size());
4199 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4200 i != e; ++i) {
4201 SDValue ArgNode = getValue(*i);
4202 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4203
4204 unsigned attrInd = i - CS.arg_begin() + 1;
Devang Patel05988662008-09-25 21:00:45 +00004205 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4206 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4207 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4208 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4209 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4210 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004211 Entry.Alignment = CS.getParamAlignment(attrInd);
4212 Args.push_back(Entry);
4213 }
4214
4215 if (LandingPad && MMI) {
4216 // Insert a label before the invoke call to mark the try range. This can be
4217 // used to detect deletion of the invoke via the MachineModuleInfo.
4218 BeginLabel = MMI->NextLabelID();
4219 // Both PendingLoads and PendingExports must be flushed here;
4220 // this call might not return.
4221 (void)getRoot();
4222 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
4223 }
4224
4225 std::pair<SDValue,SDValue> Result =
4226 TLI.LowerCallTo(getRoot(), CS.getType(),
Devang Patel05988662008-09-25 21:00:45 +00004227 CS.paramHasAttr(0, Attribute::SExt),
Dale Johannesen86098bd2008-09-26 19:31:26 +00004228 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4229 CS.paramHasAttr(0, Attribute::InReg),
4230 CS.getCallingConv(),
Dan Gohman1937e2f2008-09-16 01:42:28 +00004231 IsTailCall && PerformTailCallOpt,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004232 Callee, Args, DAG);
4233 if (CS.getType() != Type::VoidTy)
4234 setValue(CS.getInstruction(), Result.first);
4235 DAG.setRoot(Result.second);
4236
4237 if (LandingPad && MMI) {
4238 // Insert a label at the end of the invoke call to mark the try range. This
4239 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4240 EndLabel = MMI->NextLabelID();
4241 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
4242
4243 // Inform MachineModuleInfo of range.
4244 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4245 }
4246}
4247
4248
4249void SelectionDAGLowering::visitCall(CallInst &I) {
4250 const char *RenameFn = 0;
4251 if (Function *F = I.getCalledFunction()) {
4252 if (F->isDeclaration()) {
4253 if (unsigned IID = F->getIntrinsicID()) {
4254 RenameFn = visitIntrinsicCall(I, IID);
4255 if (!RenameFn)
4256 return;
4257 }
4258 }
4259
4260 // Check for well-known libc/libm calls. If the function is internal, it
4261 // can't be a library call.
4262 unsigned NameLen = F->getNameLen();
4263 if (!F->hasInternalLinkage() && NameLen) {
4264 const char *NameStr = F->getNameStart();
4265 if (NameStr[0] == 'c' &&
4266 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4267 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4268 if (I.getNumOperands() == 3 && // Basic sanity checks.
4269 I.getOperand(1)->getType()->isFloatingPoint() &&
4270 I.getType() == I.getOperand(1)->getType() &&
4271 I.getType() == I.getOperand(2)->getType()) {
4272 SDValue LHS = getValue(I.getOperand(1));
4273 SDValue RHS = getValue(I.getOperand(2));
4274 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
4275 LHS, RHS));
4276 return;
4277 }
4278 } else if (NameStr[0] == 'f' &&
4279 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4280 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4281 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4282 if (I.getNumOperands() == 2 && // Basic sanity checks.
4283 I.getOperand(1)->getType()->isFloatingPoint() &&
4284 I.getType() == I.getOperand(1)->getType()) {
4285 SDValue Tmp = getValue(I.getOperand(1));
4286 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
4287 return;
4288 }
4289 } else if (NameStr[0] == 's' &&
4290 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4291 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4292 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4293 if (I.getNumOperands() == 2 && // Basic sanity checks.
4294 I.getOperand(1)->getType()->isFloatingPoint() &&
4295 I.getType() == I.getOperand(1)->getType()) {
4296 SDValue Tmp = getValue(I.getOperand(1));
4297 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
4298 return;
4299 }
4300 } else if (NameStr[0] == 'c' &&
4301 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4302 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4303 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4304 if (I.getNumOperands() == 2 && // Basic sanity checks.
4305 I.getOperand(1)->getType()->isFloatingPoint() &&
4306 I.getType() == I.getOperand(1)->getType()) {
4307 SDValue Tmp = getValue(I.getOperand(1));
4308 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
4309 return;
4310 }
4311 }
4312 }
4313 } else if (isa<InlineAsm>(I.getOperand(0))) {
4314 visitInlineAsm(&I);
4315 return;
4316 }
4317
4318 SDValue Callee;
4319 if (!RenameFn)
4320 Callee = getValue(I.getOperand(0));
4321 else
Bill Wendling056292f2008-09-16 21:48:12 +00004322 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004323
4324 LowerCallTo(&I, Callee, I.isTailCall());
4325}
4326
4327
4328/// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4329/// this value and returns the result as a ValueVT value. This uses
4330/// Chain/Flag as the input and updates them for the output Chain/Flag.
4331/// If the Flag pointer is NULL, no flag is used.
4332SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
4333 SDValue &Chain,
4334 SDValue *Flag) const {
4335 // Assemble the legal parts into the final values.
4336 SmallVector<SDValue, 4> Values(ValueVTs.size());
4337 SmallVector<SDValue, 8> Parts;
4338 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4339 // Copy the legal parts from the registers.
4340 MVT ValueVT = ValueVTs[Value];
4341 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4342 MVT RegisterVT = RegVTs[Value];
4343
4344 Parts.resize(NumRegs);
4345 for (unsigned i = 0; i != NumRegs; ++i) {
4346 SDValue P;
4347 if (Flag == 0)
4348 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
4349 else {
4350 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
4351 *Flag = P.getValue(2);
4352 }
4353 Chain = P.getValue(1);
4354
4355 // If the source register was virtual and if we know something about it,
4356 // add an assert node.
4357 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4358 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4359 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4360 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4361 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4362 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4363
4364 unsigned RegSize = RegisterVT.getSizeInBits();
4365 unsigned NumSignBits = LOI.NumSignBits;
4366 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4367
4368 // FIXME: We capture more information than the dag can represent. For
4369 // now, just use the tightest assertzext/assertsext possible.
4370 bool isSExt = true;
4371 MVT FromVT(MVT::Other);
4372 if (NumSignBits == RegSize)
4373 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4374 else if (NumZeroBits >= RegSize-1)
4375 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4376 else if (NumSignBits > RegSize-8)
4377 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4378 else if (NumZeroBits >= RegSize-9)
4379 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4380 else if (NumSignBits > RegSize-16)
Bill Wendling181b6272008-10-19 20:34:04 +00004381 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004382 else if (NumZeroBits >= RegSize-17)
Bill Wendling181b6272008-10-19 20:34:04 +00004383 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004384 else if (NumSignBits > RegSize-32)
Bill Wendling181b6272008-10-19 20:34:04 +00004385 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004386 else if (NumZeroBits >= RegSize-33)
Bill Wendling181b6272008-10-19 20:34:04 +00004387 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004388
4389 if (FromVT != MVT::Other) {
4390 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
4391 RegisterVT, P, DAG.getValueType(FromVT));
4392
4393 }
4394 }
4395 }
4396
4397 Parts[i] = P;
4398 }
4399
4400 Values[Value] = getCopyFromParts(DAG, Parts.begin(), NumRegs, RegisterVT,
4401 ValueVT);
4402 Part += NumRegs;
4403 Parts.clear();
4404 }
4405
Duncan Sandsaaffa052008-12-01 11:41:29 +00004406 return DAG.getNode(ISD::MERGE_VALUES,
4407 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4408 &Values[0], ValueVTs.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004409}
4410
4411/// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4412/// specified value into the registers specified by this object. This uses
4413/// Chain/Flag as the input and updates them for the output Chain/Flag.
4414/// If the Flag pointer is NULL, no flag is used.
4415void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
4416 SDValue &Chain, SDValue *Flag) const {
4417 // Get the list of the values's legal parts.
4418 unsigned NumRegs = Regs.size();
4419 SmallVector<SDValue, 8> Parts(NumRegs);
4420 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4421 MVT ValueVT = ValueVTs[Value];
4422 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4423 MVT RegisterVT = RegVTs[Value];
4424
4425 getCopyToParts(DAG, Val.getValue(Val.getResNo() + Value),
4426 &Parts[Part], NumParts, RegisterVT);
4427 Part += NumParts;
4428 }
4429
4430 // Copy the parts into the registers.
4431 SmallVector<SDValue, 8> Chains(NumRegs);
4432 for (unsigned i = 0; i != NumRegs; ++i) {
4433 SDValue Part;
4434 if (Flag == 0)
4435 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
4436 else {
4437 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
4438 *Flag = Part.getValue(1);
4439 }
4440 Chains[i] = Part.getValue(0);
4441 }
4442
4443 if (NumRegs == 1 || Flag)
4444 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4445 // flagged to it. That is the CopyToReg nodes and the user are considered
4446 // a single scheduling unit. If we create a TokenFactor and return it as
4447 // chain, then the TokenFactor is both a predecessor (operand) of the
4448 // user as well as a successor (the TF operands are flagged to the user).
4449 // c1, f1 = CopyToReg
4450 // c2, f2 = CopyToReg
4451 // c3 = TokenFactor c1, c2
4452 // ...
4453 // = op c3, ..., f2
4454 Chain = Chains[NumRegs-1];
4455 else
4456 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
4457}
4458
4459/// AddInlineAsmOperands - Add this value to the specified inlineasm node
4460/// operand list. This adds the code marker and includes the number of
4461/// values added into it.
4462void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
4463 std::vector<SDValue> &Ops) const {
4464 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4465 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
4466 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4467 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4468 MVT RegisterVT = RegVTs[Value];
Chris Lattner58f15c42008-10-17 16:21:11 +00004469 for (unsigned i = 0; i != NumRegs; ++i) {
4470 assert(Reg < Regs.size() && "Mismatch in # registers expected");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004471 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
Chris Lattner58f15c42008-10-17 16:21:11 +00004472 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004473 }
4474}
4475
4476/// isAllocatableRegister - If the specified register is safe to allocate,
4477/// i.e. it isn't a stack pointer or some other special register, return the
4478/// register class for the register. Otherwise, return null.
4479static const TargetRegisterClass *
4480isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4481 const TargetLowering &TLI,
4482 const TargetRegisterInfo *TRI) {
4483 MVT FoundVT = MVT::Other;
4484 const TargetRegisterClass *FoundRC = 0;
4485 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4486 E = TRI->regclass_end(); RCI != E; ++RCI) {
4487 MVT ThisVT = MVT::Other;
4488
4489 const TargetRegisterClass *RC = *RCI;
4490 // If none of the the value types for this register class are valid, we
4491 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4492 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4493 I != E; ++I) {
4494 if (TLI.isTypeLegal(*I)) {
4495 // If we have already found this register in a different register class,
4496 // choose the one with the largest VT specified. For example, on
4497 // PowerPC, we favor f64 register classes over f32.
4498 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4499 ThisVT = *I;
4500 break;
4501 }
4502 }
4503 }
4504
4505 if (ThisVT == MVT::Other) continue;
4506
4507 // NOTE: This isn't ideal. In particular, this might allocate the
4508 // frame pointer in functions that need it (due to them not being taken
4509 // out of allocation, because a variable sized allocation hasn't been seen
4510 // yet). This is a slight code pessimization, but should still work.
4511 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4512 E = RC->allocation_order_end(MF); I != E; ++I)
4513 if (*I == Reg) {
4514 // We found a matching register class. Keep looking at others in case
4515 // we find one with larger registers that this physreg is also in.
4516 FoundRC = RC;
4517 FoundVT = ThisVT;
4518 break;
4519 }
4520 }
4521 return FoundRC;
4522}
4523
4524
4525namespace llvm {
4526/// AsmOperandInfo - This contains information for each constraint that we are
4527/// lowering.
Daniel Dunbarc0c3b9a2008-09-10 04:16:29 +00004528struct VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4529 public TargetLowering::AsmOperandInfo {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004530 /// CallOperand - If this is the result output operand or a clobber
4531 /// this is null, otherwise it is the incoming operand to the CallInst.
4532 /// This gets modified as the asm is processed.
4533 SDValue CallOperand;
4534
4535 /// AssignedRegs - If this is a register or register class operand, this
4536 /// contains the set of register corresponding to the operand.
4537 RegsForValue AssignedRegs;
4538
4539 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4540 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4541 }
4542
4543 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4544 /// busy in OutputRegs/InputRegs.
4545 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4546 std::set<unsigned> &OutputRegs,
4547 std::set<unsigned> &InputRegs,
4548 const TargetRegisterInfo &TRI) const {
4549 if (isOutReg) {
4550 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4551 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4552 }
4553 if (isInReg) {
4554 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4555 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4556 }
4557 }
Chris Lattner81249c92008-10-17 17:05:25 +00004558
4559 /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4560 /// corresponds to. If there is no Value* for this operand, it returns
4561 /// MVT::Other.
4562 MVT getCallOperandValMVT(const TargetLowering &TLI,
4563 const TargetData *TD) const {
4564 if (CallOperandVal == 0) return MVT::Other;
4565
4566 if (isa<BasicBlock>(CallOperandVal))
4567 return TLI.getPointerTy();
4568
4569 const llvm::Type *OpTy = CallOperandVal->getType();
4570
4571 // If this is an indirect operand, the operand is a pointer to the
4572 // accessed type.
4573 if (isIndirect)
4574 OpTy = cast<PointerType>(OpTy)->getElementType();
4575
4576 // If OpTy is not a single value, it may be a struct/union that we
4577 // can tile with integers.
4578 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4579 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4580 switch (BitSize) {
4581 default: break;
4582 case 1:
4583 case 8:
4584 case 16:
4585 case 32:
4586 case 64:
Chris Lattnercfc14c12008-10-17 19:59:51 +00004587 case 128:
Chris Lattner81249c92008-10-17 17:05:25 +00004588 OpTy = IntegerType::get(BitSize);
4589 break;
4590 }
4591 }
4592
4593 return TLI.getValueType(OpTy, true);
4594 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004595
4596private:
4597 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4598 /// specified set.
4599 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4600 const TargetRegisterInfo &TRI) {
4601 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4602 Regs.insert(Reg);
4603 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4604 for (; *Aliases; ++Aliases)
4605 Regs.insert(*Aliases);
4606 }
4607};
4608} // end llvm namespace.
4609
4610
4611/// GetRegistersForValue - Assign registers (virtual or physical) for the
4612/// specified operand. We prefer to assign virtual registers, to allow the
4613/// register allocator handle the assignment process. However, if the asm uses
4614/// features that we can't model on machineinstrs, we have SDISel do the
4615/// allocation. This produces generally horrible, but correct, code.
4616///
4617/// OpInfo describes the operand.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004618/// Input and OutputRegs are the set of already allocated physical registers.
4619///
4620void SelectionDAGLowering::
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004621GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004622 std::set<unsigned> &OutputRegs,
4623 std::set<unsigned> &InputRegs) {
4624 // Compute whether this value requires an input register, an output register,
4625 // or both.
4626 bool isOutReg = false;
4627 bool isInReg = false;
4628 switch (OpInfo.Type) {
4629 case InlineAsm::isOutput:
4630 isOutReg = true;
4631
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004632 // If there is an input constraint that matches this, we need to reserve
4633 // the input register so no other inputs allocate to it.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004634 isInReg = OpInfo.hasMatchingInput();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004635 break;
4636 case InlineAsm::isInput:
4637 isInReg = true;
4638 isOutReg = false;
4639 break;
4640 case InlineAsm::isClobber:
4641 isOutReg = true;
4642 isInReg = true;
4643 break;
4644 }
4645
4646
4647 MachineFunction &MF = DAG.getMachineFunction();
4648 SmallVector<unsigned, 4> Regs;
4649
4650 // If this is a constraint for a single physreg, or a constraint for a
4651 // register class, find it.
4652 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4653 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4654 OpInfo.ConstraintVT);
4655
4656 unsigned NumRegs = 1;
Chris Lattner01426e12008-10-21 00:45:36 +00004657 if (OpInfo.ConstraintVT != MVT::Other) {
4658 // If this is a FP input in an integer register (or visa versa) insert a bit
4659 // cast of the input value. More generally, handle any case where the input
4660 // value disagrees with the register class we plan to stick this in.
4661 if (OpInfo.Type == InlineAsm::isInput &&
4662 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4663 // Try to convert to the first MVT that the reg class contains. If the
4664 // types are identical size, use a bitcast to convert (e.g. two differing
4665 // vector types).
4666 MVT RegVT = *PhysReg.second->vt_begin();
4667 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
4668 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4669 OpInfo.CallOperand);
4670 OpInfo.ConstraintVT = RegVT;
4671 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4672 // If the input is a FP value and we want it in FP registers, do a
4673 // bitcast to the corresponding integer type. This turns an f64 value
4674 // into i64, which can be passed with two i32 values on a 32-bit
4675 // machine.
4676 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
4677 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4678 OpInfo.CallOperand);
4679 OpInfo.ConstraintVT = RegVT;
4680 }
4681 }
4682
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004683 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
Chris Lattner01426e12008-10-21 00:45:36 +00004684 }
4685
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004686 MVT RegVT;
4687 MVT ValueVT = OpInfo.ConstraintVT;
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004688
4689 // If this is a constraint for a specific physical register, like {r17},
4690 // assign it now.
4691 if (PhysReg.first) {
4692 if (OpInfo.ConstraintVT == MVT::Other)
4693 ValueVT = *PhysReg.second->vt_begin();
4694
4695 // Get the actual register value type. This is important, because the user
4696 // may have asked for (e.g.) the AX register in i32 type. We need to
4697 // remember that AX is actually i16 to get the right extension.
4698 RegVT = *PhysReg.second->vt_begin();
4699
4700 // This is a explicit reference to a physical register.
4701 Regs.push_back(PhysReg.first);
4702
4703 // If this is an expanded reference, add the rest of the regs to Regs.
4704 if (NumRegs != 1) {
4705 TargetRegisterClass::iterator I = PhysReg.second->begin();
4706 for (; *I != PhysReg.first; ++I)
4707 assert(I != PhysReg.second->end() && "Didn't find reg!");
4708
4709 // Already added the first reg.
4710 --NumRegs; ++I;
4711 for (; NumRegs; --NumRegs, ++I) {
4712 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
4713 Regs.push_back(*I);
4714 }
4715 }
4716 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4717 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4718 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4719 return;
4720 }
4721
4722 // Otherwise, if this was a reference to an LLVM register class, create vregs
4723 // for this reference.
4724 std::vector<unsigned> RegClassRegs;
4725 const TargetRegisterClass *RC = PhysReg.second;
4726 if (RC) {
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004727 // If this is a tied register, our regalloc doesn't know how to maintain
Chris Lattner58f15c42008-10-17 16:21:11 +00004728 // the constraint, so we have to pick a register to pin the input/output to.
4729 // If it isn't a matched constraint, go ahead and create vreg and let the
4730 // regalloc do its thing.
Chris Lattner6bdcda32008-10-17 16:47:46 +00004731 if (!OpInfo.hasMatchingInput()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004732 RegVT = *PhysReg.second->vt_begin();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004733 if (OpInfo.ConstraintVT == MVT::Other)
4734 ValueVT = RegVT;
4735
4736 // Create the appropriate number of virtual registers.
4737 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4738 for (; NumRegs; --NumRegs)
4739 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
4740
4741 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4742 return;
4743 }
4744
4745 // Otherwise, we can't allocate it. Let the code below figure out how to
4746 // maintain these constraints.
4747 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4748
4749 } else {
4750 // This is a reference to a register class that doesn't directly correspond
4751 // to an LLVM register class. Allocate NumRegs consecutive, available,
4752 // registers from the class.
4753 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4754 OpInfo.ConstraintVT);
4755 }
4756
4757 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4758 unsigned NumAllocated = 0;
4759 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4760 unsigned Reg = RegClassRegs[i];
4761 // See if this register is available.
4762 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4763 (isInReg && InputRegs.count(Reg))) { // Already used.
4764 // Make sure we find consecutive registers.
4765 NumAllocated = 0;
4766 continue;
4767 }
4768
4769 // Check to see if this register is allocatable (i.e. don't give out the
4770 // stack pointer).
4771 if (RC == 0) {
4772 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4773 if (!RC) { // Couldn't allocate this register.
4774 // Reset NumAllocated to make sure we return consecutive registers.
4775 NumAllocated = 0;
4776 continue;
4777 }
4778 }
4779
4780 // Okay, this register is good, we can use it.
4781 ++NumAllocated;
4782
4783 // If we allocated enough consecutive registers, succeed.
4784 if (NumAllocated == NumRegs) {
4785 unsigned RegStart = (i-NumAllocated)+1;
4786 unsigned RegEnd = i+1;
4787 // Mark all of the allocated registers used.
4788 for (unsigned i = RegStart; i != RegEnd; ++i)
4789 Regs.push_back(RegClassRegs[i]);
4790
4791 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
4792 OpInfo.ConstraintVT);
4793 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4794 return;
4795 }
4796 }
4797
4798 // Otherwise, we couldn't allocate enough registers for this.
4799}
4800
Evan Chengda43bcf2008-09-24 00:05:32 +00004801/// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
4802/// processed uses a memory 'm' constraint.
4803static bool
4804hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
4805 TargetLowering &TLI) {
4806 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
4807 InlineAsm::ConstraintInfo &CI = CInfos[i];
4808 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
4809 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
4810 if (CType == TargetLowering::C_Memory)
4811 return true;
4812 }
4813 }
4814
4815 return false;
4816}
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004817
4818/// visitInlineAsm - Handle a call to an InlineAsm object.
4819///
4820void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4821 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4822
4823 /// ConstraintOperands - Information about all of the constraints.
4824 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
4825
4826 SDValue Chain = getRoot();
4827 SDValue Flag;
4828
4829 std::set<unsigned> OutputRegs, InputRegs;
4830
4831 // Do a prepass over the constraints, canonicalizing them, and building up the
4832 // ConstraintOperands list.
4833 std::vector<InlineAsm::ConstraintInfo>
4834 ConstraintInfos = IA->ParseConstraints();
4835
Evan Chengda43bcf2008-09-24 00:05:32 +00004836 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004837
4838 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4839 unsigned ResNo = 0; // ResNo - The result number of the next output.
4840 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4841 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4842 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
4843
4844 MVT OpVT = MVT::Other;
4845
4846 // Compute the value type for each operand.
4847 switch (OpInfo.Type) {
4848 case InlineAsm::isOutput:
4849 // Indirect outputs just consume an argument.
4850 if (OpInfo.isIndirect) {
4851 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4852 break;
4853 }
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004854
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004855 // The return value of the call is this value. As such, there is no
4856 // corresponding argument.
4857 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4858 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4859 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4860 } else {
4861 assert(ResNo == 0 && "Asm only has one result!");
4862 OpVT = TLI.getValueType(CS.getType());
4863 }
4864 ++ResNo;
4865 break;
4866 case InlineAsm::isInput:
4867 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4868 break;
4869 case InlineAsm::isClobber:
4870 // Nothing to do.
4871 break;
4872 }
4873
4874 // If this is an input or an indirect output, process the call argument.
4875 // BasicBlocks are labels, currently appearing only in asm's.
4876 if (OpInfo.CallOperandVal) {
Chris Lattner81249c92008-10-17 17:05:25 +00004877 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004878 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
Chris Lattner81249c92008-10-17 17:05:25 +00004879 } else {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004880 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004881 }
Chris Lattner81249c92008-10-17 17:05:25 +00004882
4883 OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004884 }
4885
4886 OpInfo.ConstraintVT = OpVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004887 }
4888
4889 // Second pass over the constraints: compute which constraint option to use
4890 // and assign registers to constraints that want a specific physreg.
4891 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4892 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4893
4894 // If this is an output operand with a matching input operand, look up the
Evan Cheng09dc9c02008-12-16 18:21:39 +00004895 // matching input. If their types mismatch, e.g. one is an integer, the
4896 // other is floating point, or their sizes are different, flag it as an
4897 // error.
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004898 if (OpInfo.hasMatchingInput()) {
4899 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4900 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
Evan Cheng09dc9c02008-12-16 18:21:39 +00004901 if ((OpInfo.ConstraintVT.isInteger() !=
4902 Input.ConstraintVT.isInteger()) ||
4903 (OpInfo.ConstraintVT.getSizeInBits() !=
4904 Input.ConstraintVT.getSizeInBits())) {
4905 cerr << "Unsupported asm: input constraint with a matching output "
4906 << "constraint of incompatible type!\n";
4907 exit(1);
4908 }
4909 Input.ConstraintVT = OpInfo.ConstraintVT;
Chris Lattner2a0b96c2008-10-18 18:49:30 +00004910 }
4911 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004912
4913 // Compute the constraint code and ConstraintType to use.
Evan Chengda43bcf2008-09-24 00:05:32 +00004914 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004915
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004916 // If this is a memory input, and if the operand is not indirect, do what we
4917 // need to to provide an address for the memory input.
4918 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4919 !OpInfo.isIndirect) {
4920 assert(OpInfo.Type == InlineAsm::isInput &&
4921 "Can only indirectify direct input operands!");
4922
4923 // Memory operands really want the address of the value. If we don't have
4924 // an indirect input, put it in the constpool if we can, otherwise spill
4925 // it to a stack slot.
4926
4927 // If the operand is a float, integer, or vector constant, spill to a
4928 // constant pool entry to get its address.
4929 Value *OpVal = OpInfo.CallOperandVal;
4930 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4931 isa<ConstantVector>(OpVal)) {
4932 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4933 TLI.getPointerTy());
4934 } else {
4935 // Otherwise, create a stack slot and emit a store to it before the
4936 // asm.
4937 const Type *Ty = OpVal->getType();
4938 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
4939 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4940 MachineFunction &MF = DAG.getMachineFunction();
4941 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4942 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4943 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4944 OpInfo.CallOperand = StackSlot;
4945 }
4946
4947 // There is no longer a Value* corresponding to this operand.
4948 OpInfo.CallOperandVal = 0;
4949 // It is now an indirect operand.
4950 OpInfo.isIndirect = true;
4951 }
4952
4953 // If this constraint is for a specific register, allocate it before
4954 // anything else.
4955 if (OpInfo.ConstraintType == TargetLowering::C_Register)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004956 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004957 }
4958 ConstraintInfos.clear();
4959
4960
4961 // Second pass - Loop over all of the operands, assigning virtual or physregs
Chris Lattner58f15c42008-10-17 16:21:11 +00004962 // to register class operands.
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004963 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4964 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4965
4966 // C_Register operands have already been allocated, Other/Memory don't need
4967 // to be.
4968 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
Dale Johannesen8e3455b2008-09-24 23:13:09 +00004969 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004970 }
4971
4972 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4973 std::vector<SDValue> AsmNodeOperands;
4974 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
4975 AsmNodeOperands.push_back(
Bill Wendling056292f2008-09-16 21:48:12 +00004976 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004977
4978
4979 // Loop over all of the inputs, copying the operand values into the
4980 // appropriate registers and processing the output regs.
4981 RegsForValue RetValRegs;
4982
4983 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4984 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4985
4986 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4987 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4988
4989 switch (OpInfo.Type) {
4990 case InlineAsm::isOutput: {
4991 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4992 OpInfo.ConstraintType != TargetLowering::C_Register) {
4993 // Memory output, or 'other' output (e.g. 'X' constraint).
4994 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
4995
4996 // Add information to the INLINEASM node to know about this output.
Dale Johannesen86b49f82008-09-24 01:07:17 +00004997 unsigned ResOpType = 4/*MEM*/ | (1<<3);
4998 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00004999 TLI.getPointerTy()));
5000 AsmNodeOperands.push_back(OpInfo.CallOperand);
5001 break;
5002 }
5003
5004 // Otherwise, this is a register or register class output.
5005
5006 // Copy the output from the appropriate register. Find a register that
5007 // we can use.
5008 if (OpInfo.AssignedRegs.Regs.empty()) {
5009 cerr << "Couldn't allocate output reg for constraint '"
5010 << OpInfo.ConstraintCode << "'!\n";
5011 exit(1);
5012 }
5013
5014 // If this is an indirect operand, store through the pointer after the
5015 // asm.
5016 if (OpInfo.isIndirect) {
5017 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5018 OpInfo.CallOperandVal));
5019 } else {
5020 // This is the result value of the call.
5021 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5022 // Concatenate this output onto the outputs list.
5023 RetValRegs.append(OpInfo.AssignedRegs);
5024 }
5025
5026 // Add information to the INLINEASM node to know that this register is
5027 // set.
Dale Johannesen913d3df2008-09-12 17:49:03 +00005028 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5029 6 /* EARLYCLOBBER REGDEF */ :
5030 2 /* REGDEF */ ,
5031 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005032 break;
5033 }
5034 case InlineAsm::isInput: {
5035 SDValue InOperandVal = OpInfo.CallOperand;
5036
Chris Lattner6bdcda32008-10-17 16:47:46 +00005037 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005038 // If this is required to match an output register we have already set,
5039 // just use its register.
Chris Lattner58f15c42008-10-17 16:21:11 +00005040 unsigned OperandNo = OpInfo.getMatchedOperand();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005041
5042 // Scan until we find the definition we already emitted of this operand.
5043 // When we find it, create a RegsForValue operand.
5044 unsigned CurOp = 2; // The first operand.
5045 for (; OperandNo; --OperandNo) {
5046 // Advance to the next operand.
5047 unsigned NumOps =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005048 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005049 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
Dale Johannesen913d3df2008-09-12 17:49:03 +00005050 (NumOps & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
Dale Johannesen86b49f82008-09-24 01:07:17 +00005051 (NumOps & 7) == 4 /*MEM*/) &&
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005052 "Skipped past definitions?");
5053 CurOp += (NumOps>>3)+1;
5054 }
5055
5056 unsigned NumOps =
Dan Gohmanf5aeb1a2008-09-12 16:56:44 +00005057 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
Dale Johannesen913d3df2008-09-12 17:49:03 +00005058 if ((NumOps & 7) == 2 /*REGDEF*/
5059 || (NumOps & 7) == 6 /* EARLYCLOBBER REGDEF */) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005060 // Add NumOps>>3 registers to MatchedRegs.
5061 RegsForValue MatchedRegs;
5062 MatchedRegs.TLI = &TLI;
5063 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5064 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
5065 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
5066 unsigned Reg =
5067 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
5068 MatchedRegs.Regs.push_back(Reg);
5069 }
5070
5071 // Use the produced MatchedRegs object to
5072 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
Dale Johannesen86b49f82008-09-24 01:07:17 +00005073 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005074 break;
5075 } else {
Dale Johannesen86b49f82008-09-24 01:07:17 +00005076 assert(((NumOps & 7) == 4) && "Unknown matching constraint!");
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005077 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
5078 // Add information to the INLINEASM node to know about this input.
Dale Johannesen91aac102008-09-17 21:13:11 +00005079 AsmNodeOperands.push_back(DAG.getTargetConstant(NumOps,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005080 TLI.getPointerTy()));
5081 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5082 break;
5083 }
5084 }
5085
5086 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5087 assert(!OpInfo.isIndirect &&
5088 "Don't know how to handle indirect other inputs yet!");
5089
5090 std::vector<SDValue> Ops;
5091 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
Evan Chengda43bcf2008-09-24 00:05:32 +00005092 hasMemory, Ops, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005093 if (Ops.empty()) {
5094 cerr << "Invalid operand for inline asm constraint '"
5095 << OpInfo.ConstraintCode << "'!\n";
5096 exit(1);
5097 }
5098
5099 // Add information to the INLINEASM node to know about this input.
5100 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
5101 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5102 TLI.getPointerTy()));
5103 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5104 break;
5105 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5106 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5107 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5108 "Memory operands expect pointer values");
5109
5110 // Add information to the INLINEASM node to know about this input.
Dale Johannesen86b49f82008-09-24 01:07:17 +00005111 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5112 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005113 TLI.getPointerTy()));
5114 AsmNodeOperands.push_back(InOperandVal);
5115 break;
5116 }
5117
5118 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5119 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5120 "Unknown constraint type!");
5121 assert(!OpInfo.isIndirect &&
5122 "Don't know how to handle indirect register inputs yet!");
5123
5124 // Copy the input into the appropriate registers.
Evan Chengaa765b82008-09-25 00:14:04 +00005125 if (OpInfo.AssignedRegs.Regs.empty()) {
5126 cerr << "Couldn't allocate output reg for constraint '"
5127 << OpInfo.ConstraintCode << "'!\n";
5128 exit(1);
5129 }
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005130
5131 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
5132
Dale Johannesen86b49f82008-09-24 01:07:17 +00005133 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/,
5134 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005135 break;
5136 }
5137 case InlineAsm::isClobber: {
5138 // Add the clobbered value to the operand list, so that the register
5139 // allocator is aware that the physreg got clobbered.
5140 if (!OpInfo.AssignedRegs.Regs.empty())
Dale Johannesen91aac102008-09-17 21:13:11 +00005141 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
5142 DAG, AsmNodeOperands);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005143 break;
5144 }
5145 }
5146 }
5147
5148 // Finish up input operands.
5149 AsmNodeOperands[0] = Chain;
5150 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5151
5152 Chain = DAG.getNode(ISD::INLINEASM,
5153 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
5154 &AsmNodeOperands[0], AsmNodeOperands.size());
5155 Flag = Chain.getValue(1);
5156
5157 // If this asm returns a register value, copy the result from that register
5158 // and set it as the value of the call.
5159 if (!RetValRegs.Regs.empty()) {
5160 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005161
5162 // FIXME: Why don't we do this for inline asms with MRVs?
5163 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5164 MVT ResultType = TLI.getValueType(CS.getType());
5165
5166 // If any of the results of the inline asm is a vector, it may have the
5167 // wrong width/num elts. This can happen for register classes that can
5168 // contain multiple different value types. The preg or vreg allocated may
5169 // not have the same VT as was expected. Convert it to the right type
5170 // with bit_convert.
5171 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5172 Val = DAG.getNode(ISD::BIT_CONVERT, ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005173
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005174 } else if (ResultType != Val.getValueType() &&
5175 ResultType.isInteger() && Val.getValueType().isInteger()) {
5176 // If a result value was tied to an input value, the computed result may
5177 // have a wider width than the expected result. Extract the relevant
5178 // portion.
5179 Val = DAG.getNode(ISD::TRUNCATE, ResultType, Val);
Dan Gohman95915732008-10-18 01:03:45 +00005180 }
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005181
5182 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
Chris Lattner0c526442008-10-17 17:52:49 +00005183 }
Dan Gohman95915732008-10-18 01:03:45 +00005184
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005185 setValue(CS.getInstruction(), Val);
5186 }
5187
5188 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5189
5190 // Process indirect outputs, first output all of the flagged copies out of
5191 // physregs.
5192 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5193 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5194 Value *Ptr = IndirectStoresToEmit[i].second;
5195 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
5196 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5197 }
5198
5199 // Emit the non-flagged stores from the physregs.
5200 SmallVector<SDValue, 8> OutChains;
5201 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5202 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
5203 getValue(StoresToEmit[i].second),
5204 StoresToEmit[i].second, 0));
5205 if (!OutChains.empty())
5206 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5207 &OutChains[0], OutChains.size());
5208 DAG.setRoot(Chain);
5209}
5210
5211
5212void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5213 SDValue Src = getValue(I.getOperand(0));
5214
5215 MVT IntPtr = TLI.getPointerTy();
5216
5217 if (IntPtr.bitsLT(Src.getValueType()))
5218 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
5219 else if (IntPtr.bitsGT(Src.getValueType()))
5220 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
5221
5222 // Scale the source by the type size.
5223 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
5224 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
5225 Src, DAG.getIntPtrConstant(ElementSize));
5226
5227 TargetLowering::ArgListTy Args;
5228 TargetLowering::ArgListEntry Entry;
5229 Entry.Node = Src;
5230 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5231 Args.push_back(Entry);
5232
5233 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005234 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
5235 CallingConv::C, PerformTailCallOpt,
5236 DAG.getExternalSymbol("malloc", IntPtr),
Dan Gohman1937e2f2008-09-16 01:42:28 +00005237 Args, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005238 setValue(&I, Result.first); // Pointers always fit in registers
5239 DAG.setRoot(Result.second);
5240}
5241
5242void SelectionDAGLowering::visitFree(FreeInst &I) {
5243 TargetLowering::ArgListTy Args;
5244 TargetLowering::ArgListEntry Entry;
5245 Entry.Node = getValue(I.getOperand(0));
5246 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5247 Args.push_back(Entry);
5248 MVT IntPtr = TLI.getPointerTy();
5249 std::pair<SDValue,SDValue> Result =
Dale Johannesen86098bd2008-09-26 19:31:26 +00005250 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
Dan Gohman1937e2f2008-09-16 01:42:28 +00005251 CallingConv::C, PerformTailCallOpt,
Bill Wendling056292f2008-09-16 21:48:12 +00005252 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005253 DAG.setRoot(Result.second);
5254}
5255
5256void SelectionDAGLowering::visitVAStart(CallInst &I) {
5257 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
5258 getValue(I.getOperand(1)),
5259 DAG.getSrcValue(I.getOperand(1))));
5260}
5261
5262void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
5263 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
5264 getValue(I.getOperand(0)),
5265 DAG.getSrcValue(I.getOperand(0)));
5266 setValue(&I, V);
5267 DAG.setRoot(V.getValue(1));
5268}
5269
5270void SelectionDAGLowering::visitVAEnd(CallInst &I) {
5271 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
5272 getValue(I.getOperand(1)),
5273 DAG.getSrcValue(I.getOperand(1))));
5274}
5275
5276void SelectionDAGLowering::visitVACopy(CallInst &I) {
5277 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
5278 getValue(I.getOperand(1)),
5279 getValue(I.getOperand(2)),
5280 DAG.getSrcValue(I.getOperand(1)),
5281 DAG.getSrcValue(I.getOperand(2))));
5282}
5283
5284/// TargetLowering::LowerArguments - This is the default LowerArguments
5285/// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
5286/// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
5287/// integrated into SDISel.
5288void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
5289 SmallVectorImpl<SDValue> &ArgValues) {
5290 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5291 SmallVector<SDValue, 3+16> Ops;
5292 Ops.push_back(DAG.getRoot());
5293 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5294 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5295
5296 // Add one result value for each formal argument.
5297 SmallVector<MVT, 16> RetVals;
5298 unsigned j = 1;
5299 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5300 I != E; ++I, ++j) {
5301 SmallVector<MVT, 4> ValueVTs;
5302 ComputeValueVTs(*this, I->getType(), ValueVTs);
5303 for (unsigned Value = 0, NumValues = ValueVTs.size();
5304 Value != NumValues; ++Value) {
5305 MVT VT = ValueVTs[Value];
5306 const Type *ArgTy = VT.getTypeForMVT();
5307 ISD::ArgFlagsTy Flags;
5308 unsigned OriginalAlignment =
5309 getTargetData()->getABITypeAlignment(ArgTy);
5310
Devang Patel05988662008-09-25 21:00:45 +00005311 if (F.paramHasAttr(j, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005312 Flags.setZExt();
Devang Patel05988662008-09-25 21:00:45 +00005313 if (F.paramHasAttr(j, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005314 Flags.setSExt();
Devang Patel05988662008-09-25 21:00:45 +00005315 if (F.paramHasAttr(j, Attribute::InReg))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005316 Flags.setInReg();
Devang Patel05988662008-09-25 21:00:45 +00005317 if (F.paramHasAttr(j, Attribute::StructRet))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005318 Flags.setSRet();
Devang Patel05988662008-09-25 21:00:45 +00005319 if (F.paramHasAttr(j, Attribute::ByVal)) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005320 Flags.setByVal();
5321 const PointerType *Ty = cast<PointerType>(I->getType());
5322 const Type *ElementTy = Ty->getElementType();
5323 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5324 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
5325 // For ByVal, alignment should be passed from FE. BE will guess if
5326 // this info is not there but there are cases it cannot get right.
5327 if (F.getParamAlignment(j))
5328 FrameAlign = F.getParamAlignment(j);
5329 Flags.setByValAlign(FrameAlign);
5330 Flags.setByValSize(FrameSize);
5331 }
Devang Patel05988662008-09-25 21:00:45 +00005332 if (F.paramHasAttr(j, Attribute::Nest))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005333 Flags.setNest();
5334 Flags.setOrigAlign(OriginalAlignment);
5335
5336 MVT RegisterVT = getRegisterType(VT);
5337 unsigned NumRegs = getNumRegisters(VT);
5338 for (unsigned i = 0; i != NumRegs; ++i) {
5339 RetVals.push_back(RegisterVT);
5340 ISD::ArgFlagsTy MyFlags = Flags;
5341 if (NumRegs > 1 && i == 0)
5342 MyFlags.setSplit();
5343 // if it isn't first piece, alignment must be 1
5344 else if (i > 0)
5345 MyFlags.setOrigAlign(1);
5346 Ops.push_back(DAG.getArgFlags(MyFlags));
5347 }
5348 }
5349 }
5350
5351 RetVals.push_back(MVT::Other);
5352
5353 // Create the node.
5354 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
5355 DAG.getVTList(&RetVals[0], RetVals.size()),
5356 &Ops[0], Ops.size()).getNode();
5357
5358 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5359 // allows exposing the loads that may be part of the argument access to the
5360 // first DAGCombiner pass.
5361 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
5362
5363 // The number of results should match up, except that the lowered one may have
5364 // an extra flag result.
5365 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5366 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5367 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5368 && "Lowering produced unexpected number of results!");
5369
5370 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5371 if (Result != TmpRes.getNode() && Result->use_empty()) {
5372 HandleSDNode Dummy(DAG.getRoot());
5373 DAG.RemoveDeadNode(Result);
5374 }
5375
5376 Result = TmpRes.getNode();
5377
5378 unsigned NumArgRegs = Result->getNumValues() - 1;
5379 DAG.setRoot(SDValue(Result, NumArgRegs));
5380
5381 // Set up the return result vector.
5382 unsigned i = 0;
5383 unsigned Idx = 1;
5384 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5385 ++I, ++Idx) {
5386 SmallVector<MVT, 4> ValueVTs;
5387 ComputeValueVTs(*this, I->getType(), ValueVTs);
5388 for (unsigned Value = 0, NumValues = ValueVTs.size();
5389 Value != NumValues; ++Value) {
5390 MVT VT = ValueVTs[Value];
5391 MVT PartVT = getRegisterType(VT);
5392
5393 unsigned NumParts = getNumRegisters(VT);
5394 SmallVector<SDValue, 4> Parts(NumParts);
5395 for (unsigned j = 0; j != NumParts; ++j)
5396 Parts[j] = SDValue(Result, i++);
5397
5398 ISD::NodeType AssertOp = ISD::DELETED_NODE;
Devang Patel05988662008-09-25 21:00:45 +00005399 if (F.paramHasAttr(Idx, Attribute::SExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005400 AssertOp = ISD::AssertSext;
Devang Patel05988662008-09-25 21:00:45 +00005401 else if (F.paramHasAttr(Idx, Attribute::ZExt))
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005402 AssertOp = ISD::AssertZext;
5403
5404 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
5405 AssertOp));
5406 }
5407 }
5408 assert(i == NumArgRegs && "Argument register count mismatch!");
5409}
5410
5411
5412/// TargetLowering::LowerCallTo - This is the default LowerCallTo
5413/// implementation, which just inserts an ISD::CALL node, which is later custom
5414/// lowered by the target to something concrete. FIXME: When all targets are
5415/// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5416std::pair<SDValue, SDValue>
5417TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5418 bool RetSExt, bool RetZExt, bool isVarArg,
Dale Johannesen86098bd2008-09-26 19:31:26 +00005419 bool isInreg,
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005420 unsigned CallingConv, bool isTailCall,
5421 SDValue Callee,
5422 ArgListTy &Args, SelectionDAG &DAG) {
Dan Gohman1937e2f2008-09-16 01:42:28 +00005423 assert((!isTailCall || PerformTailCallOpt) &&
5424 "isTailCall set when tail-call optimizations are disabled!");
5425
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005426 SmallVector<SDValue, 32> Ops;
5427 Ops.push_back(Chain); // Op#0 - Chain
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005428 Ops.push_back(Callee);
5429
5430 // Handle all of the outgoing arguments.
5431 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5432 SmallVector<MVT, 4> ValueVTs;
5433 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5434 for (unsigned Value = 0, NumValues = ValueVTs.size();
5435 Value != NumValues; ++Value) {
5436 MVT VT = ValueVTs[Value];
5437 const Type *ArgTy = VT.getTypeForMVT();
Chris Lattner2a0b96c2008-10-18 18:49:30 +00005438 SDValue Op = SDValue(Args[i].Node.getNode(),
5439 Args[i].Node.getResNo() + Value);
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005440 ISD::ArgFlagsTy Flags;
5441 unsigned OriginalAlignment =
5442 getTargetData()->getABITypeAlignment(ArgTy);
5443
5444 if (Args[i].isZExt)
5445 Flags.setZExt();
5446 if (Args[i].isSExt)
5447 Flags.setSExt();
5448 if (Args[i].isInReg)
5449 Flags.setInReg();
5450 if (Args[i].isSRet)
5451 Flags.setSRet();
5452 if (Args[i].isByVal) {
5453 Flags.setByVal();
5454 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5455 const Type *ElementTy = Ty->getElementType();
5456 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5457 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
5458 // For ByVal, alignment should come from FE. BE will guess if this
5459 // info is not there but there are cases it cannot get right.
5460 if (Args[i].Alignment)
5461 FrameAlign = Args[i].Alignment;
5462 Flags.setByValAlign(FrameAlign);
5463 Flags.setByValSize(FrameSize);
5464 }
5465 if (Args[i].isNest)
5466 Flags.setNest();
5467 Flags.setOrigAlign(OriginalAlignment);
5468
5469 MVT PartVT = getRegisterType(VT);
5470 unsigned NumParts = getNumRegisters(VT);
5471 SmallVector<SDValue, 4> Parts(NumParts);
5472 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5473
5474 if (Args[i].isSExt)
5475 ExtendKind = ISD::SIGN_EXTEND;
5476 else if (Args[i].isZExt)
5477 ExtendKind = ISD::ZERO_EXTEND;
5478
5479 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5480
5481 for (unsigned i = 0; i != NumParts; ++i) {
5482 // if it isn't first piece, alignment must be 1
5483 ISD::ArgFlagsTy MyFlags = Flags;
5484 if (NumParts > 1 && i == 0)
5485 MyFlags.setSplit();
5486 else if (i != 0)
5487 MyFlags.setOrigAlign(1);
5488
5489 Ops.push_back(Parts[i]);
5490 Ops.push_back(DAG.getArgFlags(MyFlags));
5491 }
5492 }
5493 }
5494
5495 // Figure out the result value types. We start by making a list of
5496 // the potentially illegal return value types.
5497 SmallVector<MVT, 4> LoweredRetTys;
5498 SmallVector<MVT, 4> RetTys;
5499 ComputeValueVTs(*this, RetTy, RetTys);
5500
5501 // Then we translate that to a list of legal types.
5502 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5503 MVT VT = RetTys[I];
5504 MVT RegisterVT = getRegisterType(VT);
5505 unsigned NumRegs = getNumRegisters(VT);
5506 for (unsigned i = 0; i != NumRegs; ++i)
5507 LoweredRetTys.push_back(RegisterVT);
5508 }
5509
5510 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
5511
5512 // Create the CALL node.
Dale Johannesen86098bd2008-09-26 19:31:26 +00005513 SDValue Res = DAG.getCall(CallingConv, isVarArg, isTailCall, isInreg,
Dan Gohman095cc292008-09-13 01:54:27 +00005514 DAG.getVTList(&LoweredRetTys[0],
5515 LoweredRetTys.size()),
Dale Johannesen86098bd2008-09-26 19:31:26 +00005516 &Ops[0], Ops.size()
5517 );
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005518 Chain = Res.getValue(LoweredRetTys.size() - 1);
5519
5520 // Gather up the call result into a single value.
Dan Gohmanb5cc34d2008-10-07 00:12:37 +00005521 if (RetTy != Type::VoidTy && !RetTys.empty()) {
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005522 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5523
5524 if (RetSExt)
5525 AssertOp = ISD::AssertSext;
5526 else if (RetZExt)
5527 AssertOp = ISD::AssertZext;
5528
5529 SmallVector<SDValue, 4> ReturnValues;
5530 unsigned RegNo = 0;
5531 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5532 MVT VT = RetTys[I];
5533 MVT RegisterVT = getRegisterType(VT);
5534 unsigned NumRegs = getNumRegisters(VT);
5535 unsigned RegNoEnd = NumRegs + RegNo;
5536 SmallVector<SDValue, 4> Results;
5537 for (; RegNo != RegNoEnd; ++RegNo)
5538 Results.push_back(Res.getValue(RegNo));
5539 SDValue ReturnValue =
5540 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
5541 AssertOp);
5542 ReturnValues.push_back(ReturnValue);
5543 }
Duncan Sandsaaffa052008-12-01 11:41:29 +00005544 Res = DAG.getNode(ISD::MERGE_VALUES,
5545 DAG.getVTList(&RetTys[0], RetTys.size()),
5546 &ReturnValues[0], ReturnValues.size());
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005547 }
5548
5549 return std::make_pair(Res, Chain);
5550}
5551
5552SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5553 assert(0 && "LowerOperation not implemented for this target!");
5554 abort();
5555 return SDValue();
5556}
5557
5558
5559void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5560 SDValue Op = getValue(V);
5561 assert((Op.getOpcode() != ISD::CopyFromReg ||
5562 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5563 "Copy from a reg to the same reg!");
5564 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5565
5566 RegsForValue RFV(TLI, Reg, V->getType());
5567 SDValue Chain = DAG.getEntryNode();
5568 RFV.getCopyToRegs(Op, DAG, Chain, 0);
5569 PendingExports.push_back(Chain);
5570}
5571
5572#include "llvm/CodeGen/SelectionDAGISel.h"
5573
5574void SelectionDAGISel::
5575LowerArguments(BasicBlock *LLVMBB) {
5576 // If this is the entry block, emit arguments.
5577 Function &F = *LLVMBB->getParent();
5578 SDValue OldRoot = SDL->DAG.getRoot();
5579 SmallVector<SDValue, 16> Args;
5580 TLI.LowerArguments(F, SDL->DAG, Args);
5581
5582 unsigned a = 0;
5583 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5584 AI != E; ++AI) {
5585 SmallVector<MVT, 4> ValueVTs;
5586 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5587 unsigned NumValues = ValueVTs.size();
5588 if (!AI->use_empty()) {
5589 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues));
5590 // If this argument is live outside of the entry block, insert a copy from
5591 // whereever we got it to the vreg that other BB's will reference it as.
5592 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5593 if (VMI != FuncInfo->ValueMap.end()) {
5594 SDL->CopyValueToVirtualRegister(AI, VMI->second);
5595 }
5596 }
5597 a += NumValues;
5598 }
5599
5600 // Finally, if the target has anything special to do, allow it to do so.
5601 // FIXME: this should insert code into the DAG!
5602 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5603}
5604
5605/// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5606/// ensure constants are generated when needed. Remember the virtual registers
5607/// that need to be added to the Machine PHI nodes as input. We cannot just
5608/// directly add them, because expansion might result in multiple MBB's for one
5609/// BB. As such, the start of the BB might correspond to a different MBB than
5610/// the end.
5611///
5612void
5613SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5614 TerminatorInst *TI = LLVMBB->getTerminator();
5615
5616 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5617
5618 // Check successor nodes' PHI nodes that expect a constant to be available
5619 // from this block.
5620 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5621 BasicBlock *SuccBB = TI->getSuccessor(succ);
5622 if (!isa<PHINode>(SuccBB->begin())) continue;
5623 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5624
5625 // If this terminator has multiple identical successors (common for
5626 // switches), only handle each succ once.
5627 if (!SuccsHandled.insert(SuccMBB)) continue;
5628
5629 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5630 PHINode *PN;
5631
5632 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5633 // nodes and Machine PHI nodes, but the incoming operands have not been
5634 // emitted yet.
5635 for (BasicBlock::iterator I = SuccBB->begin();
5636 (PN = dyn_cast<PHINode>(I)); ++I) {
5637 // Ignore dead phi's.
5638 if (PN->use_empty()) continue;
5639
5640 unsigned Reg;
5641 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5642
5643 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5644 unsigned &RegOut = SDL->ConstantsOut[C];
5645 if (RegOut == 0) {
5646 RegOut = FuncInfo->CreateRegForValue(C);
5647 SDL->CopyValueToVirtualRegister(C, RegOut);
5648 }
5649 Reg = RegOut;
5650 } else {
5651 Reg = FuncInfo->ValueMap[PHIOp];
5652 if (Reg == 0) {
5653 assert(isa<AllocaInst>(PHIOp) &&
5654 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5655 "Didn't codegen value into a register!??");
5656 Reg = FuncInfo->CreateRegForValue(PHIOp);
5657 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5658 }
5659 }
5660
5661 // Remember that this register needs to added to the machine PHI node as
5662 // the input for this MBB.
5663 SmallVector<MVT, 4> ValueVTs;
5664 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5665 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5666 MVT VT = ValueVTs[vti];
5667 unsigned NumRegisters = TLI.getNumRegisters(VT);
5668 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5669 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5670 Reg += NumRegisters;
5671 }
5672 }
5673 }
5674 SDL->ConstantsOut.clear();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005675}
5676
Dan Gohman3df24e62008-09-03 23:12:08 +00005677/// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5678/// supports legal types, and it emits MachineInstrs directly instead of
5679/// creating SelectionDAG nodes.
5680///
5681bool
5682SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5683 FastISel *F) {
5684 TerminatorInst *TI = LLVMBB->getTerminator();
Dan Gohmanf0cbcd42008-09-03 16:12:24 +00005685
Dan Gohman3df24e62008-09-03 23:12:08 +00005686 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5687 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5688
5689 // Check successor nodes' PHI nodes that expect a constant to be available
5690 // from this block.
5691 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5692 BasicBlock *SuccBB = TI->getSuccessor(succ);
5693 if (!isa<PHINode>(SuccBB->begin())) continue;
5694 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5695
5696 // If this terminator has multiple identical successors (common for
5697 // switches), only handle each succ once.
5698 if (!SuccsHandled.insert(SuccMBB)) continue;
5699
5700 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5701 PHINode *PN;
5702
5703 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5704 // nodes and Machine PHI nodes, but the incoming operands have not been
5705 // emitted yet.
5706 for (BasicBlock::iterator I = SuccBB->begin();
5707 (PN = dyn_cast<PHINode>(I)); ++I) {
5708 // Ignore dead phi's.
5709 if (PN->use_empty()) continue;
5710
5711 // Only handle legal types. Two interesting things to note here. First,
5712 // by bailing out early, we may leave behind some dead instructions,
5713 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5714 // own moves. Second, this check is necessary becuase FastISel doesn't
5715 // use CreateRegForValue to create registers, so it always creates
5716 // exactly one register for each non-void instruction.
5717 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5718 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
Dan Gohman74321ab2008-09-10 21:01:31 +00005719 // Promote MVT::i1.
5720 if (VT == MVT::i1)
5721 VT = TLI.getTypeToTransformTo(VT);
5722 else {
5723 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5724 return false;
5725 }
Dan Gohman3df24e62008-09-03 23:12:08 +00005726 }
5727
5728 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5729
5730 unsigned Reg = F->getRegForValue(PHIOp);
5731 if (Reg == 0) {
5732 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5733 return false;
5734 }
5735 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));
5736 }
5737 }
5738
5739 return true;
5740}