1 //===-- SelectionDAGBuild.cpp - Selection-DAG building --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements routines for translating from LLVM IR into SelectionDAG IR.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "isel"
15 #include "SelectionDAGBuild.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/SmallSet.h"
18 #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"
28 #include "llvm/CodeGen/FastISel.h"
29 #include "llvm/CodeGen/GCStrategy.h"
30 #include "llvm/CodeGen/GCMetadata.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/SelectionDAG.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Target/TargetFrameInfo.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/MathExtras.h"
51 /// LimitFloatPrecision - Generate low-precision inline sequences for
52 /// some float libcalls (6, 8 or 12 bits).
53 static unsigned LimitFloatPrecision;
55 static cl::opt<unsigned, true>
56 LimitFPPrecision("limit-float-precision",
57 cl::desc("Generate low-precision inline sequences "
58 "for some float libcalls"),
59 cl::location(LimitFloatPrecision),
62 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
63 /// insertvalue or extractvalue indices that identify a member, return
64 /// the linearized index of the start of the member.
66 static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
67 const unsigned *Indices,
68 const unsigned *IndicesEnd,
69 unsigned CurIndex = 0) {
70 // Base case: We're done.
71 if (Indices && Indices == IndicesEnd)
74 // Given a struct type, recursively traverse the elements.
75 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
76 for (StructType::element_iterator EB = STy->element_begin(),
78 EE = STy->element_end();
80 if (Indices && *Indices == unsigned(EI - EB))
81 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
82 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
85 // Given an array type, recursively traverse the elements.
86 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
87 const Type *EltTy = ATy->getElementType();
88 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
89 if (Indices && *Indices == i)
90 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
91 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
94 // We haven't found the type we're looking for, so keep searching.
98 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
99 /// MVTs that represent all the individual underlying
100 /// non-aggregate types that comprise it.
102 /// If Offsets is non-null, it points to a vector to be filled in
103 /// with the in-memory offsets of each of the individual values.
105 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
106 SmallVectorImpl<MVT> &ValueVTs,
107 SmallVectorImpl<uint64_t> *Offsets = 0,
108 uint64_t StartingOffset = 0) {
109 // Given a struct type, recursively traverse the elements.
110 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
111 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
112 for (StructType::element_iterator EB = STy->element_begin(),
114 EE = STy->element_end();
116 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
117 StartingOffset + SL->getElementOffset(EI - EB));
120 // Given an array type, recursively traverse the elements.
121 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
122 const Type *EltTy = ATy->getElementType();
123 uint64_t EltSize = TLI.getTargetData()->getABITypeSize(EltTy);
124 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
125 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
126 StartingOffset + i * EltSize);
129 // Base case: we can get an MVT for this LLVM IR type.
130 ValueVTs.push_back(TLI.getValueType(Ty));
132 Offsets->push_back(StartingOffset);
136 /// RegsForValue - This struct represents the registers (physical or virtual)
137 /// that a particular set of values is assigned, and the type information about
138 /// the value. The most common situation is to represent one value at a time,
139 /// but struct or array values are handled element-wise as multiple values.
140 /// The splitting of aggregates is performed recursively, so that we never
141 /// have aggregate-typed registers. The values at this point do not necessarily
142 /// have legal types, so each value may require one or more registers of some
145 struct VISIBILITY_HIDDEN RegsForValue {
146 /// TLI - The TargetLowering object.
148 const TargetLowering *TLI;
150 /// ValueVTs - The value types of the values, which may not be legal, and
151 /// may need be promoted or synthesized from one or more registers.
153 SmallVector<MVT, 4> ValueVTs;
155 /// RegVTs - The value types of the registers. This is the same size as
156 /// ValueVTs and it records, for each value, what the type of the assigned
157 /// register or registers are. (Individual values are never synthesized
158 /// from more than one type of register.)
160 /// With virtual registers, the contents of RegVTs is redundant with TLI's
161 /// getRegisterType member function, however when with physical registers
162 /// it is necessary to have a separate record of the types.
164 SmallVector<MVT, 4> RegVTs;
166 /// Regs - This list holds the registers assigned to the values.
167 /// Each legal or promoted value requires one register, and each
168 /// expanded value requires multiple registers.
170 SmallVector<unsigned, 4> Regs;
172 RegsForValue() : TLI(0) {}
174 RegsForValue(const TargetLowering &tli,
175 const SmallVector<unsigned, 4> ®s,
176 MVT regvt, MVT valuevt)
177 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
178 RegsForValue(const TargetLowering &tli,
179 const SmallVector<unsigned, 4> ®s,
180 const SmallVector<MVT, 4> ®vts,
181 const SmallVector<MVT, 4> &valuevts)
182 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
183 RegsForValue(const TargetLowering &tli,
184 unsigned Reg, const Type *Ty) : TLI(&tli) {
185 ComputeValueVTs(tli, Ty, ValueVTs);
187 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
188 MVT ValueVT = ValueVTs[Value];
189 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
190 MVT RegisterVT = TLI->getRegisterType(ValueVT);
191 for (unsigned i = 0; i != NumRegs; ++i)
192 Regs.push_back(Reg + i);
193 RegVTs.push_back(RegisterVT);
198 /// append - Add the specified values to this one.
199 void append(const RegsForValue &RHS) {
201 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
202 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
203 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
207 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
208 /// this value and returns the result as a ValueVTs value. This uses
209 /// Chain/Flag as the input and updates them for the output Chain/Flag.
210 /// If the Flag pointer is NULL, no flag is used.
211 SDValue getCopyFromRegs(SelectionDAG &DAG,
212 SDValue &Chain, SDValue *Flag) const;
214 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
215 /// specified value into the registers specified by this object. This uses
216 /// Chain/Flag as the input and updates them for the output Chain/Flag.
217 /// If the Flag pointer is NULL, no flag is used.
218 void getCopyToRegs(SDValue Val, SelectionDAG &DAG,
219 SDValue &Chain, SDValue *Flag) const;
221 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
222 /// operand list. This adds the code marker and includes the number of
223 /// values added into it.
224 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
225 std::vector<SDValue> &Ops) const;
229 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
230 /// PHI nodes or outside of the basic block that defines it, or used by a
231 /// switch or atomic instruction, which may expand to multiple basic blocks.
232 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
233 if (isa<PHINode>(I)) return true;
234 BasicBlock *BB = I->getParent();
235 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
236 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
237 // FIXME: Remove switchinst special case.
238 isa<SwitchInst>(*UI))
243 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
244 /// entry block, return true. This includes arguments used by switches, since
245 /// the switch may expand into multiple basic blocks.
246 static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
247 // With FastISel active, we may be splitting blocks, so force creation
248 // of virtual registers for all non-dead arguments.
249 // Don't force virtual registers for byval arguments though, because
250 // fast-isel can't handle those in all cases.
251 if (EnableFastISel && !A->hasByValAttr())
252 return A->use_empty();
254 BasicBlock *Entry = A->getParent()->begin();
255 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
256 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
257 return false; // Use not in entry block.
261 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
265 void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
266 bool EnableFastISel) {
269 RegInfo = &MF->getRegInfo();
271 // Create a vreg for each argument register that is not dead and is used
272 // outside of the entry block for the function.
273 for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
275 if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
276 InitializeRegForValue(AI);
278 // Initialize the mapping of values to registers. This is only set up for
279 // instruction values that are used outside of the block that defines
281 Function::iterator BB = Fn->begin(), EB = Fn->end();
282 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
283 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
284 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
285 const Type *Ty = AI->getAllocatedType();
286 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
288 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
291 TySize *= CUI->getZExtValue(); // Get total allocated size.
292 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
293 StaticAllocaMap[AI] =
294 MF->getFrameInfo()->CreateStackObject(TySize, Align);
297 for (; BB != EB; ++BB)
298 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
299 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
300 if (!isa<AllocaInst>(I) ||
301 !StaticAllocaMap.count(cast<AllocaInst>(I)))
302 InitializeRegForValue(I);
304 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
305 // also creates the initial PHI MachineInstrs, though none of the input
306 // operands are populated.
307 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
308 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
312 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
315 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
316 if (PN->use_empty()) continue;
318 unsigned PHIReg = ValueMap[PN];
319 assert(PHIReg && "PHI node does not have an assigned virtual register!");
321 SmallVector<MVT, 4> ValueVTs;
322 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
323 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
324 MVT VT = ValueVTs[vti];
325 unsigned NumRegisters = TLI.getNumRegisters(VT);
326 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
327 for (unsigned i = 0; i != NumRegisters; ++i)
328 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
329 PHIReg += NumRegisters;
335 unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
336 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
339 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
340 /// the correctly promoted or expanded types. Assign these registers
341 /// consecutive vreg numbers and return the first assigned number.
343 /// In the case that the given value has struct or array type, this function
344 /// will assign registers for each member or element.
346 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
347 SmallVector<MVT, 4> ValueVTs;
348 ComputeValueVTs(TLI, V->getType(), ValueVTs);
350 unsigned FirstReg = 0;
351 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
352 MVT ValueVT = ValueVTs[Value];
353 MVT RegisterVT = TLI.getRegisterType(ValueVT);
355 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
356 for (unsigned i = 0; i != NumRegs; ++i) {
357 unsigned R = MakeReg(RegisterVT);
358 if (!FirstReg) FirstReg = R;
364 /// getCopyFromParts - Create a value that contains the specified legal parts
365 /// combined into the value they represent. If the parts combine to a type
366 /// larger then ValueVT then AssertOp can be used to specify whether the extra
367 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
368 /// (ISD::AssertSext).
369 static SDValue getCopyFromParts(SelectionDAG &DAG,
370 const SDValue *Parts,
374 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
375 assert(NumParts > 0 && "No parts to assemble!");
376 TargetLowering &TLI = DAG.getTargetLoweringInfo();
377 SDValue Val = Parts[0];
380 // Assemble the value from multiple parts.
381 if (!ValueVT.isVector()) {
382 unsigned PartBits = PartVT.getSizeInBits();
383 unsigned ValueBits = ValueVT.getSizeInBits();
385 // Assemble the power of 2 part.
386 unsigned RoundParts = NumParts & (NumParts - 1) ?
387 1 << Log2_32(NumParts) : NumParts;
388 unsigned RoundBits = PartBits * RoundParts;
389 MVT RoundVT = RoundBits == ValueBits ?
390 ValueVT : MVT::getIntegerVT(RoundBits);
393 if (RoundParts > 2) {
394 MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
395 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
396 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
402 if (TLI.isBigEndian())
404 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
406 if (RoundParts < NumParts) {
407 // Assemble the trailing non-power-of-2 part.
408 unsigned OddParts = NumParts - RoundParts;
409 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
410 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
412 // Combine the round and odd parts.
414 if (TLI.isBigEndian())
416 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
417 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
418 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
419 DAG.getConstant(Lo.getValueType().getSizeInBits(),
420 TLI.getShiftAmountTy()));
421 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
422 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
425 // Handle a multi-element vector.
426 MVT IntermediateVT, RegisterVT;
427 unsigned NumIntermediates;
429 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
431 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
432 NumParts = NumRegs; // Silence a compiler warning.
433 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
434 assert(RegisterVT == Parts[0].getValueType() &&
435 "Part type doesn't match part!");
437 // Assemble the parts into intermediate operands.
438 SmallVector<SDValue, 8> Ops(NumIntermediates);
439 if (NumIntermediates == NumParts) {
440 // If the register was not expanded, truncate or copy the value,
442 for (unsigned i = 0; i != NumParts; ++i)
443 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
444 PartVT, IntermediateVT);
445 } else if (NumParts > 0) {
446 // If the intermediate type was expanded, build the intermediate operands
448 assert(NumParts % NumIntermediates == 0 &&
449 "Must expand into a divisible number of parts!");
450 unsigned Factor = NumParts / NumIntermediates;
451 for (unsigned i = 0; i != NumIntermediates; ++i)
452 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
453 PartVT, IntermediateVT);
456 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
458 Val = DAG.getNode(IntermediateVT.isVector() ?
459 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
460 ValueVT, &Ops[0], NumIntermediates);
464 // There is now one part, held in Val. Correct it to match ValueVT.
465 PartVT = Val.getValueType();
467 if (PartVT == ValueVT)
470 if (PartVT.isVector()) {
471 assert(ValueVT.isVector() && "Unknown vector conversion!");
472 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
475 if (ValueVT.isVector()) {
476 assert(ValueVT.getVectorElementType() == PartVT &&
477 ValueVT.getVectorNumElements() == 1 &&
478 "Only trivial scalar-to-vector conversions should get here!");
479 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
482 if (PartVT.isInteger() &&
483 ValueVT.isInteger()) {
484 if (ValueVT.bitsLT(PartVT)) {
485 // For a truncate, see if we have any information to
486 // indicate whether the truncated bits will always be
487 // zero or sign-extension.
488 if (AssertOp != ISD::DELETED_NODE)
489 Val = DAG.getNode(AssertOp, PartVT, Val,
490 DAG.getValueType(ValueVT));
491 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
493 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
497 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
498 if (ValueVT.bitsLT(Val.getValueType()))
499 // FP_ROUND's are always exact here.
500 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
501 DAG.getIntPtrConstant(1));
502 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
505 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
506 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
508 assert(0 && "Unknown mismatch!");
512 /// getCopyToParts - Create a series of nodes that contain the specified value
513 /// split into legal parts. If the parts contain more bits than Val, then, for
514 /// integers, ExtendKind can be used to specify how to generate the extra bits.
515 static void getCopyToParts(SelectionDAG &DAG, SDValue Val,
516 SDValue *Parts, unsigned NumParts, MVT PartVT,
517 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
518 TargetLowering &TLI = DAG.getTargetLoweringInfo();
519 MVT PtrVT = TLI.getPointerTy();
520 MVT ValueVT = Val.getValueType();
521 unsigned PartBits = PartVT.getSizeInBits();
522 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
527 if (!ValueVT.isVector()) {
528 if (PartVT == ValueVT) {
529 assert(NumParts == 1 && "No-op copy with multiple parts!");
534 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
535 // If the parts cover more bits than the value has, promote the value.
536 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
537 assert(NumParts == 1 && "Do not know what to promote to!");
538 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
539 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
540 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
541 Val = DAG.getNode(ExtendKind, ValueVT, Val);
543 assert(0 && "Unknown mismatch!");
545 } else if (PartBits == ValueVT.getSizeInBits()) {
546 // Different types of the same size.
547 assert(NumParts == 1 && PartVT != ValueVT);
548 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
549 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
550 // If the parts cover less bits than value has, truncate the value.
551 if (PartVT.isInteger() && ValueVT.isInteger()) {
552 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
553 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
555 assert(0 && "Unknown mismatch!");
559 // The value may have changed - recompute ValueVT.
560 ValueVT = Val.getValueType();
561 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
562 "Failed to tile the value with PartVT!");
565 assert(PartVT == ValueVT && "Type conversion failed!");
570 // Expand the value into multiple parts.
571 if (NumParts & (NumParts - 1)) {
572 // The number of parts is not a power of 2. Split off and copy the tail.
573 assert(PartVT.isInteger() && ValueVT.isInteger() &&
574 "Do not know what to expand to!");
575 unsigned RoundParts = 1 << Log2_32(NumParts);
576 unsigned RoundBits = RoundParts * PartBits;
577 unsigned OddParts = NumParts - RoundParts;
578 SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
579 DAG.getConstant(RoundBits,
580 TLI.getShiftAmountTy()));
581 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
582 if (TLI.isBigEndian())
583 // The odd parts were reversed by getCopyToParts - unreverse them.
584 std::reverse(Parts + RoundParts, Parts + NumParts);
585 NumParts = RoundParts;
586 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
587 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
590 // The number of parts is a power of 2. Repeatedly bisect the value using
592 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
593 MVT::getIntegerVT(ValueVT.getSizeInBits()),
595 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
596 for (unsigned i = 0; i < NumParts; i += StepSize) {
597 unsigned ThisBits = StepSize * PartBits / 2;
598 MVT ThisVT = MVT::getIntegerVT (ThisBits);
599 SDValue &Part0 = Parts[i];
600 SDValue &Part1 = Parts[i+StepSize/2];
602 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
603 DAG.getConstant(1, PtrVT));
604 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
605 DAG.getConstant(0, PtrVT));
607 if (ThisBits == PartBits && ThisVT != PartVT) {
608 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
609 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
614 if (TLI.isBigEndian())
615 std::reverse(Parts, Parts + NumParts);
622 if (PartVT != ValueVT) {
623 if (PartVT.isVector()) {
624 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
626 assert(ValueVT.getVectorElementType() == PartVT &&
627 ValueVT.getVectorNumElements() == 1 &&
628 "Only trivial vector-to-scalar conversions should get here!");
629 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
630 DAG.getConstant(0, PtrVT));
638 // Handle a multi-element vector.
639 MVT IntermediateVT, RegisterVT;
640 unsigned NumIntermediates;
642 DAG.getTargetLoweringInfo()
643 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
645 unsigned NumElements = ValueVT.getVectorNumElements();
647 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
648 NumParts = NumRegs; // Silence a compiler warning.
649 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
651 // Split the vector into intermediate operands.
652 SmallVector<SDValue, 8> Ops(NumIntermediates);
653 for (unsigned i = 0; i != NumIntermediates; ++i)
654 if (IntermediateVT.isVector())
655 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
657 DAG.getConstant(i * (NumElements / NumIntermediates),
660 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
662 DAG.getConstant(i, PtrVT));
664 // Split the intermediate operands into legal parts.
665 if (NumParts == NumIntermediates) {
666 // If the register was not expanded, promote or copy the value,
668 for (unsigned i = 0; i != NumParts; ++i)
669 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
670 } else if (NumParts > 0) {
671 // If the intermediate type was expanded, split each the value into
673 assert(NumParts % NumIntermediates == 0 &&
674 "Must expand into a divisible number of parts!");
675 unsigned Factor = NumParts / NumIntermediates;
676 for (unsigned i = 0; i != NumIntermediates; ++i)
677 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
682 void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
685 TD = DAG.getTarget().getTargetData();
688 /// clear - Clear out the curret SelectionDAG and the associated
689 /// state and prepare this SelectionDAGLowering object to be used
690 /// for a new block. This doesn't clear out information about
691 /// additional blocks that are needed to complete switch lowering
692 /// or PHI node updating; that information is cleared out as it is
694 void SelectionDAGLowering::clear() {
696 PendingLoads.clear();
697 PendingExports.clear();
701 /// getRoot - Return the current virtual root of the Selection DAG,
702 /// flushing any PendingLoad items. This must be done before emitting
703 /// a store or any other node that may need to be ordered after any
704 /// prior load instructions.
706 SDValue SelectionDAGLowering::getRoot() {
707 if (PendingLoads.empty())
708 return DAG.getRoot();
710 if (PendingLoads.size() == 1) {
711 SDValue Root = PendingLoads[0];
713 PendingLoads.clear();
717 // Otherwise, we have to make a token factor node.
718 SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
719 &PendingLoads[0], PendingLoads.size());
720 PendingLoads.clear();
725 /// getControlRoot - Similar to getRoot, but instead of flushing all the
726 /// PendingLoad items, flush all the PendingExports items. It is necessary
727 /// to do this before emitting a terminator instruction.
729 SDValue SelectionDAGLowering::getControlRoot() {
730 SDValue Root = DAG.getRoot();
732 if (PendingExports.empty())
735 // Turn all of the CopyToReg chains into one factored node.
736 if (Root.getOpcode() != ISD::EntryToken) {
737 unsigned i = 0, e = PendingExports.size();
738 for (; i != e; ++i) {
739 assert(PendingExports[i].getNode()->getNumOperands() > 1);
740 if (PendingExports[i].getNode()->getOperand(0) == Root)
741 break; // Don't add the root if we already indirectly depend on it.
745 PendingExports.push_back(Root);
748 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
750 PendingExports.size());
751 PendingExports.clear();
756 void SelectionDAGLowering::visit(Instruction &I) {
757 visit(I.getOpcode(), I);
760 void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
761 // Note: this doesn't use InstVisitor, because it has to work with
762 // ConstantExpr's in addition to instructions.
764 default: assert(0 && "Unknown instruction type encountered!");
766 // Build the switch statement using the Instruction.def file.
767 #define HANDLE_INST(NUM, OPCODE, CLASS) \
768 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
769 #include "llvm/Instruction.def"
773 void SelectionDAGLowering::visitAdd(User &I) {
774 if (I.getType()->isFPOrFPVector())
775 visitBinary(I, ISD::FADD);
777 visitBinary(I, ISD::ADD);
780 void SelectionDAGLowering::visitMul(User &I) {
781 if (I.getType()->isFPOrFPVector())
782 visitBinary(I, ISD::FMUL);
784 visitBinary(I, ISD::MUL);
787 SDValue SelectionDAGLowering::getValue(const Value *V) {
788 SDValue &N = NodeMap[V];
789 if (N.getNode()) return N;
791 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
792 MVT VT = TLI.getValueType(V->getType(), true);
794 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
795 return N = DAG.getConstant(*CI, VT);
797 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
798 return N = DAG.getGlobalAddress(GV, VT);
800 if (isa<ConstantPointerNull>(C))
801 return N = DAG.getConstant(0, TLI.getPointerTy());
803 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
804 return N = DAG.getConstantFP(*CFP, VT);
806 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
807 !V->getType()->isAggregateType())
808 return N = DAG.getNode(ISD::UNDEF, VT);
810 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
811 visit(CE->getOpcode(), *CE);
812 SDValue N1 = NodeMap[V];
813 assert(N1.getNode() && "visit didn't populate the ValueMap!");
817 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
818 SmallVector<SDValue, 4> Constants;
819 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
821 SDNode *Val = getValue(*OI).getNode();
822 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
823 Constants.push_back(SDValue(Val, i));
825 return DAG.getMergeValues(&Constants[0], Constants.size());
828 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
829 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
830 "Unknown struct or array constant!");
832 SmallVector<MVT, 4> ValueVTs;
833 ComputeValueVTs(TLI, C->getType(), ValueVTs);
834 unsigned NumElts = ValueVTs.size();
836 return SDValue(); // empty struct
837 SmallVector<SDValue, 4> Constants(NumElts);
838 for (unsigned i = 0; i != NumElts; ++i) {
839 MVT EltVT = ValueVTs[i];
840 if (isa<UndefValue>(C))
841 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
842 else if (EltVT.isFloatingPoint())
843 Constants[i] = DAG.getConstantFP(0, EltVT);
845 Constants[i] = DAG.getConstant(0, EltVT);
847 return DAG.getMergeValues(&Constants[0], NumElts);
850 const VectorType *VecTy = cast<VectorType>(V->getType());
851 unsigned NumElements = VecTy->getNumElements();
853 // Now that we know the number and type of the elements, get that number of
854 // elements into the Ops array based on what kind of constant it is.
855 SmallVector<SDValue, 16> Ops;
856 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
857 for (unsigned i = 0; i != NumElements; ++i)
858 Ops.push_back(getValue(CP->getOperand(i)));
860 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
861 "Unknown vector constant!");
862 MVT EltVT = TLI.getValueType(VecTy->getElementType());
865 if (isa<UndefValue>(C))
866 Op = DAG.getNode(ISD::UNDEF, EltVT);
867 else if (EltVT.isFloatingPoint())
868 Op = DAG.getConstantFP(0, EltVT);
870 Op = DAG.getConstant(0, EltVT);
871 Ops.assign(NumElements, Op);
874 // Create a BUILD_VECTOR node.
875 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
878 // If this is a static alloca, generate it as the frameindex instead of
880 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
881 DenseMap<const AllocaInst*, int>::iterator SI =
882 FuncInfo.StaticAllocaMap.find(AI);
883 if (SI != FuncInfo.StaticAllocaMap.end())
884 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
887 unsigned InReg = FuncInfo.ValueMap[V];
888 assert(InReg && "Value not in map!");
890 RegsForValue RFV(TLI, InReg, V->getType());
891 SDValue Chain = DAG.getEntryNode();
892 return RFV.getCopyFromRegs(DAG, Chain, NULL);
896 void SelectionDAGLowering::visitRet(ReturnInst &I) {
897 if (I.getNumOperands() == 0) {
898 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
902 SmallVector<SDValue, 8> NewValues;
903 NewValues.push_back(getControlRoot());
904 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
905 SmallVector<MVT, 4> ValueVTs;
906 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
907 unsigned NumValues = ValueVTs.size();
908 if (NumValues == 0) continue;
910 SDValue RetOp = getValue(I.getOperand(i));
911 for (unsigned j = 0, f = NumValues; j != f; ++j) {
912 MVT VT = ValueVTs[j];
914 // FIXME: C calling convention requires the return type to be promoted to
915 // at least 32-bit. But this is not necessary for non-C calling
917 if (VT.isInteger()) {
918 MVT MinVT = TLI.getRegisterType(MVT::i32);
919 if (VT.bitsLT(MinVT))
923 unsigned NumParts = TLI.getNumRegisters(VT);
924 MVT PartVT = TLI.getRegisterType(VT);
925 SmallVector<SDValue, 4> Parts(NumParts);
926 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
928 const Function *F = I.getParent()->getParent();
929 if (F->paramHasAttr(0, Attribute::SExt))
930 ExtendKind = ISD::SIGN_EXTEND;
931 else if (F->paramHasAttr(0, Attribute::ZExt))
932 ExtendKind = ISD::ZERO_EXTEND;
934 getCopyToParts(DAG, SDValue(RetOp.getNode(), RetOp.getResNo() + j),
935 &Parts[0], NumParts, PartVT, ExtendKind);
937 // 'inreg' on function refers to return value
938 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
939 if (F->paramHasAttr(0, Attribute::InReg))
941 for (unsigned i = 0; i < NumParts; ++i) {
942 NewValues.push_back(Parts[i]);
943 NewValues.push_back(DAG.getArgFlags(Flags));
947 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
948 &NewValues[0], NewValues.size()));
951 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
952 /// the current basic block, add it to ValueMap now so that we'll get a
954 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
955 // No need to export constants.
956 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
959 if (FuncInfo.isExportedInst(V)) return;
961 unsigned Reg = FuncInfo.InitializeRegForValue(V);
962 CopyValueToVirtualRegister(V, Reg);
965 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
966 const BasicBlock *FromBB) {
967 // The operands of the setcc have to be in this block. We don't know
968 // how to export them from some other block.
969 if (Instruction *VI = dyn_cast<Instruction>(V)) {
970 // Can export from current BB.
971 if (VI->getParent() == FromBB)
974 // Is already exported, noop.
975 return FuncInfo.isExportedInst(V);
978 // If this is an argument, we can export it if the BB is the entry block or
979 // if it is already exported.
980 if (isa<Argument>(V)) {
981 if (FromBB == &FromBB->getParent()->getEntryBlock())
984 // Otherwise, can only export this if it is already exported.
985 return FuncInfo.isExportedInst(V);
988 // Otherwise, constants can always be exported.
992 static bool InBlock(const Value *V, const BasicBlock *BB) {
993 if (const Instruction *I = dyn_cast<Instruction>(V))
994 return I->getParent() == BB;
998 /// getFCmpCondCode - Return the ISD condition code corresponding to
999 /// the given LLVM IR floating-point condition code. This includes
1000 /// consideration of global floating-point math flags.
1002 static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1003 ISD::CondCode FPC, FOC;
1005 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1006 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1007 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1008 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1009 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1010 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1011 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1012 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1013 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1014 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1015 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1016 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1017 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1018 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1019 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1020 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1022 assert(0 && "Invalid FCmp predicate opcode!");
1023 FOC = FPC = ISD::SETFALSE;
1026 if (FiniteOnlyFPMath())
1032 /// getICmpCondCode - Return the ISD condition code corresponding to
1033 /// the given LLVM IR integer condition code.
1035 static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1037 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1038 case ICmpInst::ICMP_NE: return ISD::SETNE;
1039 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1040 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1041 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1042 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1043 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1044 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1045 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1046 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1048 assert(0 && "Invalid ICmp predicate opcode!");
1053 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1054 /// This function emits a branch and is used at the leaves of an OR or an
1055 /// AND operator tree.
1058 SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1059 MachineBasicBlock *TBB,
1060 MachineBasicBlock *FBB,
1061 MachineBasicBlock *CurBB) {
1062 const BasicBlock *BB = CurBB->getBasicBlock();
1064 // If the leaf of the tree is a comparison, merge the condition into
1066 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1067 // The operands of the cmp have to be in this block. We don't know
1068 // how to export them from some other block. If this is the first block
1069 // of the sequence, no exporting is needed.
1070 if (CurBB == CurMBB ||
1071 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1072 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1073 ISD::CondCode Condition;
1074 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1075 Condition = getICmpCondCode(IC->getPredicate());
1076 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1077 Condition = getFCmpCondCode(FC->getPredicate());
1079 Condition = ISD::SETEQ; // silence warning.
1080 assert(0 && "Unknown compare instruction");
1083 CaseBlock CB(Condition, BOp->getOperand(0),
1084 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1085 SwitchCases.push_back(CB);
1090 // Create a CaseBlock record representing this branch.
1091 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1092 NULL, TBB, FBB, CurBB);
1093 SwitchCases.push_back(CB);
1096 /// FindMergedConditions - If Cond is an expression like
1097 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1098 MachineBasicBlock *TBB,
1099 MachineBasicBlock *FBB,
1100 MachineBasicBlock *CurBB,
1102 // If this node is not part of the or/and tree, emit it as a branch.
1103 Instruction *BOp = dyn_cast<Instruction>(Cond);
1104 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1105 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1106 BOp->getParent() != CurBB->getBasicBlock() ||
1107 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1108 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1109 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
1113 // Create TmpBB after CurBB.
1114 MachineFunction::iterator BBI = CurBB;
1115 MachineFunction &MF = DAG.getMachineFunction();
1116 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1117 CurBB->getParent()->insert(++BBI, TmpBB);
1119 if (Opc == Instruction::Or) {
1120 // Codegen X | Y as:
1128 // Emit the LHS condition.
1129 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1131 // Emit the RHS condition into TmpBB.
1132 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1134 assert(Opc == Instruction::And && "Unknown merge op!");
1135 // Codegen X & Y as:
1142 // This requires creation of TmpBB after CurBB.
1144 // Emit the LHS condition.
1145 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1147 // Emit the RHS condition into TmpBB.
1148 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1152 /// If the set of cases should be emitted as a series of branches, return true.
1153 /// If we should emit this as a bunch of and/or'd together conditions, return
1156 SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1157 if (Cases.size() != 2) return true;
1159 // If this is two comparisons of the same values or'd or and'd together, they
1160 // will get folded into a single comparison, so don't emit two blocks.
1161 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1162 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1163 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1164 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1171 void SelectionDAGLowering::visitBr(BranchInst &I) {
1172 // Update machine-CFG edges.
1173 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1175 // Figure out which block is immediately after the current one.
1176 MachineBasicBlock *NextBlock = 0;
1177 MachineFunction::iterator BBI = CurMBB;
1178 if (++BBI != CurMBB->getParent()->end())
1181 if (I.isUnconditional()) {
1182 // Update machine-CFG edges.
1183 CurMBB->addSuccessor(Succ0MBB);
1185 // If this is not a fall-through branch, emit the branch.
1186 if (Succ0MBB != NextBlock)
1187 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1188 DAG.getBasicBlock(Succ0MBB)));
1192 // If this condition is one of the special cases we handle, do special stuff
1194 Value *CondVal = I.getCondition();
1195 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1197 // If this is a series of conditions that are or'd or and'd together, emit
1198 // this as a sequence of branches instead of setcc's with and/or operations.
1199 // For example, instead of something like:
1212 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1213 if (BOp->hasOneUse() &&
1214 (BOp->getOpcode() == Instruction::And ||
1215 BOp->getOpcode() == Instruction::Or)) {
1216 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1217 // If the compares in later blocks need to use values not currently
1218 // exported from this block, export them now. This block should always
1219 // be the first entry.
1220 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1222 // Allow some cases to be rejected.
1223 if (ShouldEmitAsBranches(SwitchCases)) {
1224 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1225 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1226 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1229 // Emit the branch for this block.
1230 visitSwitchCase(SwitchCases[0]);
1231 SwitchCases.erase(SwitchCases.begin());
1235 // Okay, we decided not to do this, remove any inserted MBB's and clear
1237 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1238 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
1240 SwitchCases.clear();
1244 // Create a CaseBlock record representing this branch.
1245 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1246 NULL, Succ0MBB, Succ1MBB, CurMBB);
1247 // Use visitSwitchCase to actually insert the fast branch sequence for this
1249 visitSwitchCase(CB);
1252 /// visitSwitchCase - Emits the necessary code to represent a single node in
1253 /// the binary search tree resulting from lowering a switch instruction.
1254 void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1256 SDValue CondLHS = getValue(CB.CmpLHS);
1258 // Build the setcc now.
1259 if (CB.CmpMHS == NULL) {
1260 // Fold "(X == true)" to X and "(X == false)" to !X to
1261 // handle common cases produced by branch lowering.
1262 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1264 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1265 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1266 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1268 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1270 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1272 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1273 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1275 SDValue CmpOp = getValue(CB.CmpMHS);
1276 MVT VT = CmpOp.getValueType();
1278 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1279 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1281 SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1282 Cond = DAG.getSetCC(MVT::i1, SUB,
1283 DAG.getConstant(High-Low, VT), ISD::SETULE);
1287 // Update successor info
1288 CurMBB->addSuccessor(CB.TrueBB);
1289 CurMBB->addSuccessor(CB.FalseBB);
1291 // Set NextBlock to be the MBB immediately after the current one, if any.
1292 // This is used to avoid emitting unnecessary branches to the next block.
1293 MachineBasicBlock *NextBlock = 0;
1294 MachineFunction::iterator BBI = CurMBB;
1295 if (++BBI != CurMBB->getParent()->end())
1298 // If the lhs block is the next block, invert the condition so that we can
1299 // fall through to the lhs instead of the rhs block.
1300 if (CB.TrueBB == NextBlock) {
1301 std::swap(CB.TrueBB, CB.FalseBB);
1302 SDValue True = DAG.getConstant(1, Cond.getValueType());
1303 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1305 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1306 DAG.getBasicBlock(CB.TrueBB));
1308 // If the branch was constant folded, fix up the CFG.
1309 if (BrCond.getOpcode() == ISD::BR) {
1310 CurMBB->removeSuccessor(CB.FalseBB);
1311 DAG.setRoot(BrCond);
1313 // Otherwise, go ahead and insert the false branch.
1314 if (BrCond == getControlRoot())
1315 CurMBB->removeSuccessor(CB.TrueBB);
1317 if (CB.FalseBB == NextBlock)
1318 DAG.setRoot(BrCond);
1320 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1321 DAG.getBasicBlock(CB.FalseBB)));
1325 /// visitJumpTable - Emit JumpTable node in the current MBB
1326 void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1327 // Emit the code for the jump table
1328 assert(JT.Reg != -1U && "Should lower JT Header first!");
1329 MVT PTy = TLI.getPointerTy();
1330 SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1331 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1332 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1337 /// visitJumpTableHeader - This function emits necessary code to produce index
1338 /// in the JumpTable from switch case.
1339 void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1340 JumpTableHeader &JTH) {
1341 // Subtract the lowest switch case value from the value being switched on
1342 // and conditional branch to default mbb if the result is greater than the
1343 // difference between smallest and largest cases.
1344 SDValue SwitchOp = getValue(JTH.SValue);
1345 MVT VT = SwitchOp.getValueType();
1346 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1347 DAG.getConstant(JTH.First, VT));
1349 // The SDNode we just created, which holds the value being switched on
1350 // minus the the smallest case value, needs to be copied to a virtual
1351 // register so it can be used as an index into the jump table in a
1352 // subsequent basic block. This value may be smaller or larger than the
1353 // target's pointer type, and therefore require extension or truncating.
1354 if (VT.bitsGT(TLI.getPointerTy()))
1355 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1357 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1359 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1360 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1361 JT.Reg = JumpTableReg;
1363 // Emit the range check for the jump table, and branch to the default
1364 // block for the switch statement if the value being switched on exceeds
1365 // the largest case in the switch.
1366 SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1367 DAG.getConstant(JTH.Last-JTH.First,VT),
1370 // Set NextBlock to be the MBB immediately after the current one, if any.
1371 // This is used to avoid emitting unnecessary branches to the next block.
1372 MachineBasicBlock *NextBlock = 0;
1373 MachineFunction::iterator BBI = CurMBB;
1374 if (++BBI != CurMBB->getParent()->end())
1377 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1378 DAG.getBasicBlock(JT.Default));
1380 if (JT.MBB == NextBlock)
1381 DAG.setRoot(BrCond);
1383 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1384 DAG.getBasicBlock(JT.MBB)));
1389 /// visitBitTestHeader - This function emits necessary code to produce value
1390 /// suitable for "bit tests"
1391 void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1392 // Subtract the minimum value
1393 SDValue SwitchOp = getValue(B.SValue);
1394 MVT VT = SwitchOp.getValueType();
1395 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1396 DAG.getConstant(B.First, VT));
1399 SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1400 DAG.getConstant(B.Range, VT),
1404 if (VT.bitsGT(TLI.getShiftAmountTy()))
1405 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1407 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1409 // Make desired shift
1410 SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1411 DAG.getConstant(1, TLI.getPointerTy()),
1414 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1415 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1418 // Set NextBlock to be the MBB immediately after the current one, if any.
1419 // This is used to avoid emitting unnecessary branches to the next block.
1420 MachineBasicBlock *NextBlock = 0;
1421 MachineFunction::iterator BBI = CurMBB;
1422 if (++BBI != CurMBB->getParent()->end())
1425 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1427 CurMBB->addSuccessor(B.Default);
1428 CurMBB->addSuccessor(MBB);
1430 SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1431 DAG.getBasicBlock(B.Default));
1433 if (MBB == NextBlock)
1434 DAG.setRoot(BrRange);
1436 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1437 DAG.getBasicBlock(MBB)));
1442 /// visitBitTestCase - this function produces one "bit test"
1443 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1446 // Emit bit tests and jumps
1447 SDValue SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg,
1448 TLI.getPointerTy());
1450 SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
1451 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1452 SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1453 DAG.getConstant(0, TLI.getPointerTy()),
1456 CurMBB->addSuccessor(B.TargetBB);
1457 CurMBB->addSuccessor(NextMBB);
1459 SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1460 AndCmp, DAG.getBasicBlock(B.TargetBB));
1462 // Set NextBlock to be the MBB immediately after the current one, if any.
1463 // This is used to avoid emitting unnecessary branches to the next block.
1464 MachineBasicBlock *NextBlock = 0;
1465 MachineFunction::iterator BBI = CurMBB;
1466 if (++BBI != CurMBB->getParent()->end())
1469 if (NextMBB == NextBlock)
1472 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1473 DAG.getBasicBlock(NextMBB)));
1478 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1479 // Retrieve successors.
1480 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1481 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1483 if (isa<InlineAsm>(I.getCalledValue()))
1486 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1488 // If the value of the invoke is used outside of its defining block, make it
1489 // available as a virtual register.
1490 if (!I.use_empty()) {
1491 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1492 if (VMI != FuncInfo.ValueMap.end())
1493 CopyValueToVirtualRegister(&I, VMI->second);
1496 // Update successor info
1497 CurMBB->addSuccessor(Return);
1498 CurMBB->addSuccessor(LandingPad);
1500 // Drop into normal successor.
1501 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1502 DAG.getBasicBlock(Return)));
1505 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1508 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1509 /// small case ranges).
1510 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1511 CaseRecVector& WorkList,
1513 MachineBasicBlock* Default) {
1514 Case& BackCase = *(CR.Range.second-1);
1516 // Size is the number of Cases represented by this range.
1517 unsigned Size = CR.Range.second - CR.Range.first;
1521 // Get the MachineFunction which holds the current MBB. This is used when
1522 // inserting any additional MBBs necessary to represent the switch.
1523 MachineFunction *CurMF = CurMBB->getParent();
1525 // Figure out which block is immediately after the current one.
1526 MachineBasicBlock *NextBlock = 0;
1527 MachineFunction::iterator BBI = CR.CaseBB;
1529 if (++BBI != CurMBB->getParent()->end())
1532 // TODO: If any two of the cases has the same destination, and if one value
1533 // is the same as the other, but has one bit unset that the other has set,
1534 // use bit manipulation to do two compares at once. For example:
1535 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1537 // Rearrange the case blocks so that the last one falls through if possible.
1538 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1539 // The last case block won't fall through into 'NextBlock' if we emit the
1540 // branches in this order. See if rearranging a case value would help.
1541 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1542 if (I->BB == NextBlock) {
1543 std::swap(*I, BackCase);
1549 // Create a CaseBlock record representing a conditional branch to
1550 // the Case's target mbb if the value being switched on SV is equal
1552 MachineBasicBlock *CurBlock = CR.CaseBB;
1553 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1554 MachineBasicBlock *FallThrough;
1556 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1557 CurMF->insert(BBI, FallThrough);
1559 // If the last case doesn't match, go to the default block.
1560 FallThrough = Default;
1563 Value *RHS, *LHS, *MHS;
1565 if (I->High == I->Low) {
1566 // This is just small small case range :) containing exactly 1 case
1568 LHS = SV; RHS = I->High; MHS = NULL;
1571 LHS = I->Low; MHS = SV; RHS = I->High;
1573 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1575 // If emitting the first comparison, just call visitSwitchCase to emit the
1576 // code into the current block. Otherwise, push the CaseBlock onto the
1577 // vector to be later processed by SDISel, and insert the node's MBB
1578 // before the next MBB.
1579 if (CurBlock == CurMBB)
1580 visitSwitchCase(CB);
1582 SwitchCases.push_back(CB);
1584 CurBlock = FallThrough;
1590 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1591 return !DisableJumpTables &&
1592 (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1593 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1596 /// handleJTSwitchCase - Emit jumptable for current switch case range
1597 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1598 CaseRecVector& WorkList,
1600 MachineBasicBlock* Default) {
1601 Case& FrontCase = *CR.Range.first;
1602 Case& BackCase = *(CR.Range.second-1);
1604 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1605 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1608 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1612 if (!areJTsAllowed(TLI) || TSize <= 3)
1615 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1619 DOUT << "Lowering jump table\n"
1620 << "First entry: " << First << ". Last entry: " << Last << "\n"
1621 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1623 // Get the MachineFunction which holds the current MBB. This is used when
1624 // inserting any additional MBBs necessary to represent the switch.
1625 MachineFunction *CurMF = CurMBB->getParent();
1627 // Figure out which block is immediately after the current one.
1628 MachineBasicBlock *NextBlock = 0;
1629 MachineFunction::iterator BBI = CR.CaseBB;
1631 if (++BBI != CurMBB->getParent()->end())
1634 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1636 // Create a new basic block to hold the code for loading the address
1637 // of the jump table, and jumping to it. Update successor information;
1638 // we will either branch to the default case for the switch, or the jump
1640 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1641 CurMF->insert(BBI, JumpTableBB);
1642 CR.CaseBB->addSuccessor(Default);
1643 CR.CaseBB->addSuccessor(JumpTableBB);
1645 // Build a vector of destination BBs, corresponding to each target
1646 // of the jump table. If the value of the jump table slot corresponds to
1647 // a case statement, push the case's BB onto the vector, otherwise, push
1649 std::vector<MachineBasicBlock*> DestBBs;
1650 int64_t TEI = First;
1651 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1652 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1653 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1655 if ((Low <= TEI) && (TEI <= High)) {
1656 DestBBs.push_back(I->BB);
1660 DestBBs.push_back(Default);
1664 // Update successor info. Add one edge to each unique successor.
1665 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1666 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1667 E = DestBBs.end(); I != E; ++I) {
1668 if (!SuccsHandled[(*I)->getNumber()]) {
1669 SuccsHandled[(*I)->getNumber()] = true;
1670 JumpTableBB->addSuccessor(*I);
1674 // Create a jump table index for this jump table, or return an existing
1676 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1678 // Set the jump table information so that we can codegen it as a second
1679 // MachineBasicBlock
1680 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1681 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1682 if (CR.CaseBB == CurMBB)
1683 visitJumpTableHeader(JT, JTH);
1685 JTCases.push_back(JumpTableBlock(JTH, JT));
1690 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1692 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1693 CaseRecVector& WorkList,
1695 MachineBasicBlock* Default) {
1696 // Get the MachineFunction which holds the current MBB. This is used when
1697 // inserting any additional MBBs necessary to represent the switch.
1698 MachineFunction *CurMF = CurMBB->getParent();
1700 // Figure out which block is immediately after the current one.
1701 MachineBasicBlock *NextBlock = 0;
1702 MachineFunction::iterator BBI = CR.CaseBB;
1704 if (++BBI != CurMBB->getParent()->end())
1707 Case& FrontCase = *CR.Range.first;
1708 Case& BackCase = *(CR.Range.second-1);
1709 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1711 // Size is the number of Cases represented by this range.
1712 unsigned Size = CR.Range.second - CR.Range.first;
1714 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1715 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1717 CaseItr Pivot = CR.Range.first + Size/2;
1719 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1720 // (heuristically) allow us to emit JumpTable's later.
1722 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1726 uint64_t LSize = FrontCase.size();
1727 uint64_t RSize = TSize-LSize;
1728 DOUT << "Selecting best pivot: \n"
1729 << "First: " << First << ", Last: " << Last <<"\n"
1730 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1731 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1733 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1734 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1735 assert((RBegin-LEnd>=1) && "Invalid case distance");
1736 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1737 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1738 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1739 // Should always split in some non-trivial place
1741 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1742 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1743 << "Metric: " << Metric << "\n";
1744 if (FMetric < Metric) {
1747 DOUT << "Current metric set to: " << FMetric << "\n";
1753 if (areJTsAllowed(TLI)) {
1754 // If our case is dense we *really* should handle it earlier!
1755 assert((FMetric > 0) && "Should handle dense range earlier!");
1757 Pivot = CR.Range.first + Size/2;
1760 CaseRange LHSR(CR.Range.first, Pivot);
1761 CaseRange RHSR(Pivot, CR.Range.second);
1762 Constant *C = Pivot->Low;
1763 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1765 // We know that we branch to the LHS if the Value being switched on is
1766 // less than the Pivot value, C. We use this to optimize our binary
1767 // tree a bit, by recognizing that if SV is greater than or equal to the
1768 // LHS's Case Value, and that Case Value is exactly one less than the
1769 // Pivot's Value, then we can branch directly to the LHS's Target,
1770 // rather than creating a leaf node for it.
1771 if ((LHSR.second - LHSR.first) == 1 &&
1772 LHSR.first->High == CR.GE &&
1773 cast<ConstantInt>(C)->getSExtValue() ==
1774 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1775 TrueBB = LHSR.first->BB;
1777 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1778 CurMF->insert(BBI, TrueBB);
1779 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1782 // Similar to the optimization above, if the Value being switched on is
1783 // known to be less than the Constant CR.LT, and the current Case Value
1784 // is CR.LT - 1, then we can branch directly to the target block for
1785 // the current Case Value, rather than emitting a RHS leaf node for it.
1786 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1787 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1788 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1789 FalseBB = RHSR.first->BB;
1791 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1792 CurMF->insert(BBI, FalseBB);
1793 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1796 // Create a CaseBlock record representing a conditional branch to
1797 // the LHS node if the value being switched on SV is less than C.
1798 // Otherwise, branch to LHS.
1799 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1801 if (CR.CaseBB == CurMBB)
1802 visitSwitchCase(CB);
1804 SwitchCases.push_back(CB);
1809 /// handleBitTestsSwitchCase - if current case range has few destination and
1810 /// range span less, than machine word bitwidth, encode case range into series
1811 /// of masks and emit bit tests with these masks.
1812 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1813 CaseRecVector& WorkList,
1815 MachineBasicBlock* Default){
1816 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1818 Case& FrontCase = *CR.Range.first;
1819 Case& BackCase = *(CR.Range.second-1);
1821 // Get the MachineFunction which holds the current MBB. This is used when
1822 // inserting any additional MBBs necessary to represent the switch.
1823 MachineFunction *CurMF = CurMBB->getParent();
1825 unsigned numCmps = 0;
1826 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1828 // Single case counts one, case range - two.
1829 if (I->Low == I->High)
1835 // Count unique destinations
1836 SmallSet<MachineBasicBlock*, 4> Dests;
1837 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1838 Dests.insert(I->BB);
1839 if (Dests.size() > 3)
1840 // Don't bother the code below, if there are too much unique destinations
1843 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1844 << "Total number of comparisons: " << numCmps << "\n";
1846 // Compute span of values.
1847 Constant* minValue = FrontCase.Low;
1848 Constant* maxValue = BackCase.High;
1849 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1850 cast<ConstantInt>(minValue)->getSExtValue();
1851 DOUT << "Compare range: " << range << "\n"
1852 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1853 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1855 if (range>=IntPtrBits ||
1856 (!(Dests.size() == 1 && numCmps >= 3) &&
1857 !(Dests.size() == 2 && numCmps >= 5) &&
1858 !(Dests.size() >= 3 && numCmps >= 6)))
1861 DOUT << "Emitting bit tests\n";
1862 int64_t lowBound = 0;
1864 // Optimize the case where all the case values fit in a
1865 // word without having to subtract minValue. In this case,
1866 // we can optimize away the subtraction.
1867 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
1868 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
1869 range = cast<ConstantInt>(maxValue)->getSExtValue();
1871 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1874 CaseBitsVector CasesBits;
1875 unsigned i, count = 0;
1877 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1878 MachineBasicBlock* Dest = I->BB;
1879 for (i = 0; i < count; ++i)
1880 if (Dest == CasesBits[i].BB)
1884 assert((count < 3) && "Too much destinations to test!");
1885 CasesBits.push_back(CaseBits(0, Dest, 0));
1889 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1890 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1892 for (uint64_t j = lo; j <= hi; j++) {
1893 CasesBits[i].Mask |= 1ULL << j;
1894 CasesBits[i].Bits++;
1898 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1902 // Figure out which block is immediately after the current one.
1903 MachineFunction::iterator BBI = CR.CaseBB;
1906 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1909 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1910 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1911 << ", BB: " << CasesBits[i].BB << "\n";
1913 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1914 CurMF->insert(BBI, CaseBB);
1915 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1920 BitTestBlock BTB(lowBound, range, SV,
1921 -1U, (CR.CaseBB == CurMBB),
1922 CR.CaseBB, Default, BTC);
1924 if (CR.CaseBB == CurMBB)
1925 visitBitTestHeader(BTB);
1927 BitTestCases.push_back(BTB);
1933 /// Clusterify - Transform simple list of Cases into list of CaseRange's
1934 unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1935 const SwitchInst& SI) {
1936 unsigned numCmps = 0;
1938 // Start with "simple" cases
1939 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1940 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1941 Cases.push_back(Case(SI.getSuccessorValue(i),
1942 SI.getSuccessorValue(i),
1945 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1947 // Merge case into clusters
1948 if (Cases.size()>=2)
1949 // Must recompute end() each iteration because it may be
1950 // invalidated by erase if we hold on to it
1951 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
1952 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1953 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1954 MachineBasicBlock* nextBB = J->BB;
1955 MachineBasicBlock* currentBB = I->BB;
1957 // If the two neighboring cases go to the same destination, merge them
1958 // into a single case.
1959 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1967 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1968 if (I->Low != I->High)
1969 // A range counts double, since it requires two compares.
1976 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
1977 // Figure out which block is immediately after the current one.
1978 MachineBasicBlock *NextBlock = 0;
1979 MachineFunction::iterator BBI = CurMBB;
1981 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1983 // If there is only the default destination, branch to it if it is not the
1984 // next basic block. Otherwise, just fall through.
1985 if (SI.getNumOperands() == 2) {
1986 // Update machine-CFG edges.
1988 // If this is not a fall-through branch, emit the branch.
1989 CurMBB->addSuccessor(Default);
1990 if (Default != NextBlock)
1991 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1992 DAG.getBasicBlock(Default)));
1997 // If there are any non-default case statements, create a vector of Cases
1998 // representing each one, and sort the vector so that we can efficiently
1999 // create a binary search tree from them.
2001 unsigned numCmps = Clusterify(Cases, SI);
2002 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2003 << ". Total compares: " << numCmps << "\n";
2005 // Get the Value to be switched on and default basic blocks, which will be
2006 // inserted into CaseBlock records, representing basic blocks in the binary
2008 Value *SV = SI.getOperand(0);
2010 // Push the initial CaseRec onto the worklist
2011 CaseRecVector WorkList;
2012 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2014 while (!WorkList.empty()) {
2015 // Grab a record representing a case range to process off the worklist
2016 CaseRec CR = WorkList.back();
2017 WorkList.pop_back();
2019 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2022 // If the range has few cases (two or less) emit a series of specific
2024 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2027 // If the switch has more than 5 blocks, and at least 40% dense, and the
2028 // target supports indirect branches, then emit a jump table rather than
2029 // lowering the switch to a binary tree of conditional branches.
2030 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2033 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2034 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2035 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2040 void SelectionDAGLowering::visitSub(User &I) {
2041 // -0.0 - X --> fneg
2042 const Type *Ty = I.getType();
2043 if (isa<VectorType>(Ty)) {
2044 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2045 const VectorType *DestTy = cast<VectorType>(I.getType());
2046 const Type *ElTy = DestTy->getElementType();
2047 if (ElTy->isFloatingPoint()) {
2048 unsigned VL = DestTy->getNumElements();
2049 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2050 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2052 SDValue Op2 = getValue(I.getOperand(1));
2053 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2059 if (Ty->isFloatingPoint()) {
2060 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2061 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2062 SDValue Op2 = getValue(I.getOperand(1));
2063 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2068 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2071 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2072 SDValue Op1 = getValue(I.getOperand(0));
2073 SDValue Op2 = getValue(I.getOperand(1));
2075 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2078 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2079 SDValue Op1 = getValue(I.getOperand(0));
2080 SDValue Op2 = getValue(I.getOperand(1));
2081 if (!isa<VectorType>(I.getType())) {
2082 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2083 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2084 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2085 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2088 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2091 void SelectionDAGLowering::visitICmp(User &I) {
2092 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2093 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2094 predicate = IC->getPredicate();
2095 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2096 predicate = ICmpInst::Predicate(IC->getPredicate());
2097 SDValue Op1 = getValue(I.getOperand(0));
2098 SDValue Op2 = getValue(I.getOperand(1));
2099 ISD::CondCode Opcode = getICmpCondCode(predicate);
2100 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2103 void SelectionDAGLowering::visitFCmp(User &I) {
2104 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2105 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2106 predicate = FC->getPredicate();
2107 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2108 predicate = FCmpInst::Predicate(FC->getPredicate());
2109 SDValue Op1 = getValue(I.getOperand(0));
2110 SDValue Op2 = getValue(I.getOperand(1));
2111 ISD::CondCode Condition = getFCmpCondCode(predicate);
2112 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2115 void SelectionDAGLowering::visitVICmp(User &I) {
2116 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2117 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2118 predicate = IC->getPredicate();
2119 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2120 predicate = ICmpInst::Predicate(IC->getPredicate());
2121 SDValue Op1 = getValue(I.getOperand(0));
2122 SDValue Op2 = getValue(I.getOperand(1));
2123 ISD::CondCode Opcode = getICmpCondCode(predicate);
2124 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2127 void SelectionDAGLowering::visitVFCmp(User &I) {
2128 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2129 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2130 predicate = FC->getPredicate();
2131 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2132 predicate = FCmpInst::Predicate(FC->getPredicate());
2133 SDValue Op1 = getValue(I.getOperand(0));
2134 SDValue Op2 = getValue(I.getOperand(1));
2135 ISD::CondCode Condition = getFCmpCondCode(predicate);
2136 MVT DestVT = TLI.getValueType(I.getType());
2138 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2141 void SelectionDAGLowering::visitSelect(User &I) {
2142 SmallVector<MVT, 4> ValueVTs;
2143 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2144 unsigned NumValues = ValueVTs.size();
2145 if (NumValues != 0) {
2146 SmallVector<SDValue, 4> Values(NumValues);
2147 SDValue Cond = getValue(I.getOperand(0));
2148 SDValue TrueVal = getValue(I.getOperand(1));
2149 SDValue FalseVal = getValue(I.getOperand(2));
2151 for (unsigned i = 0; i != NumValues; ++i)
2152 Values[i] = DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2153 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2154 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2156 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], NumValues),
2157 &Values[0], NumValues));
2162 void SelectionDAGLowering::visitTrunc(User &I) {
2163 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2164 SDValue N = getValue(I.getOperand(0));
2165 MVT DestVT = TLI.getValueType(I.getType());
2166 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2169 void SelectionDAGLowering::visitZExt(User &I) {
2170 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2171 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2172 SDValue N = getValue(I.getOperand(0));
2173 MVT DestVT = TLI.getValueType(I.getType());
2174 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2177 void SelectionDAGLowering::visitSExt(User &I) {
2178 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2179 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2180 SDValue N = getValue(I.getOperand(0));
2181 MVT DestVT = TLI.getValueType(I.getType());
2182 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2185 void SelectionDAGLowering::visitFPTrunc(User &I) {
2186 // FPTrunc is never a no-op cast, no need to check
2187 SDValue N = getValue(I.getOperand(0));
2188 MVT DestVT = TLI.getValueType(I.getType());
2189 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2192 void SelectionDAGLowering::visitFPExt(User &I){
2193 // FPTrunc is never a no-op cast, no need to check
2194 SDValue N = getValue(I.getOperand(0));
2195 MVT DestVT = TLI.getValueType(I.getType());
2196 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2199 void SelectionDAGLowering::visitFPToUI(User &I) {
2200 // FPToUI is never a no-op cast, no need to check
2201 SDValue N = getValue(I.getOperand(0));
2202 MVT DestVT = TLI.getValueType(I.getType());
2203 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2206 void SelectionDAGLowering::visitFPToSI(User &I) {
2207 // FPToSI is never a no-op cast, no need to check
2208 SDValue N = getValue(I.getOperand(0));
2209 MVT DestVT = TLI.getValueType(I.getType());
2210 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2213 void SelectionDAGLowering::visitUIToFP(User &I) {
2214 // UIToFP is never a no-op cast, no need to check
2215 SDValue N = getValue(I.getOperand(0));
2216 MVT DestVT = TLI.getValueType(I.getType());
2217 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2220 void SelectionDAGLowering::visitSIToFP(User &I){
2221 // SIToFP is never a no-op cast, no need to check
2222 SDValue N = getValue(I.getOperand(0));
2223 MVT DestVT = TLI.getValueType(I.getType());
2224 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2227 void SelectionDAGLowering::visitPtrToInt(User &I) {
2228 // What to do depends on the size of the integer and the size of the pointer.
2229 // We can either truncate, zero extend, or no-op, accordingly.
2230 SDValue N = getValue(I.getOperand(0));
2231 MVT SrcVT = N.getValueType();
2232 MVT DestVT = TLI.getValueType(I.getType());
2234 if (DestVT.bitsLT(SrcVT))
2235 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2237 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2238 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2239 setValue(&I, Result);
2242 void SelectionDAGLowering::visitIntToPtr(User &I) {
2243 // What to do depends on the size of the integer and the size of the pointer.
2244 // We can either truncate, zero extend, or no-op, accordingly.
2245 SDValue N = getValue(I.getOperand(0));
2246 MVT SrcVT = N.getValueType();
2247 MVT DestVT = TLI.getValueType(I.getType());
2248 if (DestVT.bitsLT(SrcVT))
2249 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2251 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2252 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2255 void SelectionDAGLowering::visitBitCast(User &I) {
2256 SDValue N = getValue(I.getOperand(0));
2257 MVT DestVT = TLI.getValueType(I.getType());
2259 // BitCast assures us that source and destination are the same size so this
2260 // is either a BIT_CONVERT or a no-op.
2261 if (DestVT != N.getValueType())
2262 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2264 setValue(&I, N); // noop cast.
2267 void SelectionDAGLowering::visitInsertElement(User &I) {
2268 SDValue InVec = getValue(I.getOperand(0));
2269 SDValue InVal = getValue(I.getOperand(1));
2270 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2271 getValue(I.getOperand(2)));
2273 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2274 TLI.getValueType(I.getType()),
2275 InVec, InVal, InIdx));
2278 void SelectionDAGLowering::visitExtractElement(User &I) {
2279 SDValue InVec = getValue(I.getOperand(0));
2280 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2281 getValue(I.getOperand(1)));
2282 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2283 TLI.getValueType(I.getType()), InVec, InIdx));
2286 void SelectionDAGLowering::visitShuffleVector(User &I) {
2287 SDValue V1 = getValue(I.getOperand(0));
2288 SDValue V2 = getValue(I.getOperand(1));
2289 SDValue Mask = getValue(I.getOperand(2));
2291 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2292 TLI.getValueType(I.getType()),
2296 void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2297 const Value *Op0 = I.getOperand(0);
2298 const Value *Op1 = I.getOperand(1);
2299 const Type *AggTy = I.getType();
2300 const Type *ValTy = Op1->getType();
2301 bool IntoUndef = isa<UndefValue>(Op0);
2302 bool FromUndef = isa<UndefValue>(Op1);
2304 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2305 I.idx_begin(), I.idx_end());
2307 SmallVector<MVT, 4> AggValueVTs;
2308 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2309 SmallVector<MVT, 4> ValValueVTs;
2310 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2312 unsigned NumAggValues = AggValueVTs.size();
2313 unsigned NumValValues = ValValueVTs.size();
2314 SmallVector<SDValue, 4> Values(NumAggValues);
2316 SDValue Agg = getValue(Op0);
2317 SDValue Val = getValue(Op1);
2319 // Copy the beginning value(s) from the original aggregate.
2320 for (; i != LinearIndex; ++i)
2321 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2322 SDValue(Agg.getNode(), Agg.getResNo() + i);
2323 // Copy values from the inserted value(s).
2324 for (; i != LinearIndex + NumValValues; ++i)
2325 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2326 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2327 // Copy remaining value(s) from the original aggregate.
2328 for (; i != NumAggValues; ++i)
2329 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2330 SDValue(Agg.getNode(), Agg.getResNo() + i);
2332 setValue(&I, DAG.getMergeValues(DAG.getVTList(&AggValueVTs[0], NumAggValues),
2333 &Values[0], NumAggValues));
2336 void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2337 const Value *Op0 = I.getOperand(0);
2338 const Type *AggTy = Op0->getType();
2339 const Type *ValTy = I.getType();
2340 bool OutOfUndef = isa<UndefValue>(Op0);
2342 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2343 I.idx_begin(), I.idx_end());
2345 SmallVector<MVT, 4> ValValueVTs;
2346 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2348 unsigned NumValValues = ValValueVTs.size();
2349 SmallVector<SDValue, 4> Values(NumValValues);
2351 SDValue Agg = getValue(Op0);
2352 // Copy out the selected value(s).
2353 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2354 Values[i - LinearIndex] =
2355 OutOfUndef ? DAG.getNode(ISD::UNDEF, Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2356 SDValue(Agg.getNode(), Agg.getResNo() + i);
2358 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValValueVTs[0], NumValValues),
2359 &Values[0], NumValValues));
2363 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2364 SDValue N = getValue(I.getOperand(0));
2365 const Type *Ty = I.getOperand(0)->getType();
2367 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2370 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2371 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2374 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2375 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2376 DAG.getIntPtrConstant(Offset));
2378 Ty = StTy->getElementType(Field);
2380 Ty = cast<SequentialType>(Ty)->getElementType();
2382 // If this is a constant subscript, handle it quickly.
2383 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2384 if (CI->getZExtValue() == 0) continue;
2386 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2387 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2388 DAG.getIntPtrConstant(Offs));
2392 // N = N + Idx * ElementSize;
2393 uint64_t ElementSize = TD->getABITypeSize(Ty);
2394 SDValue IdxN = getValue(Idx);
2396 // If the index is smaller or larger than intptr_t, truncate or extend
2398 if (IdxN.getValueType().bitsLT(N.getValueType()))
2399 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2400 else if (IdxN.getValueType().bitsGT(N.getValueType()))
2401 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2403 // If this is a multiply by a power of two, turn it into a shl
2404 // immediately. This is a very common case.
2405 if (ElementSize != 1) {
2406 if (isPowerOf2_64(ElementSize)) {
2407 unsigned Amt = Log2_64(ElementSize);
2408 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2409 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2411 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2412 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2416 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2422 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2423 // If this is a fixed sized alloca in the entry block of the function,
2424 // allocate it statically on the stack.
2425 if (FuncInfo.StaticAllocaMap.count(&I))
2426 return; // getValue will auto-populate this.
2428 const Type *Ty = I.getAllocatedType();
2429 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2431 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2434 SDValue AllocSize = getValue(I.getArraySize());
2435 MVT IntPtr = TLI.getPointerTy();
2436 if (IntPtr.bitsLT(AllocSize.getValueType()))
2437 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2438 else if (IntPtr.bitsGT(AllocSize.getValueType()))
2439 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2441 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2442 DAG.getIntPtrConstant(TySize));
2444 // Handle alignment. If the requested alignment is less than or equal to
2445 // the stack alignment, ignore it. If the size is greater than or equal to
2446 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2447 unsigned StackAlign =
2448 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2449 if (Align <= StackAlign)
2452 // Round the size of the allocation up to the stack alignment size
2453 // by add SA-1 to the size.
2454 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2455 DAG.getIntPtrConstant(StackAlign-1));
2456 // Mask out the low bits for alignment purposes.
2457 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2458 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2460 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2461 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2463 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2465 DAG.setRoot(DSA.getValue(1));
2467 // Inform the Frame Information that we have just allocated a variable-sized
2469 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2472 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2473 const Value *SV = I.getOperand(0);
2474 SDValue Ptr = getValue(SV);
2476 const Type *Ty = I.getType();
2477 bool isVolatile = I.isVolatile();
2478 unsigned Alignment = I.getAlignment();
2480 SmallVector<MVT, 4> ValueVTs;
2481 SmallVector<uint64_t, 4> Offsets;
2482 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2483 unsigned NumValues = ValueVTs.size();
2488 bool ConstantMemory = false;
2490 // Serialize volatile loads with other side effects.
2492 else if (AA->pointsToConstantMemory(SV)) {
2493 // Do not serialize (non-volatile) loads of constant memory with anything.
2494 Root = DAG.getEntryNode();
2495 ConstantMemory = true;
2497 // Do not serialize non-volatile loads against each other.
2498 Root = DAG.getRoot();
2501 SmallVector<SDValue, 4> Values(NumValues);
2502 SmallVector<SDValue, 4> Chains(NumValues);
2503 MVT PtrVT = Ptr.getValueType();
2504 for (unsigned i = 0; i != NumValues; ++i) {
2505 SDValue L = DAG.getLoad(ValueVTs[i], Root,
2506 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2507 DAG.getConstant(Offsets[i], PtrVT)),
2509 isVolatile, Alignment);
2511 Chains[i] = L.getValue(1);
2514 if (!ConstantMemory) {
2515 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2516 &Chains[0], NumValues);
2520 PendingLoads.push_back(Chain);
2523 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], NumValues),
2524 &Values[0], NumValues));
2528 void SelectionDAGLowering::visitStore(StoreInst &I) {
2529 Value *SrcV = I.getOperand(0);
2530 Value *PtrV = I.getOperand(1);
2532 SmallVector<MVT, 4> ValueVTs;
2533 SmallVector<uint64_t, 4> Offsets;
2534 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2535 unsigned NumValues = ValueVTs.size();
2539 // Get the lowered operands. Note that we do this after
2540 // checking if NumResults is zero, because with zero results
2541 // the operands won't have values in the map.
2542 SDValue Src = getValue(SrcV);
2543 SDValue Ptr = getValue(PtrV);
2545 SDValue Root = getRoot();
2546 SmallVector<SDValue, 4> Chains(NumValues);
2547 MVT PtrVT = Ptr.getValueType();
2548 bool isVolatile = I.isVolatile();
2549 unsigned Alignment = I.getAlignment();
2550 for (unsigned i = 0; i != NumValues; ++i)
2551 Chains[i] = DAG.getStore(Root, SDValue(Src.getNode(), Src.getResNo() + i),
2552 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2553 DAG.getConstant(Offsets[i], PtrVT)),
2555 isVolatile, Alignment);
2557 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2560 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2562 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2563 unsigned Intrinsic) {
2564 bool HasChain = !I.doesNotAccessMemory();
2565 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2567 // Build the operand list.
2568 SmallVector<SDValue, 8> Ops;
2569 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2571 // We don't need to serialize loads against other loads.
2572 Ops.push_back(DAG.getRoot());
2574 Ops.push_back(getRoot());
2578 // Add the intrinsic ID as an integer operand.
2579 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2581 // Add all operands of the call to the operand list.
2582 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2583 SDValue Op = getValue(I.getOperand(i));
2584 assert(TLI.isTypeLegal(Op.getValueType()) &&
2585 "Intrinsic uses a non-legal type?");
2589 std::vector<MVT> VTs;
2590 if (I.getType() != Type::VoidTy) {
2591 MVT VT = TLI.getValueType(I.getType());
2592 if (VT.isVector()) {
2593 const VectorType *DestTy = cast<VectorType>(I.getType());
2594 MVT EltVT = TLI.getValueType(DestTy->getElementType());
2596 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2597 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2600 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2604 VTs.push_back(MVT::Other);
2606 const MVT *VTList = DAG.getNodeValueTypes(VTs);
2611 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2612 &Ops[0], Ops.size());
2613 else if (I.getType() != Type::VoidTy)
2614 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2615 &Ops[0], Ops.size());
2617 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2618 &Ops[0], Ops.size());
2621 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2623 PendingLoads.push_back(Chain);
2627 if (I.getType() != Type::VoidTy) {
2628 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2629 MVT VT = TLI.getValueType(PTy);
2630 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2632 setValue(&I, Result);
2636 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2637 static GlobalVariable *ExtractTypeInfo(Value *V) {
2638 V = V->stripPointerCasts();
2639 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2640 assert ((GV || isa<ConstantPointerNull>(V)) &&
2641 "TypeInfo must be a global variable or NULL");
2647 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
2648 /// call, and add them to the specified machine basic block.
2649 void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2650 MachineBasicBlock *MBB) {
2651 // Inform the MachineModuleInfo of the personality for this landing pad.
2652 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2653 assert(CE->getOpcode() == Instruction::BitCast &&
2654 isa<Function>(CE->getOperand(0)) &&
2655 "Personality should be a function");
2656 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2658 // Gather all the type infos for this landing pad and pass them along to
2659 // MachineModuleInfo.
2660 std::vector<GlobalVariable *> TyInfo;
2661 unsigned N = I.getNumOperands();
2663 for (unsigned i = N - 1; i > 2; --i) {
2664 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2665 unsigned FilterLength = CI->getZExtValue();
2666 unsigned FirstCatch = i + FilterLength + !FilterLength;
2667 assert (FirstCatch <= N && "Invalid filter length");
2669 if (FirstCatch < N) {
2670 TyInfo.reserve(N - FirstCatch);
2671 for (unsigned j = FirstCatch; j < N; ++j)
2672 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2673 MMI->addCatchTypeInfo(MBB, TyInfo);
2677 if (!FilterLength) {
2679 MMI->addCleanup(MBB);
2682 TyInfo.reserve(FilterLength - 1);
2683 for (unsigned j = i + 1; j < FirstCatch; ++j)
2684 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2685 MMI->addFilterTypeInfo(MBB, TyInfo);
2694 TyInfo.reserve(N - 3);
2695 for (unsigned j = 3; j < N; ++j)
2696 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2697 MMI->addCatchTypeInfo(MBB, TyInfo);
2703 /// GetSignificand - Get the significand and build it into a floating-point
2704 /// number with exponent of 1:
2706 /// Op = (Op & 0x007fffff) | 0x3f800000;
2708 /// where Op is the hexidecimal representation of floating point value.
2710 GetSignificand(SelectionDAG &DAG, SDValue Op) {
2711 SDValue t1 = DAG.getNode(ISD::AND, MVT::i32, Op,
2712 DAG.getConstant(0x007fffff, MVT::i32));
2713 SDValue t2 = DAG.getNode(ISD::OR, MVT::i32, t1,
2714 DAG.getConstant(0x3f800000, MVT::i32));
2715 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t2);
2718 /// GetExponent - Get the exponent:
2720 /// (float)((Op1 >> 23) - 127);
2722 /// where Op is the hexidecimal representation of floating point value.
2724 GetExponent(SelectionDAG &DAG, SDValue Op) {
2725 SDValue t1 = DAG.getNode(ISD::SRL, MVT::i32, Op,
2726 DAG.getConstant(23, MVT::i32));
2727 SDValue t2 = DAG.getNode(ISD::SUB, MVT::i32, t1,
2728 DAG.getConstant(127, MVT::i32));
2729 return DAG.getNode(ISD::UINT_TO_FP, MVT::f32, t2);
2732 /// getF32Constant - Get 32-bit floating point constant.
2734 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
2735 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
2738 /// Inlined utility function to implement binary input atomic intrinsics for
2739 /// visitIntrinsicCall: I is a call instruction
2740 /// Op is the associated NodeType for I
2742 SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2743 SDValue Root = getRoot();
2744 SDValue L = DAG.getAtomic(Op, Root,
2745 getValue(I.getOperand(1)),
2746 getValue(I.getOperand(2)),
2749 DAG.setRoot(L.getValue(1));
2753 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
2754 /// limited-precision mode.
2756 SelectionDAGLowering::visitExp(CallInst &I) {
2759 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2760 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2761 SDValue Op = getValue(I.getOperand(1));
2763 // Put the exponent in the right bit position for later addition to the
2766 // #define LOG2OFe 1.4426950f
2767 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
2768 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
2769 getF32Constant(DAG, 0x3fb8aa3b));
2770 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
2772 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
2773 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
2774 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
2776 // IntegerPartOfX <<= 23;
2777 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
2778 DAG.getConstant(23, MVT::i32));
2780 if (LimitFloatPrecision <= 6) {
2781 // For floating-point precision of 6:
2783 // TwoToFractionalPartOfX =
2785 // (0.735607626f + 0.252464424f * x) * x;
2787 // error 0.0144103317, which is 6 bits
2788 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2789 getF32Constant(DAG, 0x3e814304));
2790 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
2791 getF32Constant(DAG, 0x3f3c50c8));
2792 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2793 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
2794 getF32Constant(DAG, 0x3f7f5e7e));
2795 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
2797 // Add the exponent into the result in integer domain.
2798 SDValue t6 = DAG.getNode(ISD::ADD, MVT::i32,
2799 TwoToFracPartOfX, IntegerPartOfX);
2801 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t6);
2802 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
2803 // For floating-point precision of 12:
2805 // TwoToFractionalPartOfX =
2808 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
2810 // 0.000107046256 error, which is 13 to 14 bits
2811 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2812 getF32Constant(DAG, 0x3da235e3));
2813 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
2814 getF32Constant(DAG, 0x3e65b8f3));
2815 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2816 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
2817 getF32Constant(DAG, 0x3f324b07));
2818 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2819 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
2820 getF32Constant(DAG, 0x3f7ff8fd));
2821 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
2823 // Add the exponent into the result in integer domain.
2824 SDValue t8 = DAG.getNode(ISD::ADD, MVT::i32,
2825 TwoToFracPartOfX, IntegerPartOfX);
2827 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t8);
2828 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
2829 // For floating-point precision of 18:
2831 // TwoToFractionalPartOfX =
2835 // (0.554906021e-1f +
2836 // (0.961591928e-2f +
2837 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
2839 // error 2.47208000*10^(-7), which is better than 18 bits
2840 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2841 getF32Constant(DAG, 0x3924b03e));
2842 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
2843 getF32Constant(DAG, 0x3ab24b87));
2844 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2845 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
2846 getF32Constant(DAG, 0x3c1d8c17));
2847 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2848 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
2849 getF32Constant(DAG, 0x3d634a1d));
2850 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
2851 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
2852 getF32Constant(DAG, 0x3e75fe14));
2853 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
2854 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
2855 getF32Constant(DAG, 0x3f317234));
2856 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
2857 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
2858 getF32Constant(DAG, 0x3f800000));
2859 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
2861 // Add the exponent into the result in integer domain.
2862 SDValue t14 = DAG.getNode(ISD::ADD, MVT::i32,
2863 TwoToFracPartOfX, IntegerPartOfX);
2865 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t14);
2868 // No special expansion.
2869 result = DAG.getNode(ISD::FEXP,
2870 getValue(I.getOperand(1)).getValueType(),
2871 getValue(I.getOperand(1)));
2874 setValue(&I, result);
2877 /// visitLog - Lower a log intrinsic. Handles the special sequences for
2878 /// limited-precision mode.
2880 SelectionDAGLowering::visitLog(CallInst &I) {
2883 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2884 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2885 SDValue Op = getValue(I.getOperand(1));
2886 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
2888 // Scale the exponent by log(2) [0.69314718f].
2889 SDValue Exp = GetExponent(DAG, Op1);
2890 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
2891 getF32Constant(DAG, 0x3f317218));
2893 // Get the significand and build it into a floating-point number with
2895 SDValue X = GetSignificand(DAG, Op1);
2897 if (LimitFloatPrecision <= 6) {
2898 // For floating-point precision of 6:
2902 // (1.4034025f - 0.23903021f * x) * x;
2904 // error 0.0034276066, which is better than 8 bits
2905 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2906 getF32Constant(DAG, 0xbe74c456));
2907 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
2908 getF32Constant(DAG, 0x3fb3a2b1));
2909 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
2910 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
2911 getF32Constant(DAG, 0x3f949a29));
2913 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
2914 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
2915 // For floating-point precision of 12:
2921 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
2923 // error 0.000061011436, which is 14 bits
2924 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2925 getF32Constant(DAG, 0xbd67b6d6));
2926 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
2927 getF32Constant(DAG, 0x3ee4f4b8));
2928 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
2929 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
2930 getF32Constant(DAG, 0x3fbc278b));
2931 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2932 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
2933 getF32Constant(DAG, 0x40348e95));
2934 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2935 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
2936 getF32Constant(DAG, 0x3fdef31a));
2938 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
2939 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
2940 // For floating-point precision of 18:
2948 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
2950 // error 0.0000023660568, which is better than 18 bits
2951 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2952 getF32Constant(DAG, 0xbc91e5ac));
2953 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
2954 getF32Constant(DAG, 0x3e4350aa));
2955 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
2956 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
2957 getF32Constant(DAG, 0x3f60d3e3));
2958 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2959 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
2960 getF32Constant(DAG, 0x4011cdf0));
2961 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2962 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
2963 getF32Constant(DAG, 0x406cfd1c));
2964 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
2965 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
2966 getF32Constant(DAG, 0x408797cb));
2967 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
2968 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
2969 getF32Constant(DAG, 0x4006dcab));
2971 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
2974 // No special expansion.
2975 result = DAG.getNode(ISD::FLOG,
2976 getValue(I.getOperand(1)).getValueType(),
2977 getValue(I.getOperand(1)));
2980 setValue(&I, result);
2983 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
2984 /// limited-precision mode.
2986 SelectionDAGLowering::visitLog2(CallInst &I) {
2989 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2990 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2991 SDValue Op = getValue(I.getOperand(1));
2992 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
2994 // Get the exponent.
2995 SDValue LogOfExponent = GetExponent(DAG, Op1);
2997 // Get the significand and build it into a floating-point number with
2999 SDValue X = GetSignificand(DAG, Op1);
3001 // Different possible minimax approximations of significand in
3002 // floating-point for various degrees of accuracy over [1,2].
3003 if (LimitFloatPrecision <= 6) {
3004 // For floating-point precision of 6:
3006 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3008 // error 0.0049451742, which is more than 7 bits
3009 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3010 getF32Constant(DAG, 0xbeb08fe0));
3011 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3012 getF32Constant(DAG, 0x40019463));
3013 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3014 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3015 getF32Constant(DAG, 0x3fd6633d));
3017 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3018 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3019 // For floating-point precision of 12:
3025 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3027 // error 0.0000876136000, which is better than 13 bits
3028 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3029 getF32Constant(DAG, 0xbda7262e));
3030 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3031 getF32Constant(DAG, 0x3f25280b));
3032 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3033 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3034 getF32Constant(DAG, 0x4007b923));
3035 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3036 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3037 getF32Constant(DAG, 0x40823e2f));
3038 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3039 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
3040 getF32Constant(DAG, 0x4020d29c));
3042 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3043 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3044 // For floating-point precision of 18:
3053 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3055 // error 0.0000018516, which is better than 18 bits
3056 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3057 getF32Constant(DAG, 0xbcd2769e));
3058 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3059 getF32Constant(DAG, 0x3e8ce0b9));
3060 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3061 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3062 getF32Constant(DAG, 0x3fa22ae7));
3063 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3064 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3065 getF32Constant(DAG, 0x40525723));
3066 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3067 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
3068 getF32Constant(DAG, 0x40aaf200));
3069 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3070 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3071 getF32Constant(DAG, 0x40c39dad));
3072 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3073 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
3074 getF32Constant(DAG, 0x4042902c));
3076 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3079 // No special expansion.
3080 result = DAG.getNode(ISD::FLOG2,
3081 getValue(I.getOperand(1)).getValueType(),
3082 getValue(I.getOperand(1)));
3085 setValue(&I, result);
3088 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3089 /// limited-precision mode.
3091 SelectionDAGLowering::visitLog10(CallInst &I) {
3094 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3095 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3096 SDValue Op = getValue(I.getOperand(1));
3097 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3099 // Scale the exponent by log10(2) [0.30102999f].
3100 SDValue Exp = GetExponent(DAG, Op1);
3101 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
3102 getF32Constant(DAG, 0x3e9a209a));
3104 // Get the significand and build it into a floating-point number with
3106 SDValue X = GetSignificand(DAG, Op1);
3108 if (LimitFloatPrecision <= 6) {
3109 // For floating-point precision of 6:
3111 // Log10ofMantissa =
3113 // (0.60948995f - 0.10380950f * x) * x;
3115 // error 0.0014886165, which is 6 bits
3116 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3117 getF32Constant(DAG, 0xbdd49a13));
3118 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3119 getF32Constant(DAG, 0x3f1c0789));
3120 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3121 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3122 getF32Constant(DAG, 0x3f011300));
3124 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3125 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3126 // For floating-point precision of 12:
3128 // Log10ofMantissa =
3131 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3133 // error 0.00019228036, which is better than 12 bits
3134 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3135 getF32Constant(DAG, 0x3d431f31));
3136 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
3137 getF32Constant(DAG, 0x3ea21fb2));
3138 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3139 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3140 getF32Constant(DAG, 0x3f6ae232));
3141 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3142 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t4,
3143 getF32Constant(DAG, 0x3f25f7c3));
3145 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3146 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3147 // For floating-point precision of 18:
3149 // Log10ofMantissa =
3154 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3156 // error 0.0000037995730, which is better than 18 bits
3157 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3158 getF32Constant(DAG, 0x3c5d51ce));
3159 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
3160 getF32Constant(DAG, 0x3e00685a));
3161 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3162 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3163 getF32Constant(DAG, 0x3efb6798));
3164 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3165 SDValue t5 = DAG.getNode(ISD::FSUB, MVT::f32, t4,
3166 getF32Constant(DAG, 0x3f88d192));
3167 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3168 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3169 getF32Constant(DAG, 0x3fc4316c));
3170 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3171 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t8,
3172 getF32Constant(DAG, 0x3f57ce70));
3174 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3177 // No special expansion.
3178 result = DAG.getNode(ISD::FLOG10,
3179 getValue(I.getOperand(1)).getValueType(),
3180 getValue(I.getOperand(1)));
3183 setValue(&I, result);
3186 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3187 /// limited-precision mode.
3189 SelectionDAGLowering::visitExp2(CallInst &I) {
3192 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3193 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3194 SDValue Op = getValue(I.getOperand(1));
3196 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, Op);
3198 // FractionalPartOfX = x - (float)IntegerPartOfX;
3199 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3200 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, Op, t1);
3202 // IntegerPartOfX <<= 23;
3203 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3204 DAG.getConstant(23, MVT::i32));
3206 if (LimitFloatPrecision <= 6) {
3207 // For floating-point precision of 6:
3209 // TwoToFractionalPartOfX =
3211 // (0.735607626f + 0.252464424f * x) * x;
3213 // error 0.0144103317, which is 6 bits
3214 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3215 getF32Constant(DAG, 0x3e814304));
3216 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3217 getF32Constant(DAG, 0x3f3c50c8));
3218 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3219 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3220 getF32Constant(DAG, 0x3f7f5e7e));
3221 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3222 SDValue TwoToFractionalPartOfX =
3223 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3225 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3226 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3227 // For floating-point precision of 12:
3229 // TwoToFractionalPartOfX =
3232 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3234 // error 0.000107046256, which is 13 to 14 bits
3235 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3236 getF32Constant(DAG, 0x3da235e3));
3237 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3238 getF32Constant(DAG, 0x3e65b8f3));
3239 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3240 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3241 getF32Constant(DAG, 0x3f324b07));
3242 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3243 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3244 getF32Constant(DAG, 0x3f7ff8fd));
3245 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3246 SDValue TwoToFractionalPartOfX =
3247 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3249 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3250 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3251 // For floating-point precision of 18:
3253 // TwoToFractionalPartOfX =
3257 // (0.554906021e-1f +
3258 // (0.961591928e-2f +
3259 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3260 // error 2.47208000*10^(-7), which is better than 18 bits
3261 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3262 getF32Constant(DAG, 0x3924b03e));
3263 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3264 getF32Constant(DAG, 0x3ab24b87));
3265 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3266 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3267 getF32Constant(DAG, 0x3c1d8c17));
3268 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3269 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3270 getF32Constant(DAG, 0x3d634a1d));
3271 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3272 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3273 getF32Constant(DAG, 0x3e75fe14));
3274 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3275 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
3276 getF32Constant(DAG, 0x3f317234));
3277 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3278 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
3279 getF32Constant(DAG, 0x3f800000));
3280 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3281 SDValue TwoToFractionalPartOfX =
3282 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3284 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3287 // No special expansion.
3288 result = DAG.getNode(ISD::FEXP2,
3289 getValue(I.getOperand(1)).getValueType(),
3290 getValue(I.getOperand(1)));
3293 setValue(&I, result);
3296 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3297 /// limited-precision mode with x == 10.0f.
3299 SelectionDAGLowering::visitPow(CallInst &I) {
3301 Value *Val = I.getOperand(1);
3302 bool IsExp10 = false;
3304 if (getValue(Val).getValueType() == MVT::f32 &&
3305 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
3306 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3307 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3308 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3310 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3315 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3316 SDValue Op = getValue(I.getOperand(2));
3318 // Put the exponent in the right bit position for later addition to the
3321 // #define LOG2OF10 3.3219281f
3322 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3323 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
3324 getF32Constant(DAG, 0x40549a78));
3325 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3327 // FractionalPartOfX = x - (float)IntegerPartOfX;
3328 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3329 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3331 // IntegerPartOfX <<= 23;
3332 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3333 DAG.getConstant(23, MVT::i32));
3335 if (LimitFloatPrecision <= 6) {
3336 // For floating-point precision of 6:
3338 // twoToFractionalPartOfX =
3340 // (0.735607626f + 0.252464424f * x) * x;
3342 // error 0.0144103317, which is 6 bits
3343 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3344 getF32Constant(DAG, 0x3e814304));
3345 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3346 getF32Constant(DAG, 0x3f3c50c8));
3347 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3348 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3349 getF32Constant(DAG, 0x3f7f5e7e));
3350 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3351 SDValue TwoToFractionalPartOfX =
3352 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3354 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3355 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3356 // For floating-point precision of 12:
3358 // TwoToFractionalPartOfX =
3361 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3363 // error 0.000107046256, which is 13 to 14 bits
3364 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3365 getF32Constant(DAG, 0x3da235e3));
3366 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3367 getF32Constant(DAG, 0x3e65b8f3));
3368 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3369 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3370 getF32Constant(DAG, 0x3f324b07));
3371 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3372 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3373 getF32Constant(DAG, 0x3f7ff8fd));
3374 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3375 SDValue TwoToFractionalPartOfX =
3376 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3378 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3379 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3380 // For floating-point precision of 18:
3382 // TwoToFractionalPartOfX =
3386 // (0.554906021e-1f +
3387 // (0.961591928e-2f +
3388 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3389 // error 2.47208000*10^(-7), which is better than 18 bits
3390 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3391 getF32Constant(DAG, 0x3924b03e));
3392 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3393 getF32Constant(DAG, 0x3ab24b87));
3394 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3395 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3396 getF32Constant(DAG, 0x3c1d8c17));
3397 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3398 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3399 getF32Constant(DAG, 0x3d634a1d));
3400 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3401 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3402 getF32Constant(DAG, 0x3e75fe14));
3403 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3404 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
3405 getF32Constant(DAG, 0x3f317234));
3406 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3407 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
3408 getF32Constant(DAG, 0x3f800000));
3409 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3410 SDValue TwoToFractionalPartOfX =
3411 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3413 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3416 // No special expansion.
3417 result = DAG.getNode(ISD::FPOW,
3418 getValue(I.getOperand(1)).getValueType(),
3419 getValue(I.getOperand(1)),
3420 getValue(I.getOperand(2)));
3423 setValue(&I, result);
3426 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3427 /// we want to emit this as a call to a named external function, return the name
3428 /// otherwise lower it and return null.
3430 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3431 switch (Intrinsic) {
3433 // By default, turn this into a target intrinsic node.
3434 visitTargetIntrinsic(I, Intrinsic);
3436 case Intrinsic::vastart: visitVAStart(I); return 0;
3437 case Intrinsic::vaend: visitVAEnd(I); return 0;
3438 case Intrinsic::vacopy: visitVACopy(I); return 0;
3439 case Intrinsic::returnaddress:
3440 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3441 getValue(I.getOperand(1))));
3443 case Intrinsic::frameaddress:
3444 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3445 getValue(I.getOperand(1))));
3447 case Intrinsic::setjmp:
3448 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3450 case Intrinsic::longjmp:
3451 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3453 case Intrinsic::memcpy_i32:
3454 case Intrinsic::memcpy_i64: {
3455 SDValue Op1 = getValue(I.getOperand(1));
3456 SDValue Op2 = getValue(I.getOperand(2));
3457 SDValue Op3 = getValue(I.getOperand(3));
3458 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3459 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3460 I.getOperand(1), 0, I.getOperand(2), 0));
3463 case Intrinsic::memset_i32:
3464 case Intrinsic::memset_i64: {
3465 SDValue Op1 = getValue(I.getOperand(1));
3466 SDValue Op2 = getValue(I.getOperand(2));
3467 SDValue Op3 = getValue(I.getOperand(3));
3468 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3469 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3470 I.getOperand(1), 0));
3473 case Intrinsic::memmove_i32:
3474 case Intrinsic::memmove_i64: {
3475 SDValue Op1 = getValue(I.getOperand(1));
3476 SDValue Op2 = getValue(I.getOperand(2));
3477 SDValue Op3 = getValue(I.getOperand(3));
3478 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3480 // If the source and destination are known to not be aliases, we can
3481 // lower memmove as memcpy.
3482 uint64_t Size = -1ULL;
3483 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3484 Size = C->getZExtValue();
3485 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3486 AliasAnalysis::NoAlias) {
3487 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3488 I.getOperand(1), 0, I.getOperand(2), 0));
3492 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3493 I.getOperand(1), 0, I.getOperand(2), 0));
3496 case Intrinsic::dbg_stoppoint: {
3497 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3498 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3499 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
3500 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
3501 assert(DD && "Not a debug information descriptor");
3502 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3505 cast<CompileUnitDesc>(DD)));
3510 case Intrinsic::dbg_region_start: {
3511 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3512 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3513 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3514 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
3515 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3520 case Intrinsic::dbg_region_end: {
3521 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3522 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3523 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3524 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
3525 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3530 case Intrinsic::dbg_func_start: {
3531 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3533 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3534 Value *SP = FSI.getSubprogram();
3535 if (SP && MMI->Verify(SP)) {
3536 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3537 // what (most?) gdb expects.
3538 DebugInfoDesc *DD = MMI->getDescFor(SP);
3539 assert(DD && "Not a debug information descriptor");
3540 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3541 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
3542 unsigned SrcFile = MMI->RecordSource(CompileUnit);
3543 // Record the source line but does create a label. It will be emitted
3544 // at asm emission time.
3545 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
3550 case Intrinsic::dbg_declare: {
3551 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3552 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3553 Value *Variable = DI.getVariable();
3554 if (MMI && Variable && MMI->Verify(Variable))
3555 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3556 getValue(DI.getAddress()), getValue(Variable)));
3560 case Intrinsic::eh_exception: {
3561 if (!CurMBB->isLandingPad()) {
3562 // FIXME: Mark exception register as live in. Hack for PR1508.
3563 unsigned Reg = TLI.getExceptionAddressRegister();
3564 if (Reg) CurMBB->addLiveIn(Reg);
3566 // Insert the EXCEPTIONADDR instruction.
3567 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3569 Ops[0] = DAG.getRoot();
3570 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3572 DAG.setRoot(Op.getValue(1));
3576 case Intrinsic::eh_selector_i32:
3577 case Intrinsic::eh_selector_i64: {
3578 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3579 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3580 MVT::i32 : MVT::i64);
3583 if (CurMBB->isLandingPad())
3584 AddCatchInfo(I, MMI, CurMBB);
3587 FuncInfo.CatchInfoLost.insert(&I);
3589 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3590 unsigned Reg = TLI.getExceptionSelectorRegister();
3591 if (Reg) CurMBB->addLiveIn(Reg);
3594 // Insert the EHSELECTION instruction.
3595 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3597 Ops[0] = getValue(I.getOperand(1));
3599 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3601 DAG.setRoot(Op.getValue(1));
3603 setValue(&I, DAG.getConstant(0, VT));
3609 case Intrinsic::eh_typeid_for_i32:
3610 case Intrinsic::eh_typeid_for_i64: {
3611 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3612 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3613 MVT::i32 : MVT::i64);
3616 // Find the type id for the given typeinfo.
3617 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3619 unsigned TypeID = MMI->getTypeIDFor(GV);
3620 setValue(&I, DAG.getConstant(TypeID, VT));
3622 // Return something different to eh_selector.
3623 setValue(&I, DAG.getConstant(1, VT));
3629 case Intrinsic::eh_return_i32:
3630 case Intrinsic::eh_return_i64:
3631 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3632 MMI->setCallsEHReturn(true);
3633 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3636 getValue(I.getOperand(1)),
3637 getValue(I.getOperand(2))));
3639 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3643 case Intrinsic::eh_unwind_init:
3644 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3645 MMI->setCallsUnwindInit(true);
3650 case Intrinsic::eh_dwarf_cfa: {
3651 MVT VT = getValue(I.getOperand(1)).getValueType();
3653 if (VT.bitsGT(TLI.getPointerTy()))
3654 CfaArg = DAG.getNode(ISD::TRUNCATE,
3655 TLI.getPointerTy(), getValue(I.getOperand(1)));
3657 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3658 TLI.getPointerTy(), getValue(I.getOperand(1)));
3660 SDValue Offset = DAG.getNode(ISD::ADD,
3662 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3663 TLI.getPointerTy()),
3665 setValue(&I, DAG.getNode(ISD::ADD,
3667 DAG.getNode(ISD::FRAMEADDR,
3670 TLI.getPointerTy())),
3675 case Intrinsic::sqrt:
3676 setValue(&I, DAG.getNode(ISD::FSQRT,
3677 getValue(I.getOperand(1)).getValueType(),
3678 getValue(I.getOperand(1))));
3680 case Intrinsic::powi:
3681 setValue(&I, DAG.getNode(ISD::FPOWI,
3682 getValue(I.getOperand(1)).getValueType(),
3683 getValue(I.getOperand(1)),
3684 getValue(I.getOperand(2))));
3686 case Intrinsic::sin:
3687 setValue(&I, DAG.getNode(ISD::FSIN,
3688 getValue(I.getOperand(1)).getValueType(),
3689 getValue(I.getOperand(1))));
3691 case Intrinsic::cos:
3692 setValue(&I, DAG.getNode(ISD::FCOS,
3693 getValue(I.getOperand(1)).getValueType(),
3694 getValue(I.getOperand(1))));
3696 case Intrinsic::log:
3699 case Intrinsic::log2:
3702 case Intrinsic::log10:
3705 case Intrinsic::exp:
3708 case Intrinsic::exp2:
3711 case Intrinsic::pow:
3714 case Intrinsic::pcmarker: {
3715 SDValue Tmp = getValue(I.getOperand(1));
3716 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3719 case Intrinsic::readcyclecounter: {
3720 SDValue Op = getRoot();
3721 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3722 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3725 DAG.setRoot(Tmp.getValue(1));
3728 case Intrinsic::part_select: {
3729 // Currently not implemented: just abort
3730 assert(0 && "part_select intrinsic not implemented");
3733 case Intrinsic::part_set: {
3734 // Currently not implemented: just abort
3735 assert(0 && "part_set intrinsic not implemented");
3738 case Intrinsic::bswap:
3739 setValue(&I, DAG.getNode(ISD::BSWAP,
3740 getValue(I.getOperand(1)).getValueType(),
3741 getValue(I.getOperand(1))));
3743 case Intrinsic::cttz: {
3744 SDValue Arg = getValue(I.getOperand(1));
3745 MVT Ty = Arg.getValueType();
3746 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
3747 setValue(&I, result);
3750 case Intrinsic::ctlz: {
3751 SDValue Arg = getValue(I.getOperand(1));
3752 MVT Ty = Arg.getValueType();
3753 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
3754 setValue(&I, result);
3757 case Intrinsic::ctpop: {
3758 SDValue Arg = getValue(I.getOperand(1));
3759 MVT Ty = Arg.getValueType();
3760 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
3761 setValue(&I, result);
3764 case Intrinsic::stacksave: {
3765 SDValue Op = getRoot();
3766 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
3767 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
3769 DAG.setRoot(Tmp.getValue(1));
3772 case Intrinsic::stackrestore: {
3773 SDValue Tmp = getValue(I.getOperand(1));
3774 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
3777 case Intrinsic::var_annotation:
3778 // Discard annotate attributes
3781 case Intrinsic::init_trampoline: {
3782 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
3786 Ops[1] = getValue(I.getOperand(1));
3787 Ops[2] = getValue(I.getOperand(2));
3788 Ops[3] = getValue(I.getOperand(3));
3789 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3790 Ops[5] = DAG.getSrcValue(F);
3792 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
3793 DAG.getNodeValueTypes(TLI.getPointerTy(),
3798 DAG.setRoot(Tmp.getValue(1));
3802 case Intrinsic::gcroot:
3804 Value *Alloca = I.getOperand(1);
3805 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3807 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
3808 GFI->addStackRoot(FI->getIndex(), TypeMap);
3812 case Intrinsic::gcread:
3813 case Intrinsic::gcwrite:
3814 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
3817 case Intrinsic::flt_rounds: {
3818 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
3822 case Intrinsic::trap: {
3823 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3826 case Intrinsic::prefetch: {
3829 Ops[1] = getValue(I.getOperand(1));
3830 Ops[2] = getValue(I.getOperand(2));
3831 Ops[3] = getValue(I.getOperand(3));
3832 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3836 case Intrinsic::memory_barrier: {
3839 for (int x = 1; x < 6; ++x)
3840 Ops[x] = getValue(I.getOperand(x));
3842 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3845 case Intrinsic::atomic_cmp_swap: {
3846 SDValue Root = getRoot();
3848 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3850 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_8, Root,
3851 getValue(I.getOperand(1)),
3852 getValue(I.getOperand(2)),
3853 getValue(I.getOperand(3)),
3857 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_16, Root,
3858 getValue(I.getOperand(1)),
3859 getValue(I.getOperand(2)),
3860 getValue(I.getOperand(3)),
3864 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_32, Root,
3865 getValue(I.getOperand(1)),
3866 getValue(I.getOperand(2)),
3867 getValue(I.getOperand(3)),
3871 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_64, Root,
3872 getValue(I.getOperand(1)),
3873 getValue(I.getOperand(2)),
3874 getValue(I.getOperand(3)),
3878 assert(0 && "Invalid atomic type");
3882 DAG.setRoot(L.getValue(1));
3885 case Intrinsic::atomic_load_add:
3886 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3888 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_8);
3890 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_16);
3892 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_32);
3894 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_64);
3896 assert(0 && "Invalid atomic type");
3899 case Intrinsic::atomic_load_sub:
3900 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3902 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_8);
3904 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_16);
3906 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_32);
3908 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_64);
3910 assert(0 && "Invalid atomic type");
3913 case Intrinsic::atomic_load_or:
3914 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3916 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_8);
3918 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_16);
3920 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_32);
3922 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_64);
3924 assert(0 && "Invalid atomic type");
3927 case Intrinsic::atomic_load_xor:
3928 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3930 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_8);
3932 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_16);
3934 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_32);
3936 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_64);
3938 assert(0 && "Invalid atomic type");
3941 case Intrinsic::atomic_load_and:
3942 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3944 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_8);
3946 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_16);
3948 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_32);
3950 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_64);
3952 assert(0 && "Invalid atomic type");
3955 case Intrinsic::atomic_load_nand:
3956 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3958 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_8);
3960 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_16);
3962 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_32);
3964 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_64);
3966 assert(0 && "Invalid atomic type");
3969 case Intrinsic::atomic_load_max:
3970 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3972 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_8);
3974 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_16);
3976 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_32);
3978 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_64);
3980 assert(0 && "Invalid atomic type");
3983 case Intrinsic::atomic_load_min:
3984 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3986 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_8);
3988 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_16);
3990 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_32);
3992 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_64);
3994 assert(0 && "Invalid atomic type");
3997 case Intrinsic::atomic_load_umin:
3998 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4000 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_8);
4002 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_16);
4004 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_32);
4006 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_64);
4008 assert(0 && "Invalid atomic type");
4011 case Intrinsic::atomic_load_umax:
4012 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4014 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_8);
4016 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_16);
4018 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_32);
4020 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_64);
4022 assert(0 && "Invalid atomic type");
4025 case Intrinsic::atomic_swap:
4026 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4028 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_8);
4030 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_16);
4032 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_32);
4034 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_64);
4036 assert(0 && "Invalid atomic type");
4043 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4045 MachineBasicBlock *LandingPad) {
4046 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4047 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4048 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4049 unsigned BeginLabel = 0, EndLabel = 0;
4051 TargetLowering::ArgListTy Args;
4052 TargetLowering::ArgListEntry Entry;
4053 Args.reserve(CS.arg_size());
4054 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4056 SDValue ArgNode = getValue(*i);
4057 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4059 unsigned attrInd = i - CS.arg_begin() + 1;
4060 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4061 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4062 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4063 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4064 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4065 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4066 Entry.Alignment = CS.getParamAlignment(attrInd);
4067 Args.push_back(Entry);
4070 if (LandingPad && MMI) {
4071 // Insert a label before the invoke call to mark the try range. This can be
4072 // used to detect deletion of the invoke via the MachineModuleInfo.
4073 BeginLabel = MMI->NextLabelID();
4074 // Both PendingLoads and PendingExports must be flushed here;
4075 // this call might not return.
4077 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
4080 std::pair<SDValue,SDValue> Result =
4081 TLI.LowerCallTo(getRoot(), CS.getType(),
4082 CS.paramHasAttr(0, Attribute::SExt),
4083 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4084 CS.paramHasAttr(0, Attribute::InReg),
4085 CS.getCallingConv(),
4086 IsTailCall && PerformTailCallOpt,
4088 if (CS.getType() != Type::VoidTy)
4089 setValue(CS.getInstruction(), Result.first);
4090 DAG.setRoot(Result.second);
4092 if (LandingPad && MMI) {
4093 // Insert a label at the end of the invoke call to mark the try range. This
4094 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4095 EndLabel = MMI->NextLabelID();
4096 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
4098 // Inform MachineModuleInfo of range.
4099 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4104 void SelectionDAGLowering::visitCall(CallInst &I) {
4105 const char *RenameFn = 0;
4106 if (Function *F = I.getCalledFunction()) {
4107 if (F->isDeclaration()) {
4108 if (unsigned IID = F->getIntrinsicID()) {
4109 RenameFn = visitIntrinsicCall(I, IID);
4115 // Check for well-known libc/libm calls. If the function is internal, it
4116 // can't be a library call.
4117 unsigned NameLen = F->getNameLen();
4118 if (!F->hasInternalLinkage() && NameLen) {
4119 const char *NameStr = F->getNameStart();
4120 if (NameStr[0] == 'c' &&
4121 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4122 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4123 if (I.getNumOperands() == 3 && // Basic sanity checks.
4124 I.getOperand(1)->getType()->isFloatingPoint() &&
4125 I.getType() == I.getOperand(1)->getType() &&
4126 I.getType() == I.getOperand(2)->getType()) {
4127 SDValue LHS = getValue(I.getOperand(1));
4128 SDValue RHS = getValue(I.getOperand(2));
4129 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
4133 } else if (NameStr[0] == 'f' &&
4134 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4135 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4136 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4137 if (I.getNumOperands() == 2 && // Basic sanity checks.
4138 I.getOperand(1)->getType()->isFloatingPoint() &&
4139 I.getType() == I.getOperand(1)->getType()) {
4140 SDValue Tmp = getValue(I.getOperand(1));
4141 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
4144 } else if (NameStr[0] == 's' &&
4145 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4146 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4147 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4148 if (I.getNumOperands() == 2 && // Basic sanity checks.
4149 I.getOperand(1)->getType()->isFloatingPoint() &&
4150 I.getType() == I.getOperand(1)->getType()) {
4151 SDValue Tmp = getValue(I.getOperand(1));
4152 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
4155 } else if (NameStr[0] == 'c' &&
4156 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4157 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4158 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4159 if (I.getNumOperands() == 2 && // Basic sanity checks.
4160 I.getOperand(1)->getType()->isFloatingPoint() &&
4161 I.getType() == I.getOperand(1)->getType()) {
4162 SDValue Tmp = getValue(I.getOperand(1));
4163 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
4168 } else if (isa<InlineAsm>(I.getOperand(0))) {
4175 Callee = getValue(I.getOperand(0));
4177 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
4179 LowerCallTo(&I, Callee, I.isTailCall());
4183 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4184 /// this value and returns the result as a ValueVT value. This uses
4185 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4186 /// If the Flag pointer is NULL, no flag is used.
4187 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
4189 SDValue *Flag) const {
4190 // Assemble the legal parts into the final values.
4191 SmallVector<SDValue, 4> Values(ValueVTs.size());
4192 SmallVector<SDValue, 8> Parts;
4193 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4194 // Copy the legal parts from the registers.
4195 MVT ValueVT = ValueVTs[Value];
4196 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4197 MVT RegisterVT = RegVTs[Value];
4199 Parts.resize(NumRegs);
4200 for (unsigned i = 0; i != NumRegs; ++i) {
4203 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
4205 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
4206 *Flag = P.getValue(2);
4208 Chain = P.getValue(1);
4210 // If the source register was virtual and if we know something about it,
4211 // add an assert node.
4212 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4213 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4214 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4215 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4216 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4217 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4219 unsigned RegSize = RegisterVT.getSizeInBits();
4220 unsigned NumSignBits = LOI.NumSignBits;
4221 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4223 // FIXME: We capture more information than the dag can represent. For
4224 // now, just use the tightest assertzext/assertsext possible.
4226 MVT FromVT(MVT::Other);
4227 if (NumSignBits == RegSize)
4228 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4229 else if (NumZeroBits >= RegSize-1)
4230 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4231 else if (NumSignBits > RegSize-8)
4232 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4233 else if (NumZeroBits >= RegSize-9)
4234 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4235 else if (NumSignBits > RegSize-16)
4236 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
4237 else if (NumZeroBits >= RegSize-17)
4238 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
4239 else if (NumSignBits > RegSize-32)
4240 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
4241 else if (NumZeroBits >= RegSize-33)
4242 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
4244 if (FromVT != MVT::Other) {
4245 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
4246 RegisterVT, P, DAG.getValueType(FromVT));
4255 Values[Value] = getCopyFromParts(DAG, Parts.begin(), NumRegs, RegisterVT,
4261 return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4262 &Values[0], ValueVTs.size());
4265 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4266 /// specified value into the registers specified by this object. This uses
4267 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4268 /// If the Flag pointer is NULL, no flag is used.
4269 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
4270 SDValue &Chain, SDValue *Flag) const {
4271 // Get the list of the values's legal parts.
4272 unsigned NumRegs = Regs.size();
4273 SmallVector<SDValue, 8> Parts(NumRegs);
4274 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4275 MVT ValueVT = ValueVTs[Value];
4276 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4277 MVT RegisterVT = RegVTs[Value];
4279 getCopyToParts(DAG, Val.getValue(Val.getResNo() + Value),
4280 &Parts[Part], NumParts, RegisterVT);
4284 // Copy the parts into the registers.
4285 SmallVector<SDValue, 8> Chains(NumRegs);
4286 for (unsigned i = 0; i != NumRegs; ++i) {
4289 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
4291 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
4292 *Flag = Part.getValue(1);
4294 Chains[i] = Part.getValue(0);
4297 if (NumRegs == 1 || Flag)
4298 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4299 // flagged to it. That is the CopyToReg nodes and the user are considered
4300 // a single scheduling unit. If we create a TokenFactor and return it as
4301 // chain, then the TokenFactor is both a predecessor (operand) of the
4302 // user as well as a successor (the TF operands are flagged to the user).
4303 // c1, f1 = CopyToReg
4304 // c2, f2 = CopyToReg
4305 // c3 = TokenFactor c1, c2
4308 Chain = Chains[NumRegs-1];
4310 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
4313 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
4314 /// operand list. This adds the code marker and includes the number of
4315 /// values added into it.
4316 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
4317 std::vector<SDValue> &Ops) const {
4318 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4319 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
4320 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4321 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4322 MVT RegisterVT = RegVTs[Value];
4323 for (unsigned i = 0; i != NumRegs; ++i) {
4324 assert(Reg < Regs.size() && "Mismatch in # registers expected");
4325 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
4330 /// isAllocatableRegister - If the specified register is safe to allocate,
4331 /// i.e. it isn't a stack pointer or some other special register, return the
4332 /// register class for the register. Otherwise, return null.
4333 static const TargetRegisterClass *
4334 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4335 const TargetLowering &TLI,
4336 const TargetRegisterInfo *TRI) {
4337 MVT FoundVT = MVT::Other;
4338 const TargetRegisterClass *FoundRC = 0;
4339 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4340 E = TRI->regclass_end(); RCI != E; ++RCI) {
4341 MVT ThisVT = MVT::Other;
4343 const TargetRegisterClass *RC = *RCI;
4344 // If none of the the value types for this register class are valid, we
4345 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4346 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4348 if (TLI.isTypeLegal(*I)) {
4349 // If we have already found this register in a different register class,
4350 // choose the one with the largest VT specified. For example, on
4351 // PowerPC, we favor f64 register classes over f32.
4352 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4359 if (ThisVT == MVT::Other) continue;
4361 // NOTE: This isn't ideal. In particular, this might allocate the
4362 // frame pointer in functions that need it (due to them not being taken
4363 // out of allocation, because a variable sized allocation hasn't been seen
4364 // yet). This is a slight code pessimization, but should still work.
4365 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4366 E = RC->allocation_order_end(MF); I != E; ++I)
4368 // We found a matching register class. Keep looking at others in case
4369 // we find one with larger registers that this physreg is also in.
4380 /// AsmOperandInfo - This contains information for each constraint that we are
4382 struct VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4383 public TargetLowering::AsmOperandInfo {
4384 /// CallOperand - If this is the result output operand or a clobber
4385 /// this is null, otherwise it is the incoming operand to the CallInst.
4386 /// This gets modified as the asm is processed.
4387 SDValue CallOperand;
4389 /// AssignedRegs - If this is a register or register class operand, this
4390 /// contains the set of register corresponding to the operand.
4391 RegsForValue AssignedRegs;
4393 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4394 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4397 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4398 /// busy in OutputRegs/InputRegs.
4399 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4400 std::set<unsigned> &OutputRegs,
4401 std::set<unsigned> &InputRegs,
4402 const TargetRegisterInfo &TRI) const {
4404 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4405 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4408 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4409 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4413 /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4414 /// corresponds to. If there is no Value* for this operand, it returns
4416 MVT getCallOperandValMVT(const TargetLowering &TLI,
4417 const TargetData *TD) const {
4418 if (CallOperandVal == 0) return MVT::Other;
4420 if (isa<BasicBlock>(CallOperandVal))
4421 return TLI.getPointerTy();
4423 const llvm::Type *OpTy = CallOperandVal->getType();
4425 // If this is an indirect operand, the operand is a pointer to the
4428 OpTy = cast<PointerType>(OpTy)->getElementType();
4430 // If OpTy is not a single value, it may be a struct/union that we
4431 // can tile with integers.
4432 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4433 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4442 OpTy = IntegerType::get(BitSize);
4447 return TLI.getValueType(OpTy, true);
4451 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4453 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4454 const TargetRegisterInfo &TRI) {
4455 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4457 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4458 for (; *Aliases; ++Aliases)
4459 Regs.insert(*Aliases);
4462 } // end llvm namespace.
4465 /// GetRegistersForValue - Assign registers (virtual or physical) for the
4466 /// specified operand. We prefer to assign virtual registers, to allow the
4467 /// register allocator handle the assignment process. However, if the asm uses
4468 /// features that we can't model on machineinstrs, we have SDISel do the
4469 /// allocation. This produces generally horrible, but correct, code.
4471 /// OpInfo describes the operand.
4472 /// Input and OutputRegs are the set of already allocated physical registers.
4474 void SelectionDAGLowering::
4475 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
4476 std::set<unsigned> &OutputRegs,
4477 std::set<unsigned> &InputRegs) {
4478 // Compute whether this value requires an input register, an output register,
4480 bool isOutReg = false;
4481 bool isInReg = false;
4482 switch (OpInfo.Type) {
4483 case InlineAsm::isOutput:
4486 // If there is an input constraint that matches this, we need to reserve
4487 // the input register so no other inputs allocate to it.
4488 isInReg = OpInfo.hasMatchingInput();
4490 case InlineAsm::isInput:
4494 case InlineAsm::isClobber:
4501 MachineFunction &MF = DAG.getMachineFunction();
4502 SmallVector<unsigned, 4> Regs;
4504 // If this is a constraint for a single physreg, or a constraint for a
4505 // register class, find it.
4506 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4507 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4508 OpInfo.ConstraintVT);
4510 unsigned NumRegs = 1;
4511 if (OpInfo.ConstraintVT != MVT::Other) {
4512 // If this is a FP input in an integer register (or visa versa) insert a bit
4513 // cast of the input value. More generally, handle any case where the input
4514 // value disagrees with the register class we plan to stick this in.
4515 if (OpInfo.Type == InlineAsm::isInput &&
4516 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4517 // Try to convert to the first MVT that the reg class contains. If the
4518 // types are identical size, use a bitcast to convert (e.g. two differing
4520 MVT RegVT = *PhysReg.second->vt_begin();
4521 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
4522 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4523 OpInfo.CallOperand);
4524 OpInfo.ConstraintVT = RegVT;
4525 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4526 // If the input is a FP value and we want it in FP registers, do a
4527 // bitcast to the corresponding integer type. This turns an f64 value
4528 // into i64, which can be passed with two i32 values on a 32-bit
4530 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
4531 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4532 OpInfo.CallOperand);
4533 OpInfo.ConstraintVT = RegVT;
4537 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
4541 MVT ValueVT = OpInfo.ConstraintVT;
4543 // If this is a constraint for a specific physical register, like {r17},
4545 if (PhysReg.first) {
4546 if (OpInfo.ConstraintVT == MVT::Other)
4547 ValueVT = *PhysReg.second->vt_begin();
4549 // Get the actual register value type. This is important, because the user
4550 // may have asked for (e.g.) the AX register in i32 type. We need to
4551 // remember that AX is actually i16 to get the right extension.
4552 RegVT = *PhysReg.second->vt_begin();
4554 // This is a explicit reference to a physical register.
4555 Regs.push_back(PhysReg.first);
4557 // If this is an expanded reference, add the rest of the regs to Regs.
4559 TargetRegisterClass::iterator I = PhysReg.second->begin();
4560 for (; *I != PhysReg.first; ++I)
4561 assert(I != PhysReg.second->end() && "Didn't find reg!");
4563 // Already added the first reg.
4565 for (; NumRegs; --NumRegs, ++I) {
4566 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
4570 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4571 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4572 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4576 // Otherwise, if this was a reference to an LLVM register class, create vregs
4577 // for this reference.
4578 std::vector<unsigned> RegClassRegs;
4579 const TargetRegisterClass *RC = PhysReg.second;
4581 // If this is a tied register, our regalloc doesn't know how to maintain
4582 // the constraint, so we have to pick a register to pin the input/output to.
4583 // If it isn't a matched constraint, go ahead and create vreg and let the
4584 // regalloc do its thing.
4585 if (!OpInfo.hasMatchingInput()) {
4586 RegVT = *PhysReg.second->vt_begin();
4587 if (OpInfo.ConstraintVT == MVT::Other)
4590 // Create the appropriate number of virtual registers.
4591 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4592 for (; NumRegs; --NumRegs)
4593 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
4595 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4599 // Otherwise, we can't allocate it. Let the code below figure out how to
4600 // maintain these constraints.
4601 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4604 // This is a reference to a register class that doesn't directly correspond
4605 // to an LLVM register class. Allocate NumRegs consecutive, available,
4606 // registers from the class.
4607 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4608 OpInfo.ConstraintVT);
4611 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4612 unsigned NumAllocated = 0;
4613 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4614 unsigned Reg = RegClassRegs[i];
4615 // See if this register is available.
4616 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4617 (isInReg && InputRegs.count(Reg))) { // Already used.
4618 // Make sure we find consecutive registers.
4623 // Check to see if this register is allocatable (i.e. don't give out the
4626 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4627 if (!RC) { // Couldn't allocate this register.
4628 // Reset NumAllocated to make sure we return consecutive registers.
4634 // Okay, this register is good, we can use it.
4637 // If we allocated enough consecutive registers, succeed.
4638 if (NumAllocated == NumRegs) {
4639 unsigned RegStart = (i-NumAllocated)+1;
4640 unsigned RegEnd = i+1;
4641 // Mark all of the allocated registers used.
4642 for (unsigned i = RegStart; i != RegEnd; ++i)
4643 Regs.push_back(RegClassRegs[i]);
4645 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
4646 OpInfo.ConstraintVT);
4647 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4652 // Otherwise, we couldn't allocate enough registers for this.
4655 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
4656 /// processed uses a memory 'm' constraint.
4658 hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
4659 TargetLowering &TLI) {
4660 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
4661 InlineAsm::ConstraintInfo &CI = CInfos[i];
4662 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
4663 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
4664 if (CType == TargetLowering::C_Memory)
4672 /// visitInlineAsm - Handle a call to an InlineAsm object.
4674 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4675 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4677 /// ConstraintOperands - Information about all of the constraints.
4678 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
4680 SDValue Chain = getRoot();
4683 std::set<unsigned> OutputRegs, InputRegs;
4685 // Do a prepass over the constraints, canonicalizing them, and building up the
4686 // ConstraintOperands list.
4687 std::vector<InlineAsm::ConstraintInfo>
4688 ConstraintInfos = IA->ParseConstraints();
4690 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
4692 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4693 unsigned ResNo = 0; // ResNo - The result number of the next output.
4694 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4695 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4696 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
4698 MVT OpVT = MVT::Other;
4700 // Compute the value type for each operand.
4701 switch (OpInfo.Type) {
4702 case InlineAsm::isOutput:
4703 // Indirect outputs just consume an argument.
4704 if (OpInfo.isIndirect) {
4705 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4709 // The return value of the call is this value. As such, there is no
4710 // corresponding argument.
4711 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4712 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4713 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4715 assert(ResNo == 0 && "Asm only has one result!");
4716 OpVT = TLI.getValueType(CS.getType());
4720 case InlineAsm::isInput:
4721 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4723 case InlineAsm::isClobber:
4728 // If this is an input or an indirect output, process the call argument.
4729 // BasicBlocks are labels, currently appearing only in asm's.
4730 if (OpInfo.CallOperandVal) {
4731 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
4732 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
4734 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
4737 OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
4740 OpInfo.ConstraintVT = OpVT;
4743 // Second pass over the constraints: compute which constraint option to use
4744 // and assign registers to constraints that want a specific physreg.
4745 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4746 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4748 // If this is an output operand with a matching input operand, look up the
4749 // matching input. It might have a different type (e.g. the output might be
4750 // i32 and the input i64) and we need to pick the larger width to ensure we
4751 // reserve the right number of registers.
4752 if (OpInfo.hasMatchingInput()) {
4753 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4754 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
4755 assert(OpInfo.ConstraintVT.isInteger() &&
4756 Input.ConstraintVT.isInteger() &&
4757 "Asm constraints must be the same or different sized integers");
4758 if (OpInfo.ConstraintVT.getSizeInBits() <
4759 Input.ConstraintVT.getSizeInBits())
4760 OpInfo.ConstraintVT = Input.ConstraintVT;
4762 Input.ConstraintVT = OpInfo.ConstraintVT;
4766 // Compute the constraint code and ConstraintType to use.
4767 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
4769 // If this is a memory input, and if the operand is not indirect, do what we
4770 // need to to provide an address for the memory input.
4771 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4772 !OpInfo.isIndirect) {
4773 assert(OpInfo.Type == InlineAsm::isInput &&
4774 "Can only indirectify direct input operands!");
4776 // Memory operands really want the address of the value. If we don't have
4777 // an indirect input, put it in the constpool if we can, otherwise spill
4778 // it to a stack slot.
4780 // If the operand is a float, integer, or vector constant, spill to a
4781 // constant pool entry to get its address.
4782 Value *OpVal = OpInfo.CallOperandVal;
4783 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4784 isa<ConstantVector>(OpVal)) {
4785 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4786 TLI.getPointerTy());
4788 // Otherwise, create a stack slot and emit a store to it before the
4790 const Type *Ty = OpVal->getType();
4791 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
4792 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4793 MachineFunction &MF = DAG.getMachineFunction();
4794 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4795 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4796 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4797 OpInfo.CallOperand = StackSlot;
4800 // There is no longer a Value* corresponding to this operand.
4801 OpInfo.CallOperandVal = 0;
4802 // It is now an indirect operand.
4803 OpInfo.isIndirect = true;
4806 // If this constraint is for a specific register, allocate it before
4808 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4809 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
4811 ConstraintInfos.clear();
4814 // Second pass - Loop over all of the operands, assigning virtual or physregs
4815 // to register class operands.
4816 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4817 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4819 // C_Register operands have already been allocated, Other/Memory don't need
4821 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4822 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
4825 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4826 std::vector<SDValue> AsmNodeOperands;
4827 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
4828 AsmNodeOperands.push_back(
4829 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4832 // Loop over all of the inputs, copying the operand values into the
4833 // appropriate registers and processing the output regs.
4834 RegsForValue RetValRegs;
4836 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4837 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4839 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4840 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4842 switch (OpInfo.Type) {
4843 case InlineAsm::isOutput: {
4844 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4845 OpInfo.ConstraintType != TargetLowering::C_Register) {
4846 // Memory output, or 'other' output (e.g. 'X' constraint).
4847 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
4849 // Add information to the INLINEASM node to know about this output.
4850 unsigned ResOpType = 4/*MEM*/ | (1<<3);
4851 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4852 TLI.getPointerTy()));
4853 AsmNodeOperands.push_back(OpInfo.CallOperand);
4857 // Otherwise, this is a register or register class output.
4859 // Copy the output from the appropriate register. Find a register that
4861 if (OpInfo.AssignedRegs.Regs.empty()) {
4862 cerr << "Couldn't allocate output reg for constraint '"
4863 << OpInfo.ConstraintCode << "'!\n";
4867 // If this is an indirect operand, store through the pointer after the
4869 if (OpInfo.isIndirect) {
4870 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
4871 OpInfo.CallOperandVal));
4873 // This is the result value of the call.
4874 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4875 // Concatenate this output onto the outputs list.
4876 RetValRegs.append(OpInfo.AssignedRegs);
4879 // Add information to the INLINEASM node to know that this register is
4881 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
4882 6 /* EARLYCLOBBER REGDEF */ :
4884 DAG, AsmNodeOperands);
4887 case InlineAsm::isInput: {
4888 SDValue InOperandVal = OpInfo.CallOperand;
4890 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
4891 // If this is required to match an output register we have already set,
4892 // just use its register.
4893 unsigned OperandNo = OpInfo.getMatchedOperand();
4895 // Scan until we find the definition we already emitted of this operand.
4896 // When we find it, create a RegsForValue operand.
4897 unsigned CurOp = 2; // The first operand.
4898 for (; OperandNo; --OperandNo) {
4899 // Advance to the next operand.
4901 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
4902 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4903 (NumOps & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
4904 (NumOps & 7) == 4 /*MEM*/) &&
4905 "Skipped past definitions?");
4906 CurOp += (NumOps>>3)+1;
4910 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
4911 if ((NumOps & 7) == 2 /*REGDEF*/
4912 || (NumOps & 7) == 6 /* EARLYCLOBBER REGDEF */) {
4913 // Add NumOps>>3 registers to MatchedRegs.
4914 RegsForValue MatchedRegs;
4915 MatchedRegs.TLI = &TLI;
4916 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4917 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
4918 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4920 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4921 MatchedRegs.Regs.push_back(Reg);
4924 // Use the produced MatchedRegs object to
4925 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4926 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4929 assert(((NumOps & 7) == 4) && "Unknown matching constraint!");
4930 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4931 // Add information to the INLINEASM node to know about this input.
4932 AsmNodeOperands.push_back(DAG.getTargetConstant(NumOps,
4933 TLI.getPointerTy()));
4934 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4939 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
4940 assert(!OpInfo.isIndirect &&
4941 "Don't know how to handle indirect other inputs yet!");
4943 std::vector<SDValue> Ops;
4944 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4945 hasMemory, Ops, DAG);
4947 cerr << "Invalid operand for inline asm constraint '"
4948 << OpInfo.ConstraintCode << "'!\n";
4952 // Add information to the INLINEASM node to know about this input.
4953 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
4954 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4955 TLI.getPointerTy()));
4956 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
4958 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
4959 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
4960 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4961 "Memory operands expect pointer values");
4963 // Add information to the INLINEASM node to know about this input.
4964 unsigned ResOpType = 4/*MEM*/ | (1<<3);
4965 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4966 TLI.getPointerTy()));
4967 AsmNodeOperands.push_back(InOperandVal);
4971 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4972 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4973 "Unknown constraint type!");
4974 assert(!OpInfo.isIndirect &&
4975 "Don't know how to handle indirect register inputs yet!");
4977 // Copy the input into the appropriate registers.
4978 if (OpInfo.AssignedRegs.Regs.empty()) {
4979 cerr << "Couldn't allocate output reg for constraint '"
4980 << OpInfo.ConstraintCode << "'!\n";
4984 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4986 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/,
4987 DAG, AsmNodeOperands);
4990 case InlineAsm::isClobber: {
4991 // Add the clobbered value to the operand list, so that the register
4992 // allocator is aware that the physreg got clobbered.
4993 if (!OpInfo.AssignedRegs.Regs.empty())
4994 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
4995 DAG, AsmNodeOperands);
5001 // Finish up input operands.
5002 AsmNodeOperands[0] = Chain;
5003 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5005 Chain = DAG.getNode(ISD::INLINEASM,
5006 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
5007 &AsmNodeOperands[0], AsmNodeOperands.size());
5008 Flag = Chain.getValue(1);
5010 // If this asm returns a register value, copy the result from that register
5011 // and set it as the value of the call.
5012 if (!RetValRegs.Regs.empty()) {
5013 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
5015 // FIXME: Why don't we do this for inline asms with MRVs?
5016 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5017 MVT ResultType = TLI.getValueType(CS.getType());
5019 // If any of the results of the inline asm is a vector, it may have the
5020 // wrong width/num elts. This can happen for register classes that can
5021 // contain multiple different value types. The preg or vreg allocated may
5022 // not have the same VT as was expected. Convert it to the right type
5023 // with bit_convert.
5024 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5025 Val = DAG.getNode(ISD::BIT_CONVERT, ResultType, Val);
5027 } else if (ResultType != Val.getValueType() &&
5028 ResultType.isInteger() && Val.getValueType().isInteger()) {
5029 // If a result value was tied to an input value, the computed result may
5030 // have a wider width than the expected result. Extract the relevant
5032 Val = DAG.getNode(ISD::TRUNCATE, ResultType, Val);
5035 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
5038 setValue(CS.getInstruction(), Val);
5041 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5043 // Process indirect outputs, first output all of the flagged copies out of
5045 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5046 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5047 Value *Ptr = IndirectStoresToEmit[i].second;
5048 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
5049 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5052 // Emit the non-flagged stores from the physregs.
5053 SmallVector<SDValue, 8> OutChains;
5054 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5055 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
5056 getValue(StoresToEmit[i].second),
5057 StoresToEmit[i].second, 0));
5058 if (!OutChains.empty())
5059 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5060 &OutChains[0], OutChains.size());
5065 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5066 SDValue Src = getValue(I.getOperand(0));
5068 MVT IntPtr = TLI.getPointerTy();
5070 if (IntPtr.bitsLT(Src.getValueType()))
5071 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
5072 else if (IntPtr.bitsGT(Src.getValueType()))
5073 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
5075 // Scale the source by the type size.
5076 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
5077 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
5078 Src, DAG.getIntPtrConstant(ElementSize));
5080 TargetLowering::ArgListTy Args;
5081 TargetLowering::ArgListEntry Entry;
5083 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5084 Args.push_back(Entry);
5086 std::pair<SDValue,SDValue> Result =
5087 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
5088 CallingConv::C, PerformTailCallOpt,
5089 DAG.getExternalSymbol("malloc", IntPtr),
5091 setValue(&I, Result.first); // Pointers always fit in registers
5092 DAG.setRoot(Result.second);
5095 void SelectionDAGLowering::visitFree(FreeInst &I) {
5096 TargetLowering::ArgListTy Args;
5097 TargetLowering::ArgListEntry Entry;
5098 Entry.Node = getValue(I.getOperand(0));
5099 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5100 Args.push_back(Entry);
5101 MVT IntPtr = TLI.getPointerTy();
5102 std::pair<SDValue,SDValue> Result =
5103 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
5104 CallingConv::C, PerformTailCallOpt,
5105 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
5106 DAG.setRoot(Result.second);
5109 void SelectionDAGLowering::visitVAStart(CallInst &I) {
5110 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
5111 getValue(I.getOperand(1)),
5112 DAG.getSrcValue(I.getOperand(1))));
5115 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
5116 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
5117 getValue(I.getOperand(0)),
5118 DAG.getSrcValue(I.getOperand(0)));
5120 DAG.setRoot(V.getValue(1));
5123 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
5124 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
5125 getValue(I.getOperand(1)),
5126 DAG.getSrcValue(I.getOperand(1))));
5129 void SelectionDAGLowering::visitVACopy(CallInst &I) {
5130 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
5131 getValue(I.getOperand(1)),
5132 getValue(I.getOperand(2)),
5133 DAG.getSrcValue(I.getOperand(1)),
5134 DAG.getSrcValue(I.getOperand(2))));
5137 /// TargetLowering::LowerArguments - This is the default LowerArguments
5138 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
5139 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
5140 /// integrated into SDISel.
5141 void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
5142 SmallVectorImpl<SDValue> &ArgValues) {
5143 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5144 SmallVector<SDValue, 3+16> Ops;
5145 Ops.push_back(DAG.getRoot());
5146 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5147 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5149 // Add one result value for each formal argument.
5150 SmallVector<MVT, 16> RetVals;
5152 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5154 SmallVector<MVT, 4> ValueVTs;
5155 ComputeValueVTs(*this, I->getType(), ValueVTs);
5156 for (unsigned Value = 0, NumValues = ValueVTs.size();
5157 Value != NumValues; ++Value) {
5158 MVT VT = ValueVTs[Value];
5159 const Type *ArgTy = VT.getTypeForMVT();
5160 ISD::ArgFlagsTy Flags;
5161 unsigned OriginalAlignment =
5162 getTargetData()->getABITypeAlignment(ArgTy);
5164 if (F.paramHasAttr(j, Attribute::ZExt))
5166 if (F.paramHasAttr(j, Attribute::SExt))
5168 if (F.paramHasAttr(j, Attribute::InReg))
5170 if (F.paramHasAttr(j, Attribute::StructRet))
5172 if (F.paramHasAttr(j, Attribute::ByVal)) {
5174 const PointerType *Ty = cast<PointerType>(I->getType());
5175 const Type *ElementTy = Ty->getElementType();
5176 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5177 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
5178 // For ByVal, alignment should be passed from FE. BE will guess if
5179 // this info is not there but there are cases it cannot get right.
5180 if (F.getParamAlignment(j))
5181 FrameAlign = F.getParamAlignment(j);
5182 Flags.setByValAlign(FrameAlign);
5183 Flags.setByValSize(FrameSize);
5185 if (F.paramHasAttr(j, Attribute::Nest))
5187 Flags.setOrigAlign(OriginalAlignment);
5189 MVT RegisterVT = getRegisterType(VT);
5190 unsigned NumRegs = getNumRegisters(VT);
5191 for (unsigned i = 0; i != NumRegs; ++i) {
5192 RetVals.push_back(RegisterVT);
5193 ISD::ArgFlagsTy MyFlags = Flags;
5194 if (NumRegs > 1 && i == 0)
5196 // if it isn't first piece, alignment must be 1
5198 MyFlags.setOrigAlign(1);
5199 Ops.push_back(DAG.getArgFlags(MyFlags));
5204 RetVals.push_back(MVT::Other);
5207 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
5208 DAG.getVTList(&RetVals[0], RetVals.size()),
5209 &Ops[0], Ops.size()).getNode();
5211 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5212 // allows exposing the loads that may be part of the argument access to the
5213 // first DAGCombiner pass.
5214 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
5216 // The number of results should match up, except that the lowered one may have
5217 // an extra flag result.
5218 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5219 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5220 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5221 && "Lowering produced unexpected number of results!");
5223 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5224 if (Result != TmpRes.getNode() && Result->use_empty()) {
5225 HandleSDNode Dummy(DAG.getRoot());
5226 DAG.RemoveDeadNode(Result);
5229 Result = TmpRes.getNode();
5231 unsigned NumArgRegs = Result->getNumValues() - 1;
5232 DAG.setRoot(SDValue(Result, NumArgRegs));
5234 // Set up the return result vector.
5237 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5239 SmallVector<MVT, 4> ValueVTs;
5240 ComputeValueVTs(*this, I->getType(), ValueVTs);
5241 for (unsigned Value = 0, NumValues = ValueVTs.size();
5242 Value != NumValues; ++Value) {
5243 MVT VT = ValueVTs[Value];
5244 MVT PartVT = getRegisterType(VT);
5246 unsigned NumParts = getNumRegisters(VT);
5247 SmallVector<SDValue, 4> Parts(NumParts);
5248 for (unsigned j = 0; j != NumParts; ++j)
5249 Parts[j] = SDValue(Result, i++);
5251 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5252 if (F.paramHasAttr(Idx, Attribute::SExt))
5253 AssertOp = ISD::AssertSext;
5254 else if (F.paramHasAttr(Idx, Attribute::ZExt))
5255 AssertOp = ISD::AssertZext;
5257 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
5261 assert(i == NumArgRegs && "Argument register count mismatch!");
5265 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
5266 /// implementation, which just inserts an ISD::CALL node, which is later custom
5267 /// lowered by the target to something concrete. FIXME: When all targets are
5268 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5269 std::pair<SDValue, SDValue>
5270 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5271 bool RetSExt, bool RetZExt, bool isVarArg,
5273 unsigned CallingConv, bool isTailCall,
5275 ArgListTy &Args, SelectionDAG &DAG) {
5276 assert((!isTailCall || PerformTailCallOpt) &&
5277 "isTailCall set when tail-call optimizations are disabled!");
5279 SmallVector<SDValue, 32> Ops;
5280 Ops.push_back(Chain); // Op#0 - Chain
5281 Ops.push_back(Callee);
5283 // Handle all of the outgoing arguments.
5284 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5285 SmallVector<MVT, 4> ValueVTs;
5286 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5287 for (unsigned Value = 0, NumValues = ValueVTs.size();
5288 Value != NumValues; ++Value) {
5289 MVT VT = ValueVTs[Value];
5290 const Type *ArgTy = VT.getTypeForMVT();
5291 SDValue Op = SDValue(Args[i].Node.getNode(),
5292 Args[i].Node.getResNo() + Value);
5293 ISD::ArgFlagsTy Flags;
5294 unsigned OriginalAlignment =
5295 getTargetData()->getABITypeAlignment(ArgTy);
5301 if (Args[i].isInReg)
5305 if (Args[i].isByVal) {
5307 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5308 const Type *ElementTy = Ty->getElementType();
5309 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5310 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
5311 // For ByVal, alignment should come from FE. BE will guess if this
5312 // info is not there but there are cases it cannot get right.
5313 if (Args[i].Alignment)
5314 FrameAlign = Args[i].Alignment;
5315 Flags.setByValAlign(FrameAlign);
5316 Flags.setByValSize(FrameSize);
5320 Flags.setOrigAlign(OriginalAlignment);
5322 MVT PartVT = getRegisterType(VT);
5323 unsigned NumParts = getNumRegisters(VT);
5324 SmallVector<SDValue, 4> Parts(NumParts);
5325 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5328 ExtendKind = ISD::SIGN_EXTEND;
5329 else if (Args[i].isZExt)
5330 ExtendKind = ISD::ZERO_EXTEND;
5332 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5334 for (unsigned i = 0; i != NumParts; ++i) {
5335 // if it isn't first piece, alignment must be 1
5336 ISD::ArgFlagsTy MyFlags = Flags;
5337 if (NumParts > 1 && i == 0)
5340 MyFlags.setOrigAlign(1);
5342 Ops.push_back(Parts[i]);
5343 Ops.push_back(DAG.getArgFlags(MyFlags));
5348 // Figure out the result value types. We start by making a list of
5349 // the potentially illegal return value types.
5350 SmallVector<MVT, 4> LoweredRetTys;
5351 SmallVector<MVT, 4> RetTys;
5352 ComputeValueVTs(*this, RetTy, RetTys);
5354 // Then we translate that to a list of legal types.
5355 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5357 MVT RegisterVT = getRegisterType(VT);
5358 unsigned NumRegs = getNumRegisters(VT);
5359 for (unsigned i = 0; i != NumRegs; ++i)
5360 LoweredRetTys.push_back(RegisterVT);
5363 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
5365 // Create the CALL node.
5366 SDValue Res = DAG.getCall(CallingConv, isVarArg, isTailCall, isInreg,
5367 DAG.getVTList(&LoweredRetTys[0],
5368 LoweredRetTys.size()),
5371 Chain = Res.getValue(LoweredRetTys.size() - 1);
5373 // Gather up the call result into a single value.
5374 if (RetTy != Type::VoidTy && !RetTys.empty()) {
5375 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5378 AssertOp = ISD::AssertSext;
5380 AssertOp = ISD::AssertZext;
5382 SmallVector<SDValue, 4> ReturnValues;
5384 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5386 MVT RegisterVT = getRegisterType(VT);
5387 unsigned NumRegs = getNumRegisters(VT);
5388 unsigned RegNoEnd = NumRegs + RegNo;
5389 SmallVector<SDValue, 4> Results;
5390 for (; RegNo != RegNoEnd; ++RegNo)
5391 Results.push_back(Res.getValue(RegNo));
5392 SDValue ReturnValue =
5393 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
5395 ReturnValues.push_back(ReturnValue);
5397 Res = DAG.getMergeValues(DAG.getVTList(&RetTys[0], RetTys.size()),
5398 &ReturnValues[0], ReturnValues.size());
5401 return std::make_pair(Res, Chain);
5404 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5405 assert(0 && "LowerOperation not implemented for this target!");
5411 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5412 SDValue Op = getValue(V);
5413 assert((Op.getOpcode() != ISD::CopyFromReg ||
5414 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5415 "Copy from a reg to the same reg!");
5416 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5418 RegsForValue RFV(TLI, Reg, V->getType());
5419 SDValue Chain = DAG.getEntryNode();
5420 RFV.getCopyToRegs(Op, DAG, Chain, 0);
5421 PendingExports.push_back(Chain);
5424 #include "llvm/CodeGen/SelectionDAGISel.h"
5426 void SelectionDAGISel::
5427 LowerArguments(BasicBlock *LLVMBB) {
5428 // If this is the entry block, emit arguments.
5429 Function &F = *LLVMBB->getParent();
5430 SDValue OldRoot = SDL->DAG.getRoot();
5431 SmallVector<SDValue, 16> Args;
5432 TLI.LowerArguments(F, SDL->DAG, Args);
5435 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5437 SmallVector<MVT, 4> ValueVTs;
5438 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5439 unsigned NumValues = ValueVTs.size();
5440 if (!AI->use_empty()) {
5441 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues));
5442 // If this argument is live outside of the entry block, insert a copy from
5443 // whereever we got it to the vreg that other BB's will reference it as.
5444 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5445 if (VMI != FuncInfo->ValueMap.end()) {
5446 SDL->CopyValueToVirtualRegister(AI, VMI->second);
5452 // Finally, if the target has anything special to do, allow it to do so.
5453 // FIXME: this should insert code into the DAG!
5454 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5457 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5458 /// ensure constants are generated when needed. Remember the virtual registers
5459 /// that need to be added to the Machine PHI nodes as input. We cannot just
5460 /// directly add them, because expansion might result in multiple MBB's for one
5461 /// BB. As such, the start of the BB might correspond to a different MBB than
5465 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5466 TerminatorInst *TI = LLVMBB->getTerminator();
5468 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5470 // Check successor nodes' PHI nodes that expect a constant to be available
5472 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5473 BasicBlock *SuccBB = TI->getSuccessor(succ);
5474 if (!isa<PHINode>(SuccBB->begin())) continue;
5475 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5477 // If this terminator has multiple identical successors (common for
5478 // switches), only handle each succ once.
5479 if (!SuccsHandled.insert(SuccMBB)) continue;
5481 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5484 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5485 // nodes and Machine PHI nodes, but the incoming operands have not been
5487 for (BasicBlock::iterator I = SuccBB->begin();
5488 (PN = dyn_cast<PHINode>(I)); ++I) {
5489 // Ignore dead phi's.
5490 if (PN->use_empty()) continue;
5493 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5495 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5496 unsigned &RegOut = SDL->ConstantsOut[C];
5498 RegOut = FuncInfo->CreateRegForValue(C);
5499 SDL->CopyValueToVirtualRegister(C, RegOut);
5503 Reg = FuncInfo->ValueMap[PHIOp];
5505 assert(isa<AllocaInst>(PHIOp) &&
5506 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5507 "Didn't codegen value into a register!??");
5508 Reg = FuncInfo->CreateRegForValue(PHIOp);
5509 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5513 // Remember that this register needs to added to the machine PHI node as
5514 // the input for this MBB.
5515 SmallVector<MVT, 4> ValueVTs;
5516 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5517 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5518 MVT VT = ValueVTs[vti];
5519 unsigned NumRegisters = TLI.getNumRegisters(VT);
5520 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5521 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5522 Reg += NumRegisters;
5526 SDL->ConstantsOut.clear();
5529 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5530 /// supports legal types, and it emits MachineInstrs directly instead of
5531 /// creating SelectionDAG nodes.
5534 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5536 TerminatorInst *TI = LLVMBB->getTerminator();
5538 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5539 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5541 // Check successor nodes' PHI nodes that expect a constant to be available
5543 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5544 BasicBlock *SuccBB = TI->getSuccessor(succ);
5545 if (!isa<PHINode>(SuccBB->begin())) continue;
5546 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5548 // If this terminator has multiple identical successors (common for
5549 // switches), only handle each succ once.
5550 if (!SuccsHandled.insert(SuccMBB)) continue;
5552 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5555 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5556 // nodes and Machine PHI nodes, but the incoming operands have not been
5558 for (BasicBlock::iterator I = SuccBB->begin();
5559 (PN = dyn_cast<PHINode>(I)); ++I) {
5560 // Ignore dead phi's.
5561 if (PN->use_empty()) continue;
5563 // Only handle legal types. Two interesting things to note here. First,
5564 // by bailing out early, we may leave behind some dead instructions,
5565 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5566 // own moves. Second, this check is necessary becuase FastISel doesn't
5567 // use CreateRegForValue to create registers, so it always creates
5568 // exactly one register for each non-void instruction.
5569 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5570 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
5573 VT = TLI.getTypeToTransformTo(VT);
5575 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5580 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5582 unsigned Reg = F->getRegForValue(PHIOp);
5584 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5587 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));