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,
520 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
521 TargetLowering &TLI = DAG.getTargetLoweringInfo();
522 MVT PtrVT = TLI.getPointerTy();
523 MVT ValueVT = Val.getValueType();
524 unsigned PartBits = PartVT.getSizeInBits();
525 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
530 if (!ValueVT.isVector()) {
531 if (PartVT == ValueVT) {
532 assert(NumParts == 1 && "No-op copy with multiple parts!");
537 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
538 // If the parts cover more bits than the value has, promote the value.
539 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
540 assert(NumParts == 1 && "Do not know what to promote to!");
541 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
542 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
543 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
544 Val = DAG.getNode(ExtendKind, ValueVT, Val);
546 assert(0 && "Unknown mismatch!");
548 } else if (PartBits == ValueVT.getSizeInBits()) {
549 // Different types of the same size.
550 assert(NumParts == 1 && PartVT != ValueVT);
551 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
552 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
553 // If the parts cover less bits than value has, truncate the value.
554 if (PartVT.isInteger() && ValueVT.isInteger()) {
555 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
556 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
558 assert(0 && "Unknown mismatch!");
562 // The value may have changed - recompute ValueVT.
563 ValueVT = Val.getValueType();
564 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
565 "Failed to tile the value with PartVT!");
568 assert(PartVT == ValueVT && "Type conversion failed!");
573 // Expand the value into multiple parts.
574 if (NumParts & (NumParts - 1)) {
575 // The number of parts is not a power of 2. Split off and copy the tail.
576 assert(PartVT.isInteger() && ValueVT.isInteger() &&
577 "Do not know what to expand to!");
578 unsigned RoundParts = 1 << Log2_32(NumParts);
579 unsigned RoundBits = RoundParts * PartBits;
580 unsigned OddParts = NumParts - RoundParts;
581 SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
582 DAG.getConstant(RoundBits,
583 TLI.getShiftAmountTy()));
584 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
585 if (TLI.isBigEndian())
586 // The odd parts were reversed by getCopyToParts - unreverse them.
587 std::reverse(Parts + RoundParts, Parts + NumParts);
588 NumParts = RoundParts;
589 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
590 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
593 // The number of parts is a power of 2. Repeatedly bisect the value using
595 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
596 MVT::getIntegerVT(ValueVT.getSizeInBits()),
598 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
599 for (unsigned i = 0; i < NumParts; i += StepSize) {
600 unsigned ThisBits = StepSize * PartBits / 2;
601 MVT ThisVT = MVT::getIntegerVT (ThisBits);
602 SDValue &Part0 = Parts[i];
603 SDValue &Part1 = Parts[i+StepSize/2];
605 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
606 DAG.getConstant(1, PtrVT));
607 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
608 DAG.getConstant(0, PtrVT));
610 if (ThisBits == PartBits && ThisVT != PartVT) {
611 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
612 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
617 if (TLI.isBigEndian())
618 std::reverse(Parts, Parts + NumParts);
625 if (PartVT != ValueVT) {
626 if (PartVT.isVector()) {
627 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
629 assert(ValueVT.getVectorElementType() == PartVT &&
630 ValueVT.getVectorNumElements() == 1 &&
631 "Only trivial vector-to-scalar conversions should get here!");
632 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
633 DAG.getConstant(0, PtrVT));
641 // Handle a multi-element vector.
642 MVT IntermediateVT, RegisterVT;
643 unsigned NumIntermediates;
645 DAG.getTargetLoweringInfo()
646 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
648 unsigned NumElements = ValueVT.getVectorNumElements();
650 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
651 NumParts = NumRegs; // Silence a compiler warning.
652 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
654 // Split the vector into intermediate operands.
655 SmallVector<SDValue, 8> Ops(NumIntermediates);
656 for (unsigned i = 0; i != NumIntermediates; ++i)
657 if (IntermediateVT.isVector())
658 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
660 DAG.getConstant(i * (NumElements / NumIntermediates),
663 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
665 DAG.getConstant(i, PtrVT));
667 // Split the intermediate operands into legal parts.
668 if (NumParts == NumIntermediates) {
669 // If the register was not expanded, promote or copy the value,
671 for (unsigned i = 0; i != NumParts; ++i)
672 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
673 } else if (NumParts > 0) {
674 // If the intermediate type was expanded, split each the value into
676 assert(NumParts % NumIntermediates == 0 &&
677 "Must expand into a divisible number of parts!");
678 unsigned Factor = NumParts / NumIntermediates;
679 for (unsigned i = 0; i != NumIntermediates; ++i)
680 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
685 void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
688 TD = DAG.getTarget().getTargetData();
691 /// clear - Clear out the curret SelectionDAG and the associated
692 /// state and prepare this SelectionDAGLowering object to be used
693 /// for a new block. This doesn't clear out information about
694 /// additional blocks that are needed to complete switch lowering
695 /// or PHI node updating; that information is cleared out as it is
697 void SelectionDAGLowering::clear() {
699 PendingLoads.clear();
700 PendingExports.clear();
704 /// getRoot - Return the current virtual root of the Selection DAG,
705 /// flushing any PendingLoad items. This must be done before emitting
706 /// a store or any other node that may need to be ordered after any
707 /// prior load instructions.
709 SDValue SelectionDAGLowering::getRoot() {
710 if (PendingLoads.empty())
711 return DAG.getRoot();
713 if (PendingLoads.size() == 1) {
714 SDValue Root = PendingLoads[0];
716 PendingLoads.clear();
720 // Otherwise, we have to make a token factor node.
721 SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
722 &PendingLoads[0], PendingLoads.size());
723 PendingLoads.clear();
728 /// getControlRoot - Similar to getRoot, but instead of flushing all the
729 /// PendingLoad items, flush all the PendingExports items. It is necessary
730 /// to do this before emitting a terminator instruction.
732 SDValue SelectionDAGLowering::getControlRoot() {
733 SDValue Root = DAG.getRoot();
735 if (PendingExports.empty())
738 // Turn all of the CopyToReg chains into one factored node.
739 if (Root.getOpcode() != ISD::EntryToken) {
740 unsigned i = 0, e = PendingExports.size();
741 for (; i != e; ++i) {
742 assert(PendingExports[i].getNode()->getNumOperands() > 1);
743 if (PendingExports[i].getNode()->getOperand(0) == Root)
744 break; // Don't add the root if we already indirectly depend on it.
748 PendingExports.push_back(Root);
751 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
753 PendingExports.size());
754 PendingExports.clear();
759 void SelectionDAGLowering::visit(Instruction &I) {
760 visit(I.getOpcode(), I);
763 void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
764 // Note: this doesn't use InstVisitor, because it has to work with
765 // ConstantExpr's in addition to instructions.
767 default: assert(0 && "Unknown instruction type encountered!");
769 // Build the switch statement using the Instruction.def file.
770 #define HANDLE_INST(NUM, OPCODE, CLASS) \
771 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
772 #include "llvm/Instruction.def"
776 void SelectionDAGLowering::visitAdd(User &I) {
777 if (I.getType()->isFPOrFPVector())
778 visitBinary(I, ISD::FADD);
780 visitBinary(I, ISD::ADD);
783 void SelectionDAGLowering::visitMul(User &I) {
784 if (I.getType()->isFPOrFPVector())
785 visitBinary(I, ISD::FMUL);
787 visitBinary(I, ISD::MUL);
790 SDValue SelectionDAGLowering::getValue(const Value *V) {
791 SDValue &N = NodeMap[V];
792 if (N.getNode()) return N;
794 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
795 MVT VT = TLI.getValueType(V->getType(), true);
797 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
798 return N = DAG.getConstant(*CI, VT);
800 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
801 return N = DAG.getGlobalAddress(GV, VT);
803 if (isa<ConstantPointerNull>(C))
804 return N = DAG.getConstant(0, TLI.getPointerTy());
806 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
807 return N = DAG.getConstantFP(*CFP, VT);
809 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
810 !V->getType()->isAggregateType())
811 return N = DAG.getNode(ISD::UNDEF, VT);
813 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
814 visit(CE->getOpcode(), *CE);
815 SDValue N1 = NodeMap[V];
816 assert(N1.getNode() && "visit didn't populate the ValueMap!");
820 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
821 SmallVector<SDValue, 4> Constants;
822 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
824 SDNode *Val = getValue(*OI).getNode();
825 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
826 Constants.push_back(SDValue(Val, i));
828 return DAG.getMergeValues(&Constants[0], Constants.size());
831 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
832 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
833 "Unknown struct or array constant!");
835 SmallVector<MVT, 4> ValueVTs;
836 ComputeValueVTs(TLI, C->getType(), ValueVTs);
837 unsigned NumElts = ValueVTs.size();
839 return SDValue(); // empty struct
840 SmallVector<SDValue, 4> Constants(NumElts);
841 for (unsigned i = 0; i != NumElts; ++i) {
842 MVT EltVT = ValueVTs[i];
843 if (isa<UndefValue>(C))
844 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
845 else if (EltVT.isFloatingPoint())
846 Constants[i] = DAG.getConstantFP(0, EltVT);
848 Constants[i] = DAG.getConstant(0, EltVT);
850 return DAG.getMergeValues(&Constants[0], NumElts);
853 const VectorType *VecTy = cast<VectorType>(V->getType());
854 unsigned NumElements = VecTy->getNumElements();
856 // Now that we know the number and type of the elements, get that number of
857 // elements into the Ops array based on what kind of constant it is.
858 SmallVector<SDValue, 16> Ops;
859 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
860 for (unsigned i = 0; i != NumElements; ++i)
861 Ops.push_back(getValue(CP->getOperand(i)));
863 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
864 "Unknown vector constant!");
865 MVT EltVT = TLI.getValueType(VecTy->getElementType());
868 if (isa<UndefValue>(C))
869 Op = DAG.getNode(ISD::UNDEF, EltVT);
870 else if (EltVT.isFloatingPoint())
871 Op = DAG.getConstantFP(0, EltVT);
873 Op = DAG.getConstant(0, EltVT);
874 Ops.assign(NumElements, Op);
877 // Create a BUILD_VECTOR node.
878 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
881 // If this is a static alloca, generate it as the frameindex instead of
883 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
884 DenseMap<const AllocaInst*, int>::iterator SI =
885 FuncInfo.StaticAllocaMap.find(AI);
886 if (SI != FuncInfo.StaticAllocaMap.end())
887 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
890 unsigned InReg = FuncInfo.ValueMap[V];
891 assert(InReg && "Value not in map!");
893 RegsForValue RFV(TLI, InReg, V->getType());
894 SDValue Chain = DAG.getEntryNode();
895 return RFV.getCopyFromRegs(DAG, Chain, NULL);
899 void SelectionDAGLowering::visitRet(ReturnInst &I) {
900 if (I.getNumOperands() == 0) {
901 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
905 SmallVector<SDValue, 8> NewValues;
906 NewValues.push_back(getControlRoot());
907 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
908 SDValue RetOp = getValue(I.getOperand(i));
910 SmallVector<MVT, 4> ValueVTs;
911 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
912 for (unsigned j = 0, f = ValueVTs.size(); j != f; ++j) {
913 MVT VT = ValueVTs[j];
915 // FIXME: C calling convention requires the return type to be promoted to
916 // at least 32-bit. But this is not necessary for non-C calling
918 if (VT.isInteger()) {
919 MVT MinVT = TLI.getRegisterType(MVT::i32);
920 if (VT.bitsLT(MinVT))
924 unsigned NumParts = TLI.getNumRegisters(VT);
925 MVT PartVT = TLI.getRegisterType(VT);
926 SmallVector<SDValue, 4> Parts(NumParts);
927 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
929 const Function *F = I.getParent()->getParent();
930 if (F->paramHasAttr(0, Attribute::SExt))
931 ExtendKind = ISD::SIGN_EXTEND;
932 else if (F->paramHasAttr(0, Attribute::ZExt))
933 ExtendKind = ISD::ZERO_EXTEND;
935 getCopyToParts(DAG, SDValue(RetOp.getNode(), RetOp.getResNo() + j),
936 &Parts[0], NumParts, PartVT, ExtendKind);
938 // 'inreg' on function refers to return value
939 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
940 if (F->paramHasAttr(0, Attribute::InReg))
942 for (unsigned i = 0; i < NumParts; ++i) {
943 NewValues.push_back(Parts[i]);
944 NewValues.push_back(DAG.getArgFlags(Flags));
948 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
949 &NewValues[0], NewValues.size()));
952 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
953 /// the current basic block, add it to ValueMap now so that we'll get a
955 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
956 // No need to export constants.
957 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
960 if (FuncInfo.isExportedInst(V)) return;
962 unsigned Reg = FuncInfo.InitializeRegForValue(V);
963 CopyValueToVirtualRegister(V, Reg);
966 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
967 const BasicBlock *FromBB) {
968 // The operands of the setcc have to be in this block. We don't know
969 // how to export them from some other block.
970 if (Instruction *VI = dyn_cast<Instruction>(V)) {
971 // Can export from current BB.
972 if (VI->getParent() == FromBB)
975 // Is already exported, noop.
976 return FuncInfo.isExportedInst(V);
979 // If this is an argument, we can export it if the BB is the entry block or
980 // if it is already exported.
981 if (isa<Argument>(V)) {
982 if (FromBB == &FromBB->getParent()->getEntryBlock())
985 // Otherwise, can only export this if it is already exported.
986 return FuncInfo.isExportedInst(V);
989 // Otherwise, constants can always be exported.
993 static bool InBlock(const Value *V, const BasicBlock *BB) {
994 if (const Instruction *I = dyn_cast<Instruction>(V))
995 return I->getParent() == BB;
999 /// FindMergedConditions - If Cond is an expression like
1000 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1001 MachineBasicBlock *TBB,
1002 MachineBasicBlock *FBB,
1003 MachineBasicBlock *CurBB,
1005 // If this node is not part of the or/and tree, emit it as a branch.
1006 Instruction *BOp = dyn_cast<Instruction>(Cond);
1008 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1009 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1010 BOp->getParent() != CurBB->getBasicBlock() ||
1011 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1012 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1013 const BasicBlock *BB = CurBB->getBasicBlock();
1015 // If the leaf of the tree is a comparison, merge the condition into
1017 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1018 // The operands of the cmp have to be in this block. We don't know
1019 // how to export them from some other block. If this is the first block
1020 // of the sequence, no exporting is needed.
1022 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1023 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
1024 BOp = cast<Instruction>(Cond);
1025 ISD::CondCode Condition;
1026 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1027 switch (IC->getPredicate()) {
1028 default: assert(0 && "Unknown icmp predicate opcode!");
1029 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1030 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1031 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1032 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1033 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1034 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1035 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1036 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1037 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1038 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1040 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1041 ISD::CondCode FPC, FOC;
1042 switch (FC->getPredicate()) {
1043 default: assert(0 && "Unknown fcmp predicate opcode!");
1044 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1045 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1046 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1047 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1048 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1049 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1050 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1051 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1052 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1053 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1054 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1055 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1056 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1057 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1058 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1059 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1061 if (FiniteOnlyFPMath())
1066 Condition = ISD::SETEQ; // silence warning.
1067 assert(0 && "Unknown compare instruction");
1070 CaseBlock CB(Condition, BOp->getOperand(0),
1071 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1072 SwitchCases.push_back(CB);
1076 // Create a CaseBlock record representing this branch.
1077 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1078 NULL, TBB, FBB, CurBB);
1079 SwitchCases.push_back(CB);
1084 // Create TmpBB after CurBB.
1085 MachineFunction::iterator BBI = CurBB;
1086 MachineFunction &MF = DAG.getMachineFunction();
1087 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1088 CurBB->getParent()->insert(++BBI, TmpBB);
1090 if (Opc == Instruction::Or) {
1091 // Codegen X | Y as:
1099 // Emit the LHS condition.
1100 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1102 // Emit the RHS condition into TmpBB.
1103 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1105 assert(Opc == Instruction::And && "Unknown merge op!");
1106 // Codegen X & Y as:
1113 // This requires creation of TmpBB after CurBB.
1115 // Emit the LHS condition.
1116 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1118 // Emit the RHS condition into TmpBB.
1119 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1123 /// If the set of cases should be emitted as a series of branches, return true.
1124 /// If we should emit this as a bunch of and/or'd together conditions, return
1127 SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1128 if (Cases.size() != 2) return true;
1130 // If this is two comparisons of the same values or'd or and'd together, they
1131 // will get folded into a single comparison, so don't emit two blocks.
1132 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1133 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1134 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1135 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1142 void SelectionDAGLowering::visitBr(BranchInst &I) {
1143 // Update machine-CFG edges.
1144 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1146 // Figure out which block is immediately after the current one.
1147 MachineBasicBlock *NextBlock = 0;
1148 MachineFunction::iterator BBI = CurMBB;
1149 if (++BBI != CurMBB->getParent()->end())
1152 if (I.isUnconditional()) {
1153 // Update machine-CFG edges.
1154 CurMBB->addSuccessor(Succ0MBB);
1156 // If this is not a fall-through branch, emit the branch.
1157 if (Succ0MBB != NextBlock)
1158 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1159 DAG.getBasicBlock(Succ0MBB)));
1163 // If this condition is one of the special cases we handle, do special stuff
1165 Value *CondVal = I.getCondition();
1166 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1168 // If this is a series of conditions that are or'd or and'd together, emit
1169 // this as a sequence of branches instead of setcc's with and/or operations.
1170 // For example, instead of something like:
1183 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1184 if (BOp->hasOneUse() &&
1185 (BOp->getOpcode() == Instruction::And ||
1186 BOp->getOpcode() == Instruction::Or)) {
1187 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1188 // If the compares in later blocks need to use values not currently
1189 // exported from this block, export them now. This block should always
1190 // be the first entry.
1191 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1193 // Allow some cases to be rejected.
1194 if (ShouldEmitAsBranches(SwitchCases)) {
1195 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1196 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1197 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1200 // Emit the branch for this block.
1201 visitSwitchCase(SwitchCases[0]);
1202 SwitchCases.erase(SwitchCases.begin());
1206 // Okay, we decided not to do this, remove any inserted MBB's and clear
1208 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1209 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
1211 SwitchCases.clear();
1215 // Create a CaseBlock record representing this branch.
1216 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1217 NULL, Succ0MBB, Succ1MBB, CurMBB);
1218 // Use visitSwitchCase to actually insert the fast branch sequence for this
1220 visitSwitchCase(CB);
1223 /// visitSwitchCase - Emits the necessary code to represent a single node in
1224 /// the binary search tree resulting from lowering a switch instruction.
1225 void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1227 SDValue CondLHS = getValue(CB.CmpLHS);
1229 // Build the setcc now.
1230 if (CB.CmpMHS == NULL) {
1231 // Fold "(X == true)" to X and "(X == false)" to !X to
1232 // handle common cases produced by branch lowering.
1233 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1235 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1236 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1237 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1239 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1241 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1243 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1244 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1246 SDValue CmpOp = getValue(CB.CmpMHS);
1247 MVT VT = CmpOp.getValueType();
1249 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1250 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1252 SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1253 Cond = DAG.getSetCC(MVT::i1, SUB,
1254 DAG.getConstant(High-Low, VT), ISD::SETULE);
1258 // Update successor info
1259 CurMBB->addSuccessor(CB.TrueBB);
1260 CurMBB->addSuccessor(CB.FalseBB);
1262 // Set NextBlock to be the MBB immediately after the current one, if any.
1263 // This is used to avoid emitting unnecessary branches to the next block.
1264 MachineBasicBlock *NextBlock = 0;
1265 MachineFunction::iterator BBI = CurMBB;
1266 if (++BBI != CurMBB->getParent()->end())
1269 // If the lhs block is the next block, invert the condition so that we can
1270 // fall through to the lhs instead of the rhs block.
1271 if (CB.TrueBB == NextBlock) {
1272 std::swap(CB.TrueBB, CB.FalseBB);
1273 SDValue True = DAG.getConstant(1, Cond.getValueType());
1274 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1276 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1277 DAG.getBasicBlock(CB.TrueBB));
1279 // If the branch was constant folded, fix up the CFG.
1280 if (BrCond.getOpcode() == ISD::BR) {
1281 CurMBB->removeSuccessor(CB.FalseBB);
1282 DAG.setRoot(BrCond);
1284 // Otherwise, go ahead and insert the false branch.
1285 if (BrCond == getControlRoot())
1286 CurMBB->removeSuccessor(CB.TrueBB);
1288 if (CB.FalseBB == NextBlock)
1289 DAG.setRoot(BrCond);
1291 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1292 DAG.getBasicBlock(CB.FalseBB)));
1296 /// visitJumpTable - Emit JumpTable node in the current MBB
1297 void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1298 // Emit the code for the jump table
1299 assert(JT.Reg != -1U && "Should lower JT Header first!");
1300 MVT PTy = TLI.getPointerTy();
1301 SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1302 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1303 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1308 /// visitJumpTableHeader - This function emits necessary code to produce index
1309 /// in the JumpTable from switch case.
1310 void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1311 JumpTableHeader &JTH) {
1312 // Subtract the lowest switch case value from the value being switched on
1313 // and conditional branch to default mbb if the result is greater than the
1314 // difference between smallest and largest cases.
1315 SDValue SwitchOp = getValue(JTH.SValue);
1316 MVT VT = SwitchOp.getValueType();
1317 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1318 DAG.getConstant(JTH.First, VT));
1320 // The SDNode we just created, which holds the value being switched on
1321 // minus the the smallest case value, needs to be copied to a virtual
1322 // register so it can be used as an index into the jump table in a
1323 // subsequent basic block. This value may be smaller or larger than the
1324 // target's pointer type, and therefore require extension or truncating.
1325 if (VT.bitsGT(TLI.getPointerTy()))
1326 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1328 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1330 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1331 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1332 JT.Reg = JumpTableReg;
1334 // Emit the range check for the jump table, and branch to the default
1335 // block for the switch statement if the value being switched on exceeds
1336 // the largest case in the switch.
1337 SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1338 DAG.getConstant(JTH.Last-JTH.First,VT),
1341 // Set NextBlock to be the MBB immediately after the current one, if any.
1342 // This is used to avoid emitting unnecessary branches to the next block.
1343 MachineBasicBlock *NextBlock = 0;
1344 MachineFunction::iterator BBI = CurMBB;
1345 if (++BBI != CurMBB->getParent()->end())
1348 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1349 DAG.getBasicBlock(JT.Default));
1351 if (JT.MBB == NextBlock)
1352 DAG.setRoot(BrCond);
1354 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1355 DAG.getBasicBlock(JT.MBB)));
1360 /// visitBitTestHeader - This function emits necessary code to produce value
1361 /// suitable for "bit tests"
1362 void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1363 // Subtract the minimum value
1364 SDValue SwitchOp = getValue(B.SValue);
1365 MVT VT = SwitchOp.getValueType();
1366 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1367 DAG.getConstant(B.First, VT));
1370 SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1371 DAG.getConstant(B.Range, VT),
1375 if (VT.bitsGT(TLI.getShiftAmountTy()))
1376 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1378 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1380 // Make desired shift
1381 SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1382 DAG.getConstant(1, TLI.getPointerTy()),
1385 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1386 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1389 // Set NextBlock to be the MBB immediately after the current one, if any.
1390 // This is used to avoid emitting unnecessary branches to the next block.
1391 MachineBasicBlock *NextBlock = 0;
1392 MachineFunction::iterator BBI = CurMBB;
1393 if (++BBI != CurMBB->getParent()->end())
1396 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1398 CurMBB->addSuccessor(B.Default);
1399 CurMBB->addSuccessor(MBB);
1401 SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1402 DAG.getBasicBlock(B.Default));
1404 if (MBB == NextBlock)
1405 DAG.setRoot(BrRange);
1407 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1408 DAG.getBasicBlock(MBB)));
1413 /// visitBitTestCase - this function produces one "bit test"
1414 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1417 // Emit bit tests and jumps
1418 SDValue SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg,
1419 TLI.getPointerTy());
1421 SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
1422 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1423 SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1424 DAG.getConstant(0, TLI.getPointerTy()),
1427 CurMBB->addSuccessor(B.TargetBB);
1428 CurMBB->addSuccessor(NextMBB);
1430 SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1431 AndCmp, DAG.getBasicBlock(B.TargetBB));
1433 // Set NextBlock to be the MBB immediately after the current one, if any.
1434 // This is used to avoid emitting unnecessary branches to the next block.
1435 MachineBasicBlock *NextBlock = 0;
1436 MachineFunction::iterator BBI = CurMBB;
1437 if (++BBI != CurMBB->getParent()->end())
1440 if (NextMBB == NextBlock)
1443 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1444 DAG.getBasicBlock(NextMBB)));
1449 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1450 // Retrieve successors.
1451 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1452 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1454 if (isa<InlineAsm>(I.getCalledValue()))
1457 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1459 // If the value of the invoke is used outside of its defining block, make it
1460 // available as a virtual register.
1461 if (!I.use_empty()) {
1462 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1463 if (VMI != FuncInfo.ValueMap.end())
1464 CopyValueToVirtualRegister(&I, VMI->second);
1467 // Update successor info
1468 CurMBB->addSuccessor(Return);
1469 CurMBB->addSuccessor(LandingPad);
1471 // Drop into normal successor.
1472 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1473 DAG.getBasicBlock(Return)));
1476 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1479 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1480 /// small case ranges).
1481 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1482 CaseRecVector& WorkList,
1484 MachineBasicBlock* Default) {
1485 Case& BackCase = *(CR.Range.second-1);
1487 // Size is the number of Cases represented by this range.
1488 unsigned Size = CR.Range.second - CR.Range.first;
1492 // Get the MachineFunction which holds the current MBB. This is used when
1493 // inserting any additional MBBs necessary to represent the switch.
1494 MachineFunction *CurMF = CurMBB->getParent();
1496 // Figure out which block is immediately after the current one.
1497 MachineBasicBlock *NextBlock = 0;
1498 MachineFunction::iterator BBI = CR.CaseBB;
1500 if (++BBI != CurMBB->getParent()->end())
1503 // TODO: If any two of the cases has the same destination, and if one value
1504 // is the same as the other, but has one bit unset that the other has set,
1505 // use bit manipulation to do two compares at once. For example:
1506 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1508 // Rearrange the case blocks so that the last one falls through if possible.
1509 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1510 // The last case block won't fall through into 'NextBlock' if we emit the
1511 // branches in this order. See if rearranging a case value would help.
1512 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1513 if (I->BB == NextBlock) {
1514 std::swap(*I, BackCase);
1520 // Create a CaseBlock record representing a conditional branch to
1521 // the Case's target mbb if the value being switched on SV is equal
1523 MachineBasicBlock *CurBlock = CR.CaseBB;
1524 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1525 MachineBasicBlock *FallThrough;
1527 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1528 CurMF->insert(BBI, FallThrough);
1530 // If the last case doesn't match, go to the default block.
1531 FallThrough = Default;
1534 Value *RHS, *LHS, *MHS;
1536 if (I->High == I->Low) {
1537 // This is just small small case range :) containing exactly 1 case
1539 LHS = SV; RHS = I->High; MHS = NULL;
1542 LHS = I->Low; MHS = SV; RHS = I->High;
1544 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1546 // If emitting the first comparison, just call visitSwitchCase to emit the
1547 // code into the current block. Otherwise, push the CaseBlock onto the
1548 // vector to be later processed by SDISel, and insert the node's MBB
1549 // before the next MBB.
1550 if (CurBlock == CurMBB)
1551 visitSwitchCase(CB);
1553 SwitchCases.push_back(CB);
1555 CurBlock = FallThrough;
1561 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1562 return !DisableJumpTables &&
1563 (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1564 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1567 /// handleJTSwitchCase - Emit jumptable for current switch case range
1568 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1569 CaseRecVector& WorkList,
1571 MachineBasicBlock* Default) {
1572 Case& FrontCase = *CR.Range.first;
1573 Case& BackCase = *(CR.Range.second-1);
1575 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1576 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1579 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1583 if (!areJTsAllowed(TLI) || TSize <= 3)
1586 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1590 DOUT << "Lowering jump table\n"
1591 << "First entry: " << First << ". Last entry: " << Last << "\n"
1592 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1594 // Get the MachineFunction which holds the current MBB. This is used when
1595 // inserting any additional MBBs necessary to represent the switch.
1596 MachineFunction *CurMF = CurMBB->getParent();
1598 // Figure out which block is immediately after the current one.
1599 MachineBasicBlock *NextBlock = 0;
1600 MachineFunction::iterator BBI = CR.CaseBB;
1602 if (++BBI != CurMBB->getParent()->end())
1605 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1607 // Create a new basic block to hold the code for loading the address
1608 // of the jump table, and jumping to it. Update successor information;
1609 // we will either branch to the default case for the switch, or the jump
1611 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1612 CurMF->insert(BBI, JumpTableBB);
1613 CR.CaseBB->addSuccessor(Default);
1614 CR.CaseBB->addSuccessor(JumpTableBB);
1616 // Build a vector of destination BBs, corresponding to each target
1617 // of the jump table. If the value of the jump table slot corresponds to
1618 // a case statement, push the case's BB onto the vector, otherwise, push
1620 std::vector<MachineBasicBlock*> DestBBs;
1621 int64_t TEI = First;
1622 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1623 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1624 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1626 if ((Low <= TEI) && (TEI <= High)) {
1627 DestBBs.push_back(I->BB);
1631 DestBBs.push_back(Default);
1635 // Update successor info. Add one edge to each unique successor.
1636 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1637 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1638 E = DestBBs.end(); I != E; ++I) {
1639 if (!SuccsHandled[(*I)->getNumber()]) {
1640 SuccsHandled[(*I)->getNumber()] = true;
1641 JumpTableBB->addSuccessor(*I);
1645 // Create a jump table index for this jump table, or return an existing
1647 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1649 // Set the jump table information so that we can codegen it as a second
1650 // MachineBasicBlock
1651 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1652 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1653 if (CR.CaseBB == CurMBB)
1654 visitJumpTableHeader(JT, JTH);
1656 JTCases.push_back(JumpTableBlock(JTH, JT));
1661 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1663 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1664 CaseRecVector& WorkList,
1666 MachineBasicBlock* Default) {
1667 // Get the MachineFunction which holds the current MBB. This is used when
1668 // inserting any additional MBBs necessary to represent the switch.
1669 MachineFunction *CurMF = CurMBB->getParent();
1671 // Figure out which block is immediately after the current one.
1672 MachineBasicBlock *NextBlock = 0;
1673 MachineFunction::iterator BBI = CR.CaseBB;
1675 if (++BBI != CurMBB->getParent()->end())
1678 Case& FrontCase = *CR.Range.first;
1679 Case& BackCase = *(CR.Range.second-1);
1680 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1682 // Size is the number of Cases represented by this range.
1683 unsigned Size = CR.Range.second - CR.Range.first;
1685 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1686 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1688 CaseItr Pivot = CR.Range.first + Size/2;
1690 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1691 // (heuristically) allow us to emit JumpTable's later.
1693 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1697 uint64_t LSize = FrontCase.size();
1698 uint64_t RSize = TSize-LSize;
1699 DOUT << "Selecting best pivot: \n"
1700 << "First: " << First << ", Last: " << Last <<"\n"
1701 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1702 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1704 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1705 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1706 assert((RBegin-LEnd>=1) && "Invalid case distance");
1707 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1708 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1709 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1710 // Should always split in some non-trivial place
1712 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1713 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1714 << "Metric: " << Metric << "\n";
1715 if (FMetric < Metric) {
1718 DOUT << "Current metric set to: " << FMetric << "\n";
1724 if (areJTsAllowed(TLI)) {
1725 // If our case is dense we *really* should handle it earlier!
1726 assert((FMetric > 0) && "Should handle dense range earlier!");
1728 Pivot = CR.Range.first + Size/2;
1731 CaseRange LHSR(CR.Range.first, Pivot);
1732 CaseRange RHSR(Pivot, CR.Range.second);
1733 Constant *C = Pivot->Low;
1734 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1736 // We know that we branch to the LHS if the Value being switched on is
1737 // less than the Pivot value, C. We use this to optimize our binary
1738 // tree a bit, by recognizing that if SV is greater than or equal to the
1739 // LHS's Case Value, and that Case Value is exactly one less than the
1740 // Pivot's Value, then we can branch directly to the LHS's Target,
1741 // rather than creating a leaf node for it.
1742 if ((LHSR.second - LHSR.first) == 1 &&
1743 LHSR.first->High == CR.GE &&
1744 cast<ConstantInt>(C)->getSExtValue() ==
1745 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1746 TrueBB = LHSR.first->BB;
1748 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1749 CurMF->insert(BBI, TrueBB);
1750 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1753 // Similar to the optimization above, if the Value being switched on is
1754 // known to be less than the Constant CR.LT, and the current Case Value
1755 // is CR.LT - 1, then we can branch directly to the target block for
1756 // the current Case Value, rather than emitting a RHS leaf node for it.
1757 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1758 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1759 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1760 FalseBB = RHSR.first->BB;
1762 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1763 CurMF->insert(BBI, FalseBB);
1764 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1767 // Create a CaseBlock record representing a conditional branch to
1768 // the LHS node if the value being switched on SV is less than C.
1769 // Otherwise, branch to LHS.
1770 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1772 if (CR.CaseBB == CurMBB)
1773 visitSwitchCase(CB);
1775 SwitchCases.push_back(CB);
1780 /// handleBitTestsSwitchCase - if current case range has few destination and
1781 /// range span less, than machine word bitwidth, encode case range into series
1782 /// of masks and emit bit tests with these masks.
1783 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1784 CaseRecVector& WorkList,
1786 MachineBasicBlock* Default){
1787 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1789 Case& FrontCase = *CR.Range.first;
1790 Case& BackCase = *(CR.Range.second-1);
1792 // Get the MachineFunction which holds the current MBB. This is used when
1793 // inserting any additional MBBs necessary to represent the switch.
1794 MachineFunction *CurMF = CurMBB->getParent();
1796 unsigned numCmps = 0;
1797 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1799 // Single case counts one, case range - two.
1800 if (I->Low == I->High)
1806 // Count unique destinations
1807 SmallSet<MachineBasicBlock*, 4> Dests;
1808 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1809 Dests.insert(I->BB);
1810 if (Dests.size() > 3)
1811 // Don't bother the code below, if there are too much unique destinations
1814 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1815 << "Total number of comparisons: " << numCmps << "\n";
1817 // Compute span of values.
1818 Constant* minValue = FrontCase.Low;
1819 Constant* maxValue = BackCase.High;
1820 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1821 cast<ConstantInt>(minValue)->getSExtValue();
1822 DOUT << "Compare range: " << range << "\n"
1823 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1824 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1826 if (range>=IntPtrBits ||
1827 (!(Dests.size() == 1 && numCmps >= 3) &&
1828 !(Dests.size() == 2 && numCmps >= 5) &&
1829 !(Dests.size() >= 3 && numCmps >= 6)))
1832 DOUT << "Emitting bit tests\n";
1833 int64_t lowBound = 0;
1835 // Optimize the case where all the case values fit in a
1836 // word without having to subtract minValue. In this case,
1837 // we can optimize away the subtraction.
1838 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
1839 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
1840 range = cast<ConstantInt>(maxValue)->getSExtValue();
1842 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1845 CaseBitsVector CasesBits;
1846 unsigned i, count = 0;
1848 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1849 MachineBasicBlock* Dest = I->BB;
1850 for (i = 0; i < count; ++i)
1851 if (Dest == CasesBits[i].BB)
1855 assert((count < 3) && "Too much destinations to test!");
1856 CasesBits.push_back(CaseBits(0, Dest, 0));
1860 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1861 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1863 for (uint64_t j = lo; j <= hi; j++) {
1864 CasesBits[i].Mask |= 1ULL << j;
1865 CasesBits[i].Bits++;
1869 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1873 // Figure out which block is immediately after the current one.
1874 MachineFunction::iterator BBI = CR.CaseBB;
1877 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1880 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1881 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1882 << ", BB: " << CasesBits[i].BB << "\n";
1884 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1885 CurMF->insert(BBI, CaseBB);
1886 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1891 BitTestBlock BTB(lowBound, range, SV,
1892 -1U, (CR.CaseBB == CurMBB),
1893 CR.CaseBB, Default, BTC);
1895 if (CR.CaseBB == CurMBB)
1896 visitBitTestHeader(BTB);
1898 BitTestCases.push_back(BTB);
1904 /// Clusterify - Transform simple list of Cases into list of CaseRange's
1905 unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1906 const SwitchInst& SI) {
1907 unsigned numCmps = 0;
1909 // Start with "simple" cases
1910 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1911 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1912 Cases.push_back(Case(SI.getSuccessorValue(i),
1913 SI.getSuccessorValue(i),
1916 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1918 // Merge case into clusters
1919 if (Cases.size()>=2)
1920 // Must recompute end() each iteration because it may be
1921 // invalidated by erase if we hold on to it
1922 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
1923 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1924 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1925 MachineBasicBlock* nextBB = J->BB;
1926 MachineBasicBlock* currentBB = I->BB;
1928 // If the two neighboring cases go to the same destination, merge them
1929 // into a single case.
1930 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1938 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1939 if (I->Low != I->High)
1940 // A range counts double, since it requires two compares.
1947 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
1948 // Figure out which block is immediately after the current one.
1949 MachineBasicBlock *NextBlock = 0;
1950 MachineFunction::iterator BBI = CurMBB;
1952 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1954 // If there is only the default destination, branch to it if it is not the
1955 // next basic block. Otherwise, just fall through.
1956 if (SI.getNumOperands() == 2) {
1957 // Update machine-CFG edges.
1959 // If this is not a fall-through branch, emit the branch.
1960 CurMBB->addSuccessor(Default);
1961 if (Default != NextBlock)
1962 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1963 DAG.getBasicBlock(Default)));
1968 // If there are any non-default case statements, create a vector of Cases
1969 // representing each one, and sort the vector so that we can efficiently
1970 // create a binary search tree from them.
1972 unsigned numCmps = Clusterify(Cases, SI);
1973 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1974 << ". Total compares: " << numCmps << "\n";
1976 // Get the Value to be switched on and default basic blocks, which will be
1977 // inserted into CaseBlock records, representing basic blocks in the binary
1979 Value *SV = SI.getOperand(0);
1981 // Push the initial CaseRec onto the worklist
1982 CaseRecVector WorkList;
1983 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1985 while (!WorkList.empty()) {
1986 // Grab a record representing a case range to process off the worklist
1987 CaseRec CR = WorkList.back();
1988 WorkList.pop_back();
1990 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1993 // If the range has few cases (two or less) emit a series of specific
1995 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1998 // If the switch has more than 5 blocks, and at least 40% dense, and the
1999 // target supports indirect branches, then emit a jump table rather than
2000 // lowering the switch to a binary tree of conditional branches.
2001 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2004 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2005 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2006 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2011 void SelectionDAGLowering::visitSub(User &I) {
2012 // -0.0 - X --> fneg
2013 const Type *Ty = I.getType();
2014 if (isa<VectorType>(Ty)) {
2015 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2016 const VectorType *DestTy = cast<VectorType>(I.getType());
2017 const Type *ElTy = DestTy->getElementType();
2018 if (ElTy->isFloatingPoint()) {
2019 unsigned VL = DestTy->getNumElements();
2020 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2021 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2023 SDValue Op2 = getValue(I.getOperand(1));
2024 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2030 if (Ty->isFloatingPoint()) {
2031 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2032 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2033 SDValue Op2 = getValue(I.getOperand(1));
2034 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2039 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2042 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2043 SDValue Op1 = getValue(I.getOperand(0));
2044 SDValue Op2 = getValue(I.getOperand(1));
2046 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2049 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2050 SDValue Op1 = getValue(I.getOperand(0));
2051 SDValue Op2 = getValue(I.getOperand(1));
2052 if (!isa<VectorType>(I.getType())) {
2053 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2054 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2055 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2056 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2059 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2062 void SelectionDAGLowering::visitICmp(User &I) {
2063 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2064 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2065 predicate = IC->getPredicate();
2066 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2067 predicate = ICmpInst::Predicate(IC->getPredicate());
2068 SDValue Op1 = getValue(I.getOperand(0));
2069 SDValue Op2 = getValue(I.getOperand(1));
2070 ISD::CondCode Opcode;
2071 switch (predicate) {
2072 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2073 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2074 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2075 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2076 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2077 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2078 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2079 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2080 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2081 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2083 assert(!"Invalid ICmp predicate value");
2084 Opcode = ISD::SETEQ;
2087 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2090 void SelectionDAGLowering::visitFCmp(User &I) {
2091 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2092 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2093 predicate = FC->getPredicate();
2094 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2095 predicate = FCmpInst::Predicate(FC->getPredicate());
2096 SDValue Op1 = getValue(I.getOperand(0));
2097 SDValue Op2 = getValue(I.getOperand(1));
2098 ISD::CondCode Condition, FOC, FPC;
2099 switch (predicate) {
2100 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2101 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2102 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2103 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2104 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2105 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2106 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2107 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2108 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2109 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2110 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2111 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2112 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2113 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2114 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2115 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2117 assert(!"Invalid FCmp predicate value");
2118 FOC = FPC = ISD::SETFALSE;
2121 if (FiniteOnlyFPMath())
2125 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2128 void SelectionDAGLowering::visitVICmp(User &I) {
2129 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2130 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2131 predicate = IC->getPredicate();
2132 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2133 predicate = ICmpInst::Predicate(IC->getPredicate());
2134 SDValue Op1 = getValue(I.getOperand(0));
2135 SDValue Op2 = getValue(I.getOperand(1));
2136 ISD::CondCode Opcode;
2137 switch (predicate) {
2138 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2139 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2140 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2141 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2142 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2143 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2144 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2145 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2146 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2147 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2149 assert(!"Invalid ICmp predicate value");
2150 Opcode = ISD::SETEQ;
2153 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2156 void SelectionDAGLowering::visitVFCmp(User &I) {
2157 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2158 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2159 predicate = FC->getPredicate();
2160 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2161 predicate = FCmpInst::Predicate(FC->getPredicate());
2162 SDValue Op1 = getValue(I.getOperand(0));
2163 SDValue Op2 = getValue(I.getOperand(1));
2164 ISD::CondCode Condition, FOC, FPC;
2165 switch (predicate) {
2166 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2167 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2168 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2169 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2170 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2171 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2172 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2173 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2174 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2175 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2176 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2177 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2178 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2179 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2180 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2181 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2183 assert(!"Invalid VFCmp predicate value");
2184 FOC = FPC = ISD::SETFALSE;
2187 if (FiniteOnlyFPMath())
2192 MVT DestVT = TLI.getValueType(I.getType());
2194 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2197 void SelectionDAGLowering::visitSelect(User &I) {
2198 SDValue Cond = getValue(I.getOperand(0));
2199 SDValue TrueVal = getValue(I.getOperand(1));
2200 SDValue FalseVal = getValue(I.getOperand(2));
2201 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2202 TrueVal, FalseVal));
2206 void SelectionDAGLowering::visitTrunc(User &I) {
2207 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2208 SDValue N = getValue(I.getOperand(0));
2209 MVT DestVT = TLI.getValueType(I.getType());
2210 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2213 void SelectionDAGLowering::visitZExt(User &I) {
2214 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2215 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2216 SDValue N = getValue(I.getOperand(0));
2217 MVT DestVT = TLI.getValueType(I.getType());
2218 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2221 void SelectionDAGLowering::visitSExt(User &I) {
2222 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2223 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2224 SDValue N = getValue(I.getOperand(0));
2225 MVT DestVT = TLI.getValueType(I.getType());
2226 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2229 void SelectionDAGLowering::visitFPTrunc(User &I) {
2230 // FPTrunc is never a no-op cast, no need to check
2231 SDValue N = getValue(I.getOperand(0));
2232 MVT DestVT = TLI.getValueType(I.getType());
2233 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2236 void SelectionDAGLowering::visitFPExt(User &I){
2237 // FPTrunc is never a no-op cast, no need to check
2238 SDValue N = getValue(I.getOperand(0));
2239 MVT DestVT = TLI.getValueType(I.getType());
2240 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2243 void SelectionDAGLowering::visitFPToUI(User &I) {
2244 // FPToUI is never a no-op cast, no need to check
2245 SDValue N = getValue(I.getOperand(0));
2246 MVT DestVT = TLI.getValueType(I.getType());
2247 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2250 void SelectionDAGLowering::visitFPToSI(User &I) {
2251 // FPToSI is never a no-op cast, no need to check
2252 SDValue N = getValue(I.getOperand(0));
2253 MVT DestVT = TLI.getValueType(I.getType());
2254 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2257 void SelectionDAGLowering::visitUIToFP(User &I) {
2258 // UIToFP is never a no-op cast, no need to check
2259 SDValue N = getValue(I.getOperand(0));
2260 MVT DestVT = TLI.getValueType(I.getType());
2261 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2264 void SelectionDAGLowering::visitSIToFP(User &I){
2265 // UIToFP is never a no-op cast, no need to check
2266 SDValue N = getValue(I.getOperand(0));
2267 MVT DestVT = TLI.getValueType(I.getType());
2268 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2271 void SelectionDAGLowering::visitPtrToInt(User &I) {
2272 // What to do depends on the size of the integer and the size of the pointer.
2273 // We can either truncate, zero extend, or no-op, accordingly.
2274 SDValue N = getValue(I.getOperand(0));
2275 MVT SrcVT = N.getValueType();
2276 MVT DestVT = TLI.getValueType(I.getType());
2278 if (DestVT.bitsLT(SrcVT))
2279 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2281 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2282 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2283 setValue(&I, Result);
2286 void SelectionDAGLowering::visitIntToPtr(User &I) {
2287 // What to do depends on the size of the integer and the size of the pointer.
2288 // We can either truncate, zero extend, or no-op, accordingly.
2289 SDValue N = getValue(I.getOperand(0));
2290 MVT SrcVT = N.getValueType();
2291 MVT DestVT = TLI.getValueType(I.getType());
2292 if (DestVT.bitsLT(SrcVT))
2293 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2295 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2296 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2299 void SelectionDAGLowering::visitBitCast(User &I) {
2300 SDValue N = getValue(I.getOperand(0));
2301 MVT DestVT = TLI.getValueType(I.getType());
2303 // BitCast assures us that source and destination are the same size so this
2304 // is either a BIT_CONVERT or a no-op.
2305 if (DestVT != N.getValueType())
2306 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2308 setValue(&I, N); // noop cast.
2311 void SelectionDAGLowering::visitInsertElement(User &I) {
2312 SDValue InVec = getValue(I.getOperand(0));
2313 SDValue InVal = getValue(I.getOperand(1));
2314 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2315 getValue(I.getOperand(2)));
2317 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2318 TLI.getValueType(I.getType()),
2319 InVec, InVal, InIdx));
2322 void SelectionDAGLowering::visitExtractElement(User &I) {
2323 SDValue InVec = getValue(I.getOperand(0));
2324 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2325 getValue(I.getOperand(1)));
2326 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2327 TLI.getValueType(I.getType()), InVec, InIdx));
2330 void SelectionDAGLowering::visitShuffleVector(User &I) {
2331 SDValue V1 = getValue(I.getOperand(0));
2332 SDValue V2 = getValue(I.getOperand(1));
2333 SDValue Mask = getValue(I.getOperand(2));
2335 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2336 TLI.getValueType(I.getType()),
2340 void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2341 const Value *Op0 = I.getOperand(0);
2342 const Value *Op1 = I.getOperand(1);
2343 const Type *AggTy = I.getType();
2344 const Type *ValTy = Op1->getType();
2345 bool IntoUndef = isa<UndefValue>(Op0);
2346 bool FromUndef = isa<UndefValue>(Op1);
2348 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2349 I.idx_begin(), I.idx_end());
2351 SmallVector<MVT, 4> AggValueVTs;
2352 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2353 SmallVector<MVT, 4> ValValueVTs;
2354 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2356 unsigned NumAggValues = AggValueVTs.size();
2357 unsigned NumValValues = ValValueVTs.size();
2358 SmallVector<SDValue, 4> Values(NumAggValues);
2360 SDValue Agg = getValue(Op0);
2361 SDValue Val = getValue(Op1);
2363 // Copy the beginning value(s) from the original aggregate.
2364 for (; i != LinearIndex; ++i)
2365 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2366 SDValue(Agg.getNode(), Agg.getResNo() + i);
2367 // Copy values from the inserted value(s).
2368 for (; i != LinearIndex + NumValValues; ++i)
2369 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2370 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2371 // Copy remaining value(s) from the original aggregate.
2372 for (; i != NumAggValues; ++i)
2373 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2374 SDValue(Agg.getNode(), Agg.getResNo() + i);
2376 setValue(&I, DAG.getMergeValues(DAG.getVTList(&AggValueVTs[0], NumAggValues),
2377 &Values[0], NumAggValues));
2380 void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2381 const Value *Op0 = I.getOperand(0);
2382 const Type *AggTy = Op0->getType();
2383 const Type *ValTy = I.getType();
2384 bool OutOfUndef = isa<UndefValue>(Op0);
2386 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2387 I.idx_begin(), I.idx_end());
2389 SmallVector<MVT, 4> ValValueVTs;
2390 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2392 unsigned NumValValues = ValValueVTs.size();
2393 SmallVector<SDValue, 4> Values(NumValValues);
2395 SDValue Agg = getValue(Op0);
2396 // Copy out the selected value(s).
2397 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2398 Values[i - LinearIndex] =
2399 OutOfUndef ? DAG.getNode(ISD::UNDEF, Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2400 SDValue(Agg.getNode(), Agg.getResNo() + i);
2402 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValValueVTs[0], NumValValues),
2403 &Values[0], NumValValues));
2407 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2408 SDValue N = getValue(I.getOperand(0));
2409 const Type *Ty = I.getOperand(0)->getType();
2411 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2414 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2415 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2418 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2419 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2420 DAG.getIntPtrConstant(Offset));
2422 Ty = StTy->getElementType(Field);
2424 Ty = cast<SequentialType>(Ty)->getElementType();
2426 // If this is a constant subscript, handle it quickly.
2427 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2428 if (CI->getZExtValue() == 0) continue;
2430 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2431 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2432 DAG.getIntPtrConstant(Offs));
2436 // N = N + Idx * ElementSize;
2437 uint64_t ElementSize = TD->getABITypeSize(Ty);
2438 SDValue IdxN = getValue(Idx);
2440 // If the index is smaller or larger than intptr_t, truncate or extend
2442 if (IdxN.getValueType().bitsLT(N.getValueType()))
2443 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2444 else if (IdxN.getValueType().bitsGT(N.getValueType()))
2445 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2447 // If this is a multiply by a power of two, turn it into a shl
2448 // immediately. This is a very common case.
2449 if (ElementSize != 1) {
2450 if (isPowerOf2_64(ElementSize)) {
2451 unsigned Amt = Log2_64(ElementSize);
2452 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2453 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2455 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2456 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2460 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2466 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2467 // If this is a fixed sized alloca in the entry block of the function,
2468 // allocate it statically on the stack.
2469 if (FuncInfo.StaticAllocaMap.count(&I))
2470 return; // getValue will auto-populate this.
2472 const Type *Ty = I.getAllocatedType();
2473 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2475 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2478 SDValue AllocSize = getValue(I.getArraySize());
2479 MVT IntPtr = TLI.getPointerTy();
2480 if (IntPtr.bitsLT(AllocSize.getValueType()))
2481 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2482 else if (IntPtr.bitsGT(AllocSize.getValueType()))
2483 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2485 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2486 DAG.getIntPtrConstant(TySize));
2488 // Handle alignment. If the requested alignment is less than or equal to
2489 // the stack alignment, ignore it. If the size is greater than or equal to
2490 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2491 unsigned StackAlign =
2492 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2493 if (Align <= StackAlign)
2496 // Round the size of the allocation up to the stack alignment size
2497 // by add SA-1 to the size.
2498 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2499 DAG.getIntPtrConstant(StackAlign-1));
2500 // Mask out the low bits for alignment purposes.
2501 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2502 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2504 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2505 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2507 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2509 DAG.setRoot(DSA.getValue(1));
2511 // Inform the Frame Information that we have just allocated a variable-sized
2513 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2516 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2517 const Value *SV = I.getOperand(0);
2518 SDValue Ptr = getValue(SV);
2520 const Type *Ty = I.getType();
2521 bool isVolatile = I.isVolatile();
2522 unsigned Alignment = I.getAlignment();
2524 SmallVector<MVT, 4> ValueVTs;
2525 SmallVector<uint64_t, 4> Offsets;
2526 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2527 unsigned NumValues = ValueVTs.size();
2532 bool ConstantMemory = false;
2534 // Serialize volatile loads with other side effects.
2536 else if (AA->pointsToConstantMemory(SV)) {
2537 // Do not serialize (non-volatile) loads of constant memory with anything.
2538 Root = DAG.getEntryNode();
2539 ConstantMemory = true;
2541 // Do not serialize non-volatile loads against each other.
2542 Root = DAG.getRoot();
2545 SmallVector<SDValue, 4> Values(NumValues);
2546 SmallVector<SDValue, 4> Chains(NumValues);
2547 MVT PtrVT = Ptr.getValueType();
2548 for (unsigned i = 0; i != NumValues; ++i) {
2549 SDValue L = DAG.getLoad(ValueVTs[i], Root,
2550 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2551 DAG.getConstant(Offsets[i], PtrVT)),
2553 isVolatile, Alignment);
2555 Chains[i] = L.getValue(1);
2558 if (!ConstantMemory) {
2559 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2560 &Chains[0], NumValues);
2564 PendingLoads.push_back(Chain);
2567 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], NumValues),
2568 &Values[0], NumValues));
2572 void SelectionDAGLowering::visitStore(StoreInst &I) {
2573 Value *SrcV = I.getOperand(0);
2574 Value *PtrV = I.getOperand(1);
2576 SmallVector<MVT, 4> ValueVTs;
2577 SmallVector<uint64_t, 4> Offsets;
2578 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2579 unsigned NumValues = ValueVTs.size();
2583 // Get the lowered operands. Note that we do this after
2584 // checking if NumResults is zero, because with zero results
2585 // the operands won't have values in the map.
2586 SDValue Src = getValue(SrcV);
2587 SDValue Ptr = getValue(PtrV);
2589 SDValue Root = getRoot();
2590 SmallVector<SDValue, 4> Chains(NumValues);
2591 MVT PtrVT = Ptr.getValueType();
2592 bool isVolatile = I.isVolatile();
2593 unsigned Alignment = I.getAlignment();
2594 for (unsigned i = 0; i != NumValues; ++i)
2595 Chains[i] = DAG.getStore(Root, SDValue(Src.getNode(), Src.getResNo() + i),
2596 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2597 DAG.getConstant(Offsets[i], PtrVT)),
2599 isVolatile, Alignment);
2601 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2604 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2606 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2607 unsigned Intrinsic) {
2608 bool HasChain = !I.doesNotAccessMemory();
2609 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2611 // Build the operand list.
2612 SmallVector<SDValue, 8> Ops;
2613 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2615 // We don't need to serialize loads against other loads.
2616 Ops.push_back(DAG.getRoot());
2618 Ops.push_back(getRoot());
2622 // Add the intrinsic ID as an integer operand.
2623 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2625 // Add all operands of the call to the operand list.
2626 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2627 SDValue Op = getValue(I.getOperand(i));
2628 assert(TLI.isTypeLegal(Op.getValueType()) &&
2629 "Intrinsic uses a non-legal type?");
2633 std::vector<MVT> VTs;
2634 if (I.getType() != Type::VoidTy) {
2635 MVT VT = TLI.getValueType(I.getType());
2636 if (VT.isVector()) {
2637 const VectorType *DestTy = cast<VectorType>(I.getType());
2638 MVT EltVT = TLI.getValueType(DestTy->getElementType());
2640 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2641 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2644 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2648 VTs.push_back(MVT::Other);
2650 const MVT *VTList = DAG.getNodeValueTypes(VTs);
2655 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2656 &Ops[0], Ops.size());
2657 else if (I.getType() != Type::VoidTy)
2658 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2659 &Ops[0], Ops.size());
2661 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2662 &Ops[0], Ops.size());
2665 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2667 PendingLoads.push_back(Chain);
2671 if (I.getType() != Type::VoidTy) {
2672 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2673 MVT VT = TLI.getValueType(PTy);
2674 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2676 setValue(&I, Result);
2680 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2681 static GlobalVariable *ExtractTypeInfo(Value *V) {
2682 V = V->stripPointerCasts();
2683 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2684 assert ((GV || isa<ConstantPointerNull>(V)) &&
2685 "TypeInfo must be a global variable or NULL");
2691 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
2692 /// call, and add them to the specified machine basic block.
2693 void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2694 MachineBasicBlock *MBB) {
2695 // Inform the MachineModuleInfo of the personality for this landing pad.
2696 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2697 assert(CE->getOpcode() == Instruction::BitCast &&
2698 isa<Function>(CE->getOperand(0)) &&
2699 "Personality should be a function");
2700 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2702 // Gather all the type infos for this landing pad and pass them along to
2703 // MachineModuleInfo.
2704 std::vector<GlobalVariable *> TyInfo;
2705 unsigned N = I.getNumOperands();
2707 for (unsigned i = N - 1; i > 2; --i) {
2708 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2709 unsigned FilterLength = CI->getZExtValue();
2710 unsigned FirstCatch = i + FilterLength + !FilterLength;
2711 assert (FirstCatch <= N && "Invalid filter length");
2713 if (FirstCatch < N) {
2714 TyInfo.reserve(N - FirstCatch);
2715 for (unsigned j = FirstCatch; j < N; ++j)
2716 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2717 MMI->addCatchTypeInfo(MBB, TyInfo);
2721 if (!FilterLength) {
2723 MMI->addCleanup(MBB);
2726 TyInfo.reserve(FilterLength - 1);
2727 for (unsigned j = i + 1; j < FirstCatch; ++j)
2728 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2729 MMI->addFilterTypeInfo(MBB, TyInfo);
2738 TyInfo.reserve(N - 3);
2739 for (unsigned j = 3; j < N; ++j)
2740 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2741 MMI->addCatchTypeInfo(MBB, TyInfo);
2747 /// GetSignificand - Get the significand and build it into a floating-point
2748 /// number with exponent of 1:
2750 /// Op = (Op & 0x007fffff) | 0x3f800000;
2752 /// where Op is the hexidecimal representation of floating point value.
2754 GetSignificand(SelectionDAG &DAG, SDValue Op) {
2755 SDValue t1 = DAG.getNode(ISD::AND, MVT::i32, Op,
2756 DAG.getConstant(0x007fffff, MVT::i32));
2757 SDValue t2 = DAG.getNode(ISD::OR, MVT::i32, t1,
2758 DAG.getConstant(0x3f800000, MVT::i32));
2759 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t2);
2762 /// GetExponent - Get the exponent:
2764 /// (float)((Op1 >> 23) - 127);
2766 /// where Op is the hexidecimal representation of floating point value.
2768 GetExponent(SelectionDAG &DAG, SDValue Op) {
2769 SDValue t1 = DAG.getNode(ISD::SRL, MVT::i32, Op,
2770 DAG.getConstant(23, MVT::i32));
2771 SDValue t2 = DAG.getNode(ISD::SUB, MVT::i32, t1,
2772 DAG.getConstant(127, MVT::i32));
2773 return DAG.getNode(ISD::UINT_TO_FP, MVT::f32, t2);
2776 /// getF32Constant - Get 32-bit floating point constant.
2778 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
2779 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
2782 /// Inlined utility function to implement binary input atomic intrinsics for
2783 /// visitIntrinsicCall: I is a call instruction
2784 /// Op is the associated NodeType for I
2786 SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2787 SDValue Root = getRoot();
2788 SDValue L = DAG.getAtomic(Op, Root,
2789 getValue(I.getOperand(1)),
2790 getValue(I.getOperand(2)),
2793 DAG.setRoot(L.getValue(1));
2797 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
2798 /// limited-precision mode.
2800 SelectionDAGLowering::visitExp(CallInst &I) {
2803 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2804 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2805 SDValue Op = getValue(I.getOperand(1));
2807 // Put the exponent in the right bit position for later addition to the
2810 // #define LOG2OFe 1.4426950f
2811 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
2812 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
2813 getF32Constant(DAG, 0x3fb8aa3b));
2814 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
2816 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
2817 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
2818 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
2820 // IntegerPartOfX <<= 23;
2821 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
2822 DAG.getConstant(23, MVT::i32));
2824 if (LimitFloatPrecision <= 6) {
2825 // For floating-point precision of 6:
2827 // TwoToFractionalPartOfX =
2829 // (0.735607626f + 0.252464424f * x) * x;
2831 // error 0.0144103317, which is 6 bits
2832 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2833 getF32Constant(DAG, 0x3e814304));
2834 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
2835 getF32Constant(DAG, 0x3f3c50c8));
2836 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2837 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
2838 getF32Constant(DAG, 0x3f7f5e7e));
2839 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
2841 // Add the exponent into the result in integer domain.
2842 SDValue t6 = DAG.getNode(ISD::ADD, MVT::i32,
2843 TwoToFracPartOfX, IntegerPartOfX);
2845 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t6);
2846 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
2847 // For floating-point precision of 12:
2849 // TwoToFractionalPartOfX =
2852 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
2854 // 0.000107046256 error, which is 13 to 14 bits
2855 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2856 getF32Constant(DAG, 0x3da235e3));
2857 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
2858 getF32Constant(DAG, 0x3e65b8f3));
2859 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2860 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
2861 getF32Constant(DAG, 0x3f324b07));
2862 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2863 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
2864 getF32Constant(DAG, 0x3f7ff8fd));
2865 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
2867 // Add the exponent into the result in integer domain.
2868 SDValue t8 = DAG.getNode(ISD::ADD, MVT::i32,
2869 TwoToFracPartOfX, IntegerPartOfX);
2871 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t8);
2872 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
2873 // For floating-point precision of 18:
2875 // TwoToFractionalPartOfX =
2879 // (0.554906021e-1f +
2880 // (0.961591928e-2f +
2881 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
2883 // error 2.47208000*10^(-7), which is better than 18 bits
2884 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2885 getF32Constant(DAG, 0x3924b03e));
2886 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
2887 getF32Constant(DAG, 0x3ab24b87));
2888 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2889 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
2890 getF32Constant(DAG, 0x3c1d8c17));
2891 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2892 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
2893 getF32Constant(DAG, 0x3d634a1d));
2894 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
2895 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
2896 getF32Constant(DAG, 0x3e75fe14));
2897 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
2898 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
2899 getF32Constant(DAG, 0x3f317234));
2900 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
2901 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
2902 getF32Constant(DAG, 0x3f800000));
2903 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
2905 // Add the exponent into the result in integer domain.
2906 SDValue t14 = DAG.getNode(ISD::ADD, MVT::i32,
2907 TwoToFracPartOfX, IntegerPartOfX);
2909 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t14);
2912 // No special expansion.
2913 result = DAG.getNode(ISD::FEXP,
2914 getValue(I.getOperand(1)).getValueType(),
2915 getValue(I.getOperand(1)));
2918 setValue(&I, result);
2921 /// visitLog - Lower a log intrinsic. Handles the special sequences for
2922 /// limited-precision mode.
2924 SelectionDAGLowering::visitLog(CallInst &I) {
2927 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2928 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2929 SDValue Op = getValue(I.getOperand(1));
2930 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
2932 // Scale the exponent by log(2) [0.69314718f].
2933 SDValue Exp = GetExponent(DAG, Op1);
2934 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
2935 getF32Constant(DAG, 0x3f317218));
2937 // Get the significand and build it into a floating-point number with
2939 SDValue X = GetSignificand(DAG, Op1);
2941 if (LimitFloatPrecision <= 6) {
2942 // For floating-point precision of 6:
2946 // (1.4034025f - 0.23903021f * x) * x;
2948 // error 0.0034276066, which is better than 8 bits
2949 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2950 getF32Constant(DAG, 0xbe74c456));
2951 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
2952 getF32Constant(DAG, 0x3fb3a2b1));
2953 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
2954 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
2955 getF32Constant(DAG, 0x3f949a29));
2957 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
2958 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
2959 // For floating-point precision of 12:
2965 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
2967 // error 0.000061011436, which is 14 bits
2968 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2969 getF32Constant(DAG, 0xbd67b6d6));
2970 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
2971 getF32Constant(DAG, 0x3ee4f4b8));
2972 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
2973 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
2974 getF32Constant(DAG, 0x3fbc278b));
2975 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
2976 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
2977 getF32Constant(DAG, 0x40348e95));
2978 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
2979 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
2980 getF32Constant(DAG, 0x3fdef31a));
2982 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
2983 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
2984 // For floating-point precision of 18:
2992 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
2994 // error 0.0000023660568, which is better than 18 bits
2995 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
2996 getF32Constant(DAG, 0xbc91e5ac));
2997 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
2998 getF32Constant(DAG, 0x3e4350aa));
2999 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3000 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3001 getF32Constant(DAG, 0x3f60d3e3));
3002 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3003 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3004 getF32Constant(DAG, 0x4011cdf0));
3005 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3006 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
3007 getF32Constant(DAG, 0x406cfd1c));
3008 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3009 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3010 getF32Constant(DAG, 0x408797cb));
3011 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3012 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
3013 getF32Constant(DAG, 0x4006dcab));
3015 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3018 // No special expansion.
3019 result = DAG.getNode(ISD::FLOG,
3020 getValue(I.getOperand(1)).getValueType(),
3021 getValue(I.getOperand(1)));
3024 setValue(&I, result);
3027 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3028 /// limited-precision mode.
3030 SelectionDAGLowering::visitLog2(CallInst &I) {
3033 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3034 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3035 SDValue Op = getValue(I.getOperand(1));
3036 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3038 // Get the exponent.
3039 SDValue LogOfExponent = GetExponent(DAG, Op1);
3041 // Get the significand and build it into a floating-point number with
3043 SDValue X = GetSignificand(DAG, Op1);
3045 // Different possible minimax approximations of significand in
3046 // floating-point for various degrees of accuracy over [1,2].
3047 if (LimitFloatPrecision <= 6) {
3048 // For floating-point precision of 6:
3050 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3052 // error 0.0049451742, which is more than 7 bits
3053 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3054 getF32Constant(DAG, 0xbeb08fe0));
3055 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3056 getF32Constant(DAG, 0x40019463));
3057 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3058 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3059 getF32Constant(DAG, 0x3fd6633d));
3061 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3062 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3063 // For floating-point precision of 12:
3069 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3071 // error 0.0000876136000, which is better than 13 bits
3072 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3073 getF32Constant(DAG, 0xbda7262e));
3074 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3075 getF32Constant(DAG, 0x3f25280b));
3076 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3077 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3078 getF32Constant(DAG, 0x4007b923));
3079 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3080 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3081 getF32Constant(DAG, 0x40823e2f));
3082 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3083 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
3084 getF32Constant(DAG, 0x4020d29c));
3086 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3087 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3088 // For floating-point precision of 18:
3097 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3099 // error 0.0000018516, which is better than 18 bits
3100 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3101 getF32Constant(DAG, 0xbcd2769e));
3102 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3103 getF32Constant(DAG, 0x3e8ce0b9));
3104 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3105 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3106 getF32Constant(DAG, 0x3fa22ae7));
3107 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3108 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3109 getF32Constant(DAG, 0x40525723));
3110 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3111 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
3112 getF32Constant(DAG, 0x40aaf200));
3113 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3114 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3115 getF32Constant(DAG, 0x40c39dad));
3116 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3117 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
3118 getF32Constant(DAG, 0x4042902c));
3120 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3123 // No special expansion.
3124 result = DAG.getNode(ISD::FLOG2,
3125 getValue(I.getOperand(1)).getValueType(),
3126 getValue(I.getOperand(1)));
3129 setValue(&I, result);
3132 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3133 /// limited-precision mode.
3135 SelectionDAGLowering::visitLog10(CallInst &I) {
3137 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3138 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3139 SDValue Op = getValue(I.getOperand(1));
3140 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3142 // Scale the exponent by log10(2) [0.30102999f].
3143 SDValue Exp = GetExponent(DAG, Op1);
3144 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
3145 getF32Constant(DAG, 0x3e9a209a));
3147 // Get the significand and build it into a floating-point number with
3149 SDValue X = GetSignificand(DAG, Op1);
3151 if (LimitFloatPrecision <= 6) {
3152 // For floating-point precision of 6:
3154 // Log10ofMantissa =
3156 // (0.60948995f - 0.10380950f * x) * x;
3158 // error 0.0014886165, which is 6 bits
3159 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3160 getF32Constant(DAG, 0xbdd49a13));
3161 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3162 getF32Constant(DAG, 0x3f1c0789));
3163 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3164 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3165 getF32Constant(DAG, 0x3f011300));
3167 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3168 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3169 // For floating-point precision of 12:
3171 // Log10ofMantissa =
3174 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3176 // error 0.00019228036, which is better than 12 bits
3177 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3178 getF32Constant(DAG, 0x3d431f31));
3179 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
3180 getF32Constant(DAG, 0x3ea21fb2));
3181 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3182 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3183 getF32Constant(DAG, 0x3f6ae232));
3184 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3185 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t4,
3186 getF32Constant(DAG, 0x3f25f7c3));
3188 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3189 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3190 // For floating-point precision of 18:
3192 // Log10ofMantissa =
3197 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3199 // error 0.0000037995730, which is better than 18 bits
3200 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3201 getF32Constant(DAG, 0x3c5d51ce));
3202 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
3203 getF32Constant(DAG, 0x3e00685a));
3204 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3205 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3206 getF32Constant(DAG, 0x3efb6798));
3207 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3208 SDValue t5 = DAG.getNode(ISD::FSUB, MVT::f32, t4,
3209 getF32Constant(DAG, 0x3f88d192));
3210 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3211 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3212 getF32Constant(DAG, 0x3fc4316c));
3213 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3214 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t8,
3215 getF32Constant(DAG, 0x3f57ce70));
3217 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3220 // No special expansion.
3221 result = DAG.getNode(ISD::FLOG10,
3222 getValue(I.getOperand(1)).getValueType(),
3223 getValue(I.getOperand(1)));
3226 setValue(&I, result);
3229 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3230 /// limited-precision mode.
3232 SelectionDAGLowering::visitExp2(CallInst &I) {
3235 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3236 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3237 SDValue Op = getValue(I.getOperand(1));
3239 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, Op);
3241 // FractionalPartOfX = x - (float)IntegerPartOfX;
3242 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3243 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, Op, t1);
3245 // IntegerPartOfX <<= 23;
3246 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3247 DAG.getConstant(23, MVT::i32));
3249 if (LimitFloatPrecision <= 6) {
3250 // For floating-point precision of 6:
3252 // TwoToFractionalPartOfX =
3254 // (0.735607626f + 0.252464424f * x) * x;
3256 // error 0.0144103317, which is 6 bits
3257 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3258 getF32Constant(DAG, 0x3e814304));
3259 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3260 getF32Constant(DAG, 0x3f3c50c8));
3261 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3262 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3263 getF32Constant(DAG, 0x3f7f5e7e));
3264 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3265 SDValue TwoToFractionalPartOfX =
3266 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3268 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3269 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3270 // For floating-point precision of 12:
3272 // TwoToFractionalPartOfX =
3275 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3277 // error 0.000107046256, which is 13 to 14 bits
3278 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3279 getF32Constant(DAG, 0x3da235e3));
3280 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3281 getF32Constant(DAG, 0x3e65b8f3));
3282 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3283 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3284 getF32Constant(DAG, 0x3f324b07));
3285 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3286 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3287 getF32Constant(DAG, 0x3f7ff8fd));
3288 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3289 SDValue TwoToFractionalPartOfX =
3290 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3292 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3293 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3294 // For floating-point precision of 18:
3296 // TwoToFractionalPartOfX =
3300 // (0.554906021e-1f +
3301 // (0.961591928e-2f +
3302 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3303 // error 2.47208000*10^(-7), which is better than 18 bits
3304 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3305 getF32Constant(DAG, 0x3924b03e));
3306 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3307 getF32Constant(DAG, 0x3ab24b87));
3308 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3309 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3310 getF32Constant(DAG, 0x3c1d8c17));
3311 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3312 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3313 getF32Constant(DAG, 0x3d634a1d));
3314 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3315 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3316 getF32Constant(DAG, 0x3e75fe14));
3317 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3318 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
3319 getF32Constant(DAG, 0x3f317234));
3320 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3321 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
3322 getF32Constant(DAG, 0x3f800000));
3323 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3324 SDValue TwoToFractionalPartOfX =
3325 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3327 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3330 // No special expansion.
3331 result = DAG.getNode(ISD::FEXP2,
3332 getValue(I.getOperand(1)).getValueType(),
3333 getValue(I.getOperand(1)));
3336 setValue(&I, result);
3339 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3340 /// limited-precision mode with x == 10.0f.
3342 SelectionDAGLowering::visitPow(CallInst &I) {
3344 Value *Val = I.getOperand(1);
3345 bool IsExp10 = false;
3347 if (getValue(Val).getValueType() == MVT::f32 &&
3348 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
3349 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3350 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3351 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3353 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3358 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3359 SDValue Op = getValue(I.getOperand(2));
3361 // Put the exponent in the right bit position for later addition to the
3364 // #define LOG2OF10 3.3219281f
3365 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3366 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
3367 getF32Constant(DAG, 0x40549a78));
3368 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3370 // FractionalPartOfX = x - (float)IntegerPartOfX;
3371 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3372 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3374 // IntegerPartOfX <<= 23;
3375 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3376 DAG.getConstant(23, MVT::i32));
3378 if (LimitFloatPrecision <= 6) {
3379 // For floating-point precision of 6:
3381 // twoToFractionalPartOfX =
3383 // (0.735607626f + 0.252464424f * x) * x;
3385 // error 0.0144103317, which is 6 bits
3386 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3387 getF32Constant(DAG, 0x3e814304));
3388 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3389 getF32Constant(DAG, 0x3f3c50c8));
3390 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3391 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3392 getF32Constant(DAG, 0x3f7f5e7e));
3393 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3394 SDValue TwoToFractionalPartOfX =
3395 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3397 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3398 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3399 // For floating-point precision of 12:
3401 // TwoToFractionalPartOfX =
3404 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3406 // error 0.000107046256, which is 13 to 14 bits
3407 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3408 getF32Constant(DAG, 0x3da235e3));
3409 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3410 getF32Constant(DAG, 0x3e65b8f3));
3411 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3412 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3413 getF32Constant(DAG, 0x3f324b07));
3414 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3415 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3416 getF32Constant(DAG, 0x3f7ff8fd));
3417 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3418 SDValue TwoToFractionalPartOfX =
3419 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3421 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3422 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3423 // For floating-point precision of 18:
3425 // TwoToFractionalPartOfX =
3429 // (0.554906021e-1f +
3430 // (0.961591928e-2f +
3431 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3432 // error 2.47208000*10^(-7), which is better than 18 bits
3433 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3434 getF32Constant(DAG, 0x3924b03e));
3435 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3436 getF32Constant(DAG, 0x3ab24b87));
3437 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3438 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3439 getF32Constant(DAG, 0x3c1d8c17));
3440 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3441 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3442 getF32Constant(DAG, 0x3d634a1d));
3443 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3444 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3445 getF32Constant(DAG, 0x3e75fe14));
3446 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3447 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
3448 getF32Constant(DAG, 0x3f317234));
3449 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3450 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
3451 getF32Constant(DAG, 0x3f800000));
3452 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3453 SDValue TwoToFractionalPartOfX =
3454 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3456 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3459 // No special expansion.
3460 result = DAG.getNode(ISD::FPOW,
3461 getValue(I.getOperand(1)).getValueType(),
3462 getValue(I.getOperand(1)),
3463 getValue(I.getOperand(2)));
3466 setValue(&I, result);
3469 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3470 /// we want to emit this as a call to a named external function, return the name
3471 /// otherwise lower it and return null.
3473 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3474 switch (Intrinsic) {
3476 // By default, turn this into a target intrinsic node.
3477 visitTargetIntrinsic(I, Intrinsic);
3479 case Intrinsic::vastart: visitVAStart(I); return 0;
3480 case Intrinsic::vaend: visitVAEnd(I); return 0;
3481 case Intrinsic::vacopy: visitVACopy(I); return 0;
3482 case Intrinsic::returnaddress:
3483 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3484 getValue(I.getOperand(1))));
3486 case Intrinsic::frameaddress:
3487 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3488 getValue(I.getOperand(1))));
3490 case Intrinsic::setjmp:
3491 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3493 case Intrinsic::longjmp:
3494 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3496 case Intrinsic::memcpy_i32:
3497 case Intrinsic::memcpy_i64: {
3498 SDValue Op1 = getValue(I.getOperand(1));
3499 SDValue Op2 = getValue(I.getOperand(2));
3500 SDValue Op3 = getValue(I.getOperand(3));
3501 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3502 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3503 I.getOperand(1), 0, I.getOperand(2), 0));
3506 case Intrinsic::memset_i32:
3507 case Intrinsic::memset_i64: {
3508 SDValue Op1 = getValue(I.getOperand(1));
3509 SDValue Op2 = getValue(I.getOperand(2));
3510 SDValue Op3 = getValue(I.getOperand(3));
3511 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3512 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3513 I.getOperand(1), 0));
3516 case Intrinsic::memmove_i32:
3517 case Intrinsic::memmove_i64: {
3518 SDValue Op1 = getValue(I.getOperand(1));
3519 SDValue Op2 = getValue(I.getOperand(2));
3520 SDValue Op3 = getValue(I.getOperand(3));
3521 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3523 // If the source and destination are known to not be aliases, we can
3524 // lower memmove as memcpy.
3525 uint64_t Size = -1ULL;
3526 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3527 Size = C->getZExtValue();
3528 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3529 AliasAnalysis::NoAlias) {
3530 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3531 I.getOperand(1), 0, I.getOperand(2), 0));
3535 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3536 I.getOperand(1), 0, I.getOperand(2), 0));
3539 case Intrinsic::dbg_stoppoint: {
3540 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3541 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3542 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
3543 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
3544 assert(DD && "Not a debug information descriptor");
3545 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3548 cast<CompileUnitDesc>(DD)));
3553 case Intrinsic::dbg_region_start: {
3554 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3555 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3556 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3557 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
3558 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3563 case Intrinsic::dbg_region_end: {
3564 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3565 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3566 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3567 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
3568 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3573 case Intrinsic::dbg_func_start: {
3574 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3576 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3577 Value *SP = FSI.getSubprogram();
3578 if (SP && MMI->Verify(SP)) {
3579 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3580 // what (most?) gdb expects.
3581 DebugInfoDesc *DD = MMI->getDescFor(SP);
3582 assert(DD && "Not a debug information descriptor");
3583 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3584 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
3585 unsigned SrcFile = MMI->RecordSource(CompileUnit);
3586 // Record the source line but does create a label. It will be emitted
3587 // at asm emission time.
3588 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
3593 case Intrinsic::dbg_declare: {
3594 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3595 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3596 Value *Variable = DI.getVariable();
3597 if (MMI && Variable && MMI->Verify(Variable))
3598 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3599 getValue(DI.getAddress()), getValue(Variable)));
3603 case Intrinsic::eh_exception: {
3604 if (!CurMBB->isLandingPad()) {
3605 // FIXME: Mark exception register as live in. Hack for PR1508.
3606 unsigned Reg = TLI.getExceptionAddressRegister();
3607 if (Reg) CurMBB->addLiveIn(Reg);
3609 // Insert the EXCEPTIONADDR instruction.
3610 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3612 Ops[0] = DAG.getRoot();
3613 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3615 DAG.setRoot(Op.getValue(1));
3619 case Intrinsic::eh_selector_i32:
3620 case Intrinsic::eh_selector_i64: {
3621 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3622 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3623 MVT::i32 : MVT::i64);
3626 if (CurMBB->isLandingPad())
3627 AddCatchInfo(I, MMI, CurMBB);
3630 FuncInfo.CatchInfoLost.insert(&I);
3632 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3633 unsigned Reg = TLI.getExceptionSelectorRegister();
3634 if (Reg) CurMBB->addLiveIn(Reg);
3637 // Insert the EHSELECTION instruction.
3638 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3640 Ops[0] = getValue(I.getOperand(1));
3642 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3644 DAG.setRoot(Op.getValue(1));
3646 setValue(&I, DAG.getConstant(0, VT));
3652 case Intrinsic::eh_typeid_for_i32:
3653 case Intrinsic::eh_typeid_for_i64: {
3654 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3655 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3656 MVT::i32 : MVT::i64);
3659 // Find the type id for the given typeinfo.
3660 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3662 unsigned TypeID = MMI->getTypeIDFor(GV);
3663 setValue(&I, DAG.getConstant(TypeID, VT));
3665 // Return something different to eh_selector.
3666 setValue(&I, DAG.getConstant(1, VT));
3672 case Intrinsic::eh_return_i32:
3673 case Intrinsic::eh_return_i64:
3674 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3675 MMI->setCallsEHReturn(true);
3676 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3679 getValue(I.getOperand(1)),
3680 getValue(I.getOperand(2))));
3682 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3686 case Intrinsic::eh_unwind_init:
3687 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3688 MMI->setCallsUnwindInit(true);
3693 case Intrinsic::eh_dwarf_cfa: {
3694 MVT VT = getValue(I.getOperand(1)).getValueType();
3696 if (VT.bitsGT(TLI.getPointerTy()))
3697 CfaArg = DAG.getNode(ISD::TRUNCATE,
3698 TLI.getPointerTy(), getValue(I.getOperand(1)));
3700 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3701 TLI.getPointerTy(), getValue(I.getOperand(1)));
3703 SDValue Offset = DAG.getNode(ISD::ADD,
3705 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3706 TLI.getPointerTy()),
3708 setValue(&I, DAG.getNode(ISD::ADD,
3710 DAG.getNode(ISD::FRAMEADDR,
3713 TLI.getPointerTy())),
3718 case Intrinsic::sqrt:
3719 setValue(&I, DAG.getNode(ISD::FSQRT,
3720 getValue(I.getOperand(1)).getValueType(),
3721 getValue(I.getOperand(1))));
3723 case Intrinsic::powi:
3724 setValue(&I, DAG.getNode(ISD::FPOWI,
3725 getValue(I.getOperand(1)).getValueType(),
3726 getValue(I.getOperand(1)),
3727 getValue(I.getOperand(2))));
3729 case Intrinsic::sin:
3730 setValue(&I, DAG.getNode(ISD::FSIN,
3731 getValue(I.getOperand(1)).getValueType(),
3732 getValue(I.getOperand(1))));
3734 case Intrinsic::cos:
3735 setValue(&I, DAG.getNode(ISD::FCOS,
3736 getValue(I.getOperand(1)).getValueType(),
3737 getValue(I.getOperand(1))));
3739 case Intrinsic::log:
3742 case Intrinsic::log2:
3745 case Intrinsic::log10:
3748 case Intrinsic::exp:
3751 case Intrinsic::exp2:
3754 case Intrinsic::pow:
3757 case Intrinsic::pcmarker: {
3758 SDValue Tmp = getValue(I.getOperand(1));
3759 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3762 case Intrinsic::readcyclecounter: {
3763 SDValue Op = getRoot();
3764 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3765 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3768 DAG.setRoot(Tmp.getValue(1));
3771 case Intrinsic::part_select: {
3772 // Currently not implemented: just abort
3773 assert(0 && "part_select intrinsic not implemented");
3776 case Intrinsic::part_set: {
3777 // Currently not implemented: just abort
3778 assert(0 && "part_set intrinsic not implemented");
3781 case Intrinsic::bswap:
3782 setValue(&I, DAG.getNode(ISD::BSWAP,
3783 getValue(I.getOperand(1)).getValueType(),
3784 getValue(I.getOperand(1))));
3786 case Intrinsic::cttz: {
3787 SDValue Arg = getValue(I.getOperand(1));
3788 MVT Ty = Arg.getValueType();
3789 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
3790 setValue(&I, result);
3793 case Intrinsic::ctlz: {
3794 SDValue Arg = getValue(I.getOperand(1));
3795 MVT Ty = Arg.getValueType();
3796 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
3797 setValue(&I, result);
3800 case Intrinsic::ctpop: {
3801 SDValue Arg = getValue(I.getOperand(1));
3802 MVT Ty = Arg.getValueType();
3803 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
3804 setValue(&I, result);
3807 case Intrinsic::stacksave: {
3808 SDValue Op = getRoot();
3809 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
3810 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
3812 DAG.setRoot(Tmp.getValue(1));
3815 case Intrinsic::stackrestore: {
3816 SDValue Tmp = getValue(I.getOperand(1));
3817 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
3820 case Intrinsic::var_annotation:
3821 // Discard annotate attributes
3824 case Intrinsic::init_trampoline: {
3825 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
3829 Ops[1] = getValue(I.getOperand(1));
3830 Ops[2] = getValue(I.getOperand(2));
3831 Ops[3] = getValue(I.getOperand(3));
3832 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3833 Ops[5] = DAG.getSrcValue(F);
3835 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
3836 DAG.getNodeValueTypes(TLI.getPointerTy(),
3841 DAG.setRoot(Tmp.getValue(1));
3845 case Intrinsic::gcroot:
3847 Value *Alloca = I.getOperand(1);
3848 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3850 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
3851 GFI->addStackRoot(FI->getIndex(), TypeMap);
3855 case Intrinsic::gcread:
3856 case Intrinsic::gcwrite:
3857 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
3860 case Intrinsic::flt_rounds: {
3861 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
3865 case Intrinsic::trap: {
3866 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3869 case Intrinsic::prefetch: {
3872 Ops[1] = getValue(I.getOperand(1));
3873 Ops[2] = getValue(I.getOperand(2));
3874 Ops[3] = getValue(I.getOperand(3));
3875 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3879 case Intrinsic::memory_barrier: {
3882 for (int x = 1; x < 6; ++x)
3883 Ops[x] = getValue(I.getOperand(x));
3885 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3888 case Intrinsic::atomic_cmp_swap: {
3889 SDValue Root = getRoot();
3891 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3893 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_8, Root,
3894 getValue(I.getOperand(1)),
3895 getValue(I.getOperand(2)),
3896 getValue(I.getOperand(3)),
3900 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_16, Root,
3901 getValue(I.getOperand(1)),
3902 getValue(I.getOperand(2)),
3903 getValue(I.getOperand(3)),
3907 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_32, Root,
3908 getValue(I.getOperand(1)),
3909 getValue(I.getOperand(2)),
3910 getValue(I.getOperand(3)),
3914 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_64, Root,
3915 getValue(I.getOperand(1)),
3916 getValue(I.getOperand(2)),
3917 getValue(I.getOperand(3)),
3921 assert(0 && "Invalid atomic type");
3925 DAG.setRoot(L.getValue(1));
3928 case Intrinsic::atomic_load_add:
3929 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3931 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_8);
3933 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_16);
3935 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_32);
3937 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_64);
3939 assert(0 && "Invalid atomic type");
3942 case Intrinsic::atomic_load_sub:
3943 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3945 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_8);
3947 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_16);
3949 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_32);
3951 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_64);
3953 assert(0 && "Invalid atomic type");
3956 case Intrinsic::atomic_load_or:
3957 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3959 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_8);
3961 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_16);
3963 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_32);
3965 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_64);
3967 assert(0 && "Invalid atomic type");
3970 case Intrinsic::atomic_load_xor:
3971 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3973 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_8);
3975 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_16);
3977 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_32);
3979 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_64);
3981 assert(0 && "Invalid atomic type");
3984 case Intrinsic::atomic_load_and:
3985 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3987 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_8);
3989 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_16);
3991 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_32);
3993 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_64);
3995 assert(0 && "Invalid atomic type");
3998 case Intrinsic::atomic_load_nand:
3999 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4001 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_8);
4003 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_16);
4005 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_32);
4007 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_64);
4009 assert(0 && "Invalid atomic type");
4012 case Intrinsic::atomic_load_max:
4013 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4015 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_8);
4017 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_16);
4019 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_32);
4021 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_64);
4023 assert(0 && "Invalid atomic type");
4026 case Intrinsic::atomic_load_min:
4027 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4029 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_8);
4031 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_16);
4033 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_32);
4035 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_64);
4037 assert(0 && "Invalid atomic type");
4040 case Intrinsic::atomic_load_umin:
4041 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4043 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_8);
4045 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_16);
4047 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_32);
4049 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_64);
4051 assert(0 && "Invalid atomic type");
4054 case Intrinsic::atomic_load_umax:
4055 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4057 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_8);
4059 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_16);
4061 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_32);
4063 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_64);
4065 assert(0 && "Invalid atomic type");
4068 case Intrinsic::atomic_swap:
4069 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
4071 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_8);
4073 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_16);
4075 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_32);
4077 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_64);
4079 assert(0 && "Invalid atomic type");
4086 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4088 MachineBasicBlock *LandingPad) {
4089 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4090 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4091 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4092 unsigned BeginLabel = 0, EndLabel = 0;
4094 TargetLowering::ArgListTy Args;
4095 TargetLowering::ArgListEntry Entry;
4096 Args.reserve(CS.arg_size());
4097 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4099 SDValue ArgNode = getValue(*i);
4100 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4102 unsigned attrInd = i - CS.arg_begin() + 1;
4103 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4104 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4105 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4106 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4107 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4108 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4109 Entry.Alignment = CS.getParamAlignment(attrInd);
4110 Args.push_back(Entry);
4113 if (LandingPad && MMI) {
4114 // Insert a label before the invoke call to mark the try range. This can be
4115 // used to detect deletion of the invoke via the MachineModuleInfo.
4116 BeginLabel = MMI->NextLabelID();
4117 // Both PendingLoads and PendingExports must be flushed here;
4118 // this call might not return.
4120 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
4123 std::pair<SDValue,SDValue> Result =
4124 TLI.LowerCallTo(getRoot(), CS.getType(),
4125 CS.paramHasAttr(0, Attribute::SExt),
4126 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4127 CS.paramHasAttr(0, Attribute::InReg),
4128 CS.getCallingConv(),
4129 IsTailCall && PerformTailCallOpt,
4131 if (CS.getType() != Type::VoidTy)
4132 setValue(CS.getInstruction(), Result.first);
4133 DAG.setRoot(Result.second);
4135 if (LandingPad && MMI) {
4136 // Insert a label at the end of the invoke call to mark the try range. This
4137 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4138 EndLabel = MMI->NextLabelID();
4139 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
4141 // Inform MachineModuleInfo of range.
4142 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4147 void SelectionDAGLowering::visitCall(CallInst &I) {
4148 const char *RenameFn = 0;
4149 if (Function *F = I.getCalledFunction()) {
4150 if (F->isDeclaration()) {
4151 if (unsigned IID = F->getIntrinsicID()) {
4152 RenameFn = visitIntrinsicCall(I, IID);
4158 // Check for well-known libc/libm calls. If the function is internal, it
4159 // can't be a library call.
4160 unsigned NameLen = F->getNameLen();
4161 if (!F->hasInternalLinkage() && NameLen) {
4162 const char *NameStr = F->getNameStart();
4163 if (NameStr[0] == 'c' &&
4164 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4165 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4166 if (I.getNumOperands() == 3 && // Basic sanity checks.
4167 I.getOperand(1)->getType()->isFloatingPoint() &&
4168 I.getType() == I.getOperand(1)->getType() &&
4169 I.getType() == I.getOperand(2)->getType()) {
4170 SDValue LHS = getValue(I.getOperand(1));
4171 SDValue RHS = getValue(I.getOperand(2));
4172 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
4176 } else if (NameStr[0] == 'f' &&
4177 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4178 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4179 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4180 if (I.getNumOperands() == 2 && // Basic sanity checks.
4181 I.getOperand(1)->getType()->isFloatingPoint() &&
4182 I.getType() == I.getOperand(1)->getType()) {
4183 SDValue Tmp = getValue(I.getOperand(1));
4184 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
4187 } else if (NameStr[0] == 's' &&
4188 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4189 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4190 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4191 if (I.getNumOperands() == 2 && // Basic sanity checks.
4192 I.getOperand(1)->getType()->isFloatingPoint() &&
4193 I.getType() == I.getOperand(1)->getType()) {
4194 SDValue Tmp = getValue(I.getOperand(1));
4195 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
4198 } else if (NameStr[0] == 'c' &&
4199 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4200 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4201 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4202 if (I.getNumOperands() == 2 && // Basic sanity checks.
4203 I.getOperand(1)->getType()->isFloatingPoint() &&
4204 I.getType() == I.getOperand(1)->getType()) {
4205 SDValue Tmp = getValue(I.getOperand(1));
4206 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
4211 } else if (isa<InlineAsm>(I.getOperand(0))) {
4218 Callee = getValue(I.getOperand(0));
4220 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
4222 LowerCallTo(&I, Callee, I.isTailCall());
4226 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4227 /// this value and returns the result as a ValueVT value. This uses
4228 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4229 /// If the Flag pointer is NULL, no flag is used.
4230 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
4232 SDValue *Flag) const {
4233 // Assemble the legal parts into the final values.
4234 SmallVector<SDValue, 4> Values(ValueVTs.size());
4235 SmallVector<SDValue, 8> Parts;
4236 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4237 // Copy the legal parts from the registers.
4238 MVT ValueVT = ValueVTs[Value];
4239 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4240 MVT RegisterVT = RegVTs[Value];
4242 Parts.resize(NumRegs);
4243 for (unsigned i = 0; i != NumRegs; ++i) {
4246 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
4248 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
4249 *Flag = P.getValue(2);
4251 Chain = P.getValue(1);
4253 // If the source register was virtual and if we know something about it,
4254 // add an assert node.
4255 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4256 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4257 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4258 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4259 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4260 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4262 unsigned RegSize = RegisterVT.getSizeInBits();
4263 unsigned NumSignBits = LOI.NumSignBits;
4264 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4266 // FIXME: We capture more information than the dag can represent. For
4267 // now, just use the tightest assertzext/assertsext possible.
4269 MVT FromVT(MVT::Other);
4270 if (NumSignBits == RegSize)
4271 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4272 else if (NumZeroBits >= RegSize-1)
4273 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4274 else if (NumSignBits > RegSize-8)
4275 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4276 else if (NumZeroBits >= RegSize-9)
4277 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4278 else if (NumSignBits > RegSize-16)
4279 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
4280 else if (NumZeroBits >= RegSize-17)
4281 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
4282 else if (NumSignBits > RegSize-32)
4283 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
4284 else if (NumZeroBits >= RegSize-33)
4285 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
4287 if (FromVT != MVT::Other) {
4288 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
4289 RegisterVT, P, DAG.getValueType(FromVT));
4298 Values[Value] = getCopyFromParts(DAG, Parts.begin(), NumRegs, RegisterVT,
4304 return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4305 &Values[0], ValueVTs.size());
4308 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4309 /// specified value into the registers specified by this object. This uses
4310 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4311 /// If the Flag pointer is NULL, no flag is used.
4312 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
4313 SDValue &Chain, SDValue *Flag) const {
4314 // Get the list of the values's legal parts.
4315 unsigned NumRegs = Regs.size();
4316 SmallVector<SDValue, 8> Parts(NumRegs);
4317 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4318 MVT ValueVT = ValueVTs[Value];
4319 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4320 MVT RegisterVT = RegVTs[Value];
4322 getCopyToParts(DAG, Val.getValue(Val.getResNo() + Value),
4323 &Parts[Part], NumParts, RegisterVT);
4327 // Copy the parts into the registers.
4328 SmallVector<SDValue, 8> Chains(NumRegs);
4329 for (unsigned i = 0; i != NumRegs; ++i) {
4332 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
4334 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
4335 *Flag = Part.getValue(1);
4337 Chains[i] = Part.getValue(0);
4340 if (NumRegs == 1 || Flag)
4341 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4342 // flagged to it. That is the CopyToReg nodes and the user are considered
4343 // a single scheduling unit. If we create a TokenFactor and return it as
4344 // chain, then the TokenFactor is both a predecessor (operand) of the
4345 // user as well as a successor (the TF operands are flagged to the user).
4346 // c1, f1 = CopyToReg
4347 // c2, f2 = CopyToReg
4348 // c3 = TokenFactor c1, c2
4351 Chain = Chains[NumRegs-1];
4353 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
4356 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
4357 /// operand list. This adds the code marker and includes the number of
4358 /// values added into it.
4359 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
4360 std::vector<SDValue> &Ops) const {
4361 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4362 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
4363 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4364 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4365 MVT RegisterVT = RegVTs[Value];
4366 for (unsigned i = 0; i != NumRegs; ++i)
4367 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
4371 /// isAllocatableRegister - If the specified register is safe to allocate,
4372 /// i.e. it isn't a stack pointer or some other special register, return the
4373 /// register class for the register. Otherwise, return null.
4374 static const TargetRegisterClass *
4375 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4376 const TargetLowering &TLI,
4377 const TargetRegisterInfo *TRI) {
4378 MVT FoundVT = MVT::Other;
4379 const TargetRegisterClass *FoundRC = 0;
4380 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4381 E = TRI->regclass_end(); RCI != E; ++RCI) {
4382 MVT ThisVT = MVT::Other;
4384 const TargetRegisterClass *RC = *RCI;
4385 // If none of the the value types for this register class are valid, we
4386 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4387 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4389 if (TLI.isTypeLegal(*I)) {
4390 // If we have already found this register in a different register class,
4391 // choose the one with the largest VT specified. For example, on
4392 // PowerPC, we favor f64 register classes over f32.
4393 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4400 if (ThisVT == MVT::Other) continue;
4402 // NOTE: This isn't ideal. In particular, this might allocate the
4403 // frame pointer in functions that need it (due to them not being taken
4404 // out of allocation, because a variable sized allocation hasn't been seen
4405 // yet). This is a slight code pessimization, but should still work.
4406 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4407 E = RC->allocation_order_end(MF); I != E; ++I)
4409 // We found a matching register class. Keep looking at others in case
4410 // we find one with larger registers that this physreg is also in.
4421 /// AsmOperandInfo - This contains information for each constraint that we are
4423 struct VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4424 public TargetLowering::AsmOperandInfo {
4425 /// CallOperand - If this is the result output operand or a clobber
4426 /// this is null, otherwise it is the incoming operand to the CallInst.
4427 /// This gets modified as the asm is processed.
4428 SDValue CallOperand;
4430 /// AssignedRegs - If this is a register or register class operand, this
4431 /// contains the set of register corresponding to the operand.
4432 RegsForValue AssignedRegs;
4434 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4435 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4438 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4439 /// busy in OutputRegs/InputRegs.
4440 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4441 std::set<unsigned> &OutputRegs,
4442 std::set<unsigned> &InputRegs,
4443 const TargetRegisterInfo &TRI) const {
4445 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4446 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4449 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4450 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4455 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4457 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4458 const TargetRegisterInfo &TRI) {
4459 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4461 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4462 for (; *Aliases; ++Aliases)
4463 Regs.insert(*Aliases);
4466 } // end llvm namespace.
4469 /// GetRegistersForValue - Assign registers (virtual or physical) for the
4470 /// specified operand. We prefer to assign virtual registers, to allow the
4471 /// register allocator handle the assignment process. However, if the asm uses
4472 /// features that we can't model on machineinstrs, we have SDISel do the
4473 /// allocation. This produces generally horrible, but correct, code.
4475 /// OpInfo describes the operand.
4476 /// Input and OutputRegs are the set of already allocated physical registers.
4478 void SelectionDAGLowering::
4479 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
4480 std::set<unsigned> &OutputRegs,
4481 std::set<unsigned> &InputRegs) {
4482 // Compute whether this value requires an input register, an output register,
4484 bool isOutReg = false;
4485 bool isInReg = false;
4486 switch (OpInfo.Type) {
4487 case InlineAsm::isOutput:
4490 // If there is an input constraint that matches this, we need to reserve
4491 // the input register so no other inputs allocate to it.
4492 isInReg = OpInfo.hasMatchingInput;
4494 case InlineAsm::isInput:
4498 case InlineAsm::isClobber:
4505 MachineFunction &MF = DAG.getMachineFunction();
4506 SmallVector<unsigned, 4> Regs;
4508 // If this is a constraint for a single physreg, or a constraint for a
4509 // register class, find it.
4510 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4511 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4512 OpInfo.ConstraintVT);
4514 unsigned NumRegs = 1;
4515 if (OpInfo.ConstraintVT != MVT::Other)
4516 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
4518 MVT ValueVT = OpInfo.ConstraintVT;
4521 // If this is a constraint for a specific physical register, like {r17},
4523 if (PhysReg.first) {
4524 if (OpInfo.ConstraintVT == MVT::Other)
4525 ValueVT = *PhysReg.second->vt_begin();
4527 // Get the actual register value type. This is important, because the user
4528 // may have asked for (e.g.) the AX register in i32 type. We need to
4529 // remember that AX is actually i16 to get the right extension.
4530 RegVT = *PhysReg.second->vt_begin();
4532 // This is a explicit reference to a physical register.
4533 Regs.push_back(PhysReg.first);
4535 // If this is an expanded reference, add the rest of the regs to Regs.
4537 TargetRegisterClass::iterator I = PhysReg.second->begin();
4538 for (; *I != PhysReg.first; ++I)
4539 assert(I != PhysReg.second->end() && "Didn't find reg!");
4541 // Already added the first reg.
4543 for (; NumRegs; --NumRegs, ++I) {
4544 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
4548 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4549 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4550 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4554 // Otherwise, if this was a reference to an LLVM register class, create vregs
4555 // for this reference.
4556 std::vector<unsigned> RegClassRegs;
4557 const TargetRegisterClass *RC = PhysReg.second;
4559 // If this is a tied register, our regalloc doesn't know how to maintain
4560 // the constraint. If it isn't, go ahead and create vreg
4561 // and let the regalloc do the right thing.
4562 if (!OpInfo.hasMatchingInput) {
4563 RegVT = *PhysReg.second->vt_begin();
4564 if (OpInfo.ConstraintVT == MVT::Other)
4567 // Create the appropriate number of virtual registers.
4568 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4569 for (; NumRegs; --NumRegs)
4570 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
4572 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4576 // Otherwise, we can't allocate it. Let the code below figure out how to
4577 // maintain these constraints.
4578 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4581 // This is a reference to a register class that doesn't directly correspond
4582 // to an LLVM register class. Allocate NumRegs consecutive, available,
4583 // registers from the class.
4584 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4585 OpInfo.ConstraintVT);
4588 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4589 unsigned NumAllocated = 0;
4590 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4591 unsigned Reg = RegClassRegs[i];
4592 // See if this register is available.
4593 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4594 (isInReg && InputRegs.count(Reg))) { // Already used.
4595 // Make sure we find consecutive registers.
4600 // Check to see if this register is allocatable (i.e. don't give out the
4603 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4604 if (!RC) { // Couldn't allocate this register.
4605 // Reset NumAllocated to make sure we return consecutive registers.
4611 // Okay, this register is good, we can use it.
4614 // If we allocated enough consecutive registers, succeed.
4615 if (NumAllocated == NumRegs) {
4616 unsigned RegStart = (i-NumAllocated)+1;
4617 unsigned RegEnd = i+1;
4618 // Mark all of the allocated registers used.
4619 for (unsigned i = RegStart; i != RegEnd; ++i)
4620 Regs.push_back(RegClassRegs[i]);
4622 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
4623 OpInfo.ConstraintVT);
4624 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4629 // Otherwise, we couldn't allocate enough registers for this.
4632 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
4633 /// processed uses a memory 'm' constraint.
4635 hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
4636 TargetLowering &TLI) {
4637 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
4638 InlineAsm::ConstraintInfo &CI = CInfos[i];
4639 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
4640 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
4641 if (CType == TargetLowering::C_Memory)
4649 /// visitInlineAsm - Handle a call to an InlineAsm object.
4651 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4652 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4654 /// ConstraintOperands - Information about all of the constraints.
4655 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
4657 SDValue Chain = getRoot();
4660 std::set<unsigned> OutputRegs, InputRegs;
4662 // Do a prepass over the constraints, canonicalizing them, and building up the
4663 // ConstraintOperands list.
4664 std::vector<InlineAsm::ConstraintInfo>
4665 ConstraintInfos = IA->ParseConstraints();
4667 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
4669 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4670 unsigned ResNo = 0; // ResNo - The result number of the next output.
4671 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4672 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4673 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
4675 MVT OpVT = MVT::Other;
4677 // Compute the value type for each operand.
4678 switch (OpInfo.Type) {
4679 case InlineAsm::isOutput:
4680 // Indirect outputs just consume an argument.
4681 if (OpInfo.isIndirect) {
4682 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4685 // The return value of the call is this value. As such, there is no
4686 // corresponding argument.
4687 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4688 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4689 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4691 assert(ResNo == 0 && "Asm only has one result!");
4692 OpVT = TLI.getValueType(CS.getType());
4696 case InlineAsm::isInput:
4697 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4699 case InlineAsm::isClobber:
4704 // If this is an input or an indirect output, process the call argument.
4705 // BasicBlocks are labels, currently appearing only in asm's.
4706 if (OpInfo.CallOperandVal) {
4707 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
4708 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
4710 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
4711 const Type *OpTy = OpInfo.CallOperandVal->getType();
4712 // If this is an indirect operand, the operand is a pointer to the
4714 if (OpInfo.isIndirect)
4715 OpTy = cast<PointerType>(OpTy)->getElementType();
4717 // If OpTy is not a single value, it may be a struct/union that we
4718 // can tile with integers.
4719 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4720 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4728 OpTy = IntegerType::get(BitSize);
4733 OpVT = TLI.getValueType(OpTy, true);
4737 OpInfo.ConstraintVT = OpVT;
4739 // Compute the constraint code and ConstraintType to use.
4740 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
4742 // If this is a memory input, and if the operand is not indirect, do what we
4743 // need to to provide an address for the memory input.
4744 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4745 !OpInfo.isIndirect) {
4746 assert(OpInfo.Type == InlineAsm::isInput &&
4747 "Can only indirectify direct input operands!");
4749 // Memory operands really want the address of the value. If we don't have
4750 // an indirect input, put it in the constpool if we can, otherwise spill
4751 // it to a stack slot.
4753 // If the operand is a float, integer, or vector constant, spill to a
4754 // constant pool entry to get its address.
4755 Value *OpVal = OpInfo.CallOperandVal;
4756 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4757 isa<ConstantVector>(OpVal)) {
4758 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4759 TLI.getPointerTy());
4761 // Otherwise, create a stack slot and emit a store to it before the
4763 const Type *Ty = OpVal->getType();
4764 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
4765 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4766 MachineFunction &MF = DAG.getMachineFunction();
4767 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4768 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4769 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4770 OpInfo.CallOperand = StackSlot;
4773 // There is no longer a Value* corresponding to this operand.
4774 OpInfo.CallOperandVal = 0;
4775 // It is now an indirect operand.
4776 OpInfo.isIndirect = true;
4779 // If this constraint is for a specific register, allocate it before
4781 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4782 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
4784 ConstraintInfos.clear();
4787 // Second pass - Loop over all of the operands, assigning virtual or physregs
4788 // to registerclass operands.
4789 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4790 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4792 // C_Register operands have already been allocated, Other/Memory don't need
4794 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4795 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
4798 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4799 std::vector<SDValue> AsmNodeOperands;
4800 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
4801 AsmNodeOperands.push_back(
4802 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4805 // Loop over all of the inputs, copying the operand values into the
4806 // appropriate registers and processing the output regs.
4807 RegsForValue RetValRegs;
4809 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4810 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4812 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4813 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4815 switch (OpInfo.Type) {
4816 case InlineAsm::isOutput: {
4817 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4818 OpInfo.ConstraintType != TargetLowering::C_Register) {
4819 // Memory output, or 'other' output (e.g. 'X' constraint).
4820 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
4822 // Add information to the INLINEASM node to know about this output.
4823 unsigned ResOpType = 4/*MEM*/ | (1<<3);
4824 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4825 TLI.getPointerTy()));
4826 AsmNodeOperands.push_back(OpInfo.CallOperand);
4830 // Otherwise, this is a register or register class output.
4832 // Copy the output from the appropriate register. Find a register that
4834 if (OpInfo.AssignedRegs.Regs.empty()) {
4835 cerr << "Couldn't allocate output reg for constraint '"
4836 << OpInfo.ConstraintCode << "'!\n";
4840 // If this is an indirect operand, store through the pointer after the
4842 if (OpInfo.isIndirect) {
4843 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
4844 OpInfo.CallOperandVal));
4846 // This is the result value of the call.
4847 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4848 // Concatenate this output onto the outputs list.
4849 RetValRegs.append(OpInfo.AssignedRegs);
4852 // Add information to the INLINEASM node to know that this register is
4854 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
4855 6 /* EARLYCLOBBER REGDEF */ :
4857 DAG, AsmNodeOperands);
4860 case InlineAsm::isInput: {
4861 SDValue InOperandVal = OpInfo.CallOperand;
4863 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
4864 // If this is required to match an output register we have already set,
4865 // just use its register.
4866 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
4868 // Scan until we find the definition we already emitted of this operand.
4869 // When we find it, create a RegsForValue operand.
4870 unsigned CurOp = 2; // The first operand.
4871 for (; OperandNo; --OperandNo) {
4872 // Advance to the next operand.
4874 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
4875 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4876 (NumOps & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
4877 (NumOps & 7) == 4 /*MEM*/) &&
4878 "Skipped past definitions?");
4879 CurOp += (NumOps>>3)+1;
4883 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
4884 if ((NumOps & 7) == 2 /*REGDEF*/
4885 || (NumOps & 7) == 6 /* EARLYCLOBBER REGDEF */) {
4886 // Add NumOps>>3 registers to MatchedRegs.
4887 RegsForValue MatchedRegs;
4888 MatchedRegs.TLI = &TLI;
4889 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4890 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
4891 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4893 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4894 MatchedRegs.Regs.push_back(Reg);
4897 // Use the produced MatchedRegs object to
4898 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4899 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4902 assert(((NumOps & 7) == 4) && "Unknown matching constraint!");
4903 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4904 // Add information to the INLINEASM node to know about this input.
4905 AsmNodeOperands.push_back(DAG.getTargetConstant(NumOps,
4906 TLI.getPointerTy()));
4907 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4912 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
4913 assert(!OpInfo.isIndirect &&
4914 "Don't know how to handle indirect other inputs yet!");
4916 std::vector<SDValue> Ops;
4917 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4918 hasMemory, Ops, DAG);
4920 cerr << "Invalid operand for inline asm constraint '"
4921 << OpInfo.ConstraintCode << "'!\n";
4925 // Add information to the INLINEASM node to know about this input.
4926 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
4927 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4928 TLI.getPointerTy()));
4929 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
4931 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
4932 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
4933 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4934 "Memory operands expect pointer values");
4936 // Add information to the INLINEASM node to know about this input.
4937 unsigned ResOpType = 4/*MEM*/ | (1<<3);
4938 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4939 TLI.getPointerTy()));
4940 AsmNodeOperands.push_back(InOperandVal);
4944 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4945 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4946 "Unknown constraint type!");
4947 assert(!OpInfo.isIndirect &&
4948 "Don't know how to handle indirect register inputs yet!");
4950 // Copy the input into the appropriate registers.
4951 if (OpInfo.AssignedRegs.Regs.empty()) {
4952 cerr << "Couldn't allocate output reg for constraint '"
4953 << OpInfo.ConstraintCode << "'!\n";
4957 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4959 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/,
4960 DAG, AsmNodeOperands);
4963 case InlineAsm::isClobber: {
4964 // Add the clobbered value to the operand list, so that the register
4965 // allocator is aware that the physreg got clobbered.
4966 if (!OpInfo.AssignedRegs.Regs.empty())
4967 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
4968 DAG, AsmNodeOperands);
4974 // Finish up input operands.
4975 AsmNodeOperands[0] = Chain;
4976 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
4978 Chain = DAG.getNode(ISD::INLINEASM,
4979 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
4980 &AsmNodeOperands[0], AsmNodeOperands.size());
4981 Flag = Chain.getValue(1);
4983 // If this asm returns a register value, copy the result from that register
4984 // and set it as the value of the call.
4985 if (!RetValRegs.Regs.empty()) {
4986 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
4988 // If any of the results of the inline asm is a vector, it may have the
4989 // wrong width/num elts. This can happen for register classes that can
4990 // contain multiple different value types. The preg or vreg allocated may
4991 // not have the same VT as was expected. Convert it to the right type with
4993 if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4994 for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
4995 if (Val.getNode()->getValueType(i).isVector())
4996 Val = DAG.getNode(ISD::BIT_CONVERT,
4997 TLI.getValueType(ResSTy->getElementType(i)), Val);
5000 if (Val.getValueType().isVector())
5001 Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
5005 setValue(CS.getInstruction(), Val);
5008 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5010 // Process indirect outputs, first output all of the flagged copies out of
5012 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5013 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5014 Value *Ptr = IndirectStoresToEmit[i].second;
5015 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
5016 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5019 // Emit the non-flagged stores from the physregs.
5020 SmallVector<SDValue, 8> OutChains;
5021 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5022 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
5023 getValue(StoresToEmit[i].second),
5024 StoresToEmit[i].second, 0));
5025 if (!OutChains.empty())
5026 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5027 &OutChains[0], OutChains.size());
5032 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5033 SDValue Src = getValue(I.getOperand(0));
5035 MVT IntPtr = TLI.getPointerTy();
5037 if (IntPtr.bitsLT(Src.getValueType()))
5038 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
5039 else if (IntPtr.bitsGT(Src.getValueType()))
5040 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
5042 // Scale the source by the type size.
5043 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
5044 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
5045 Src, DAG.getIntPtrConstant(ElementSize));
5047 TargetLowering::ArgListTy Args;
5048 TargetLowering::ArgListEntry Entry;
5050 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5051 Args.push_back(Entry);
5053 std::pair<SDValue,SDValue> Result =
5054 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
5055 CallingConv::C, PerformTailCallOpt,
5056 DAG.getExternalSymbol("malloc", IntPtr),
5058 setValue(&I, Result.first); // Pointers always fit in registers
5059 DAG.setRoot(Result.second);
5062 void SelectionDAGLowering::visitFree(FreeInst &I) {
5063 TargetLowering::ArgListTy Args;
5064 TargetLowering::ArgListEntry Entry;
5065 Entry.Node = getValue(I.getOperand(0));
5066 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5067 Args.push_back(Entry);
5068 MVT IntPtr = TLI.getPointerTy();
5069 std::pair<SDValue,SDValue> Result =
5070 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
5071 CallingConv::C, PerformTailCallOpt,
5072 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
5073 DAG.setRoot(Result.second);
5076 void SelectionDAGLowering::visitVAStart(CallInst &I) {
5077 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
5078 getValue(I.getOperand(1)),
5079 DAG.getSrcValue(I.getOperand(1))));
5082 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
5083 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
5084 getValue(I.getOperand(0)),
5085 DAG.getSrcValue(I.getOperand(0)));
5087 DAG.setRoot(V.getValue(1));
5090 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
5091 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
5092 getValue(I.getOperand(1)),
5093 DAG.getSrcValue(I.getOperand(1))));
5096 void SelectionDAGLowering::visitVACopy(CallInst &I) {
5097 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
5098 getValue(I.getOperand(1)),
5099 getValue(I.getOperand(2)),
5100 DAG.getSrcValue(I.getOperand(1)),
5101 DAG.getSrcValue(I.getOperand(2))));
5104 /// TargetLowering::LowerArguments - This is the default LowerArguments
5105 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
5106 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
5107 /// integrated into SDISel.
5108 void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
5109 SmallVectorImpl<SDValue> &ArgValues) {
5110 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5111 SmallVector<SDValue, 3+16> Ops;
5112 Ops.push_back(DAG.getRoot());
5113 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5114 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5116 // Add one result value for each formal argument.
5117 SmallVector<MVT, 16> RetVals;
5119 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5121 SmallVector<MVT, 4> ValueVTs;
5122 ComputeValueVTs(*this, I->getType(), ValueVTs);
5123 for (unsigned Value = 0, NumValues = ValueVTs.size();
5124 Value != NumValues; ++Value) {
5125 MVT VT = ValueVTs[Value];
5126 const Type *ArgTy = VT.getTypeForMVT();
5127 ISD::ArgFlagsTy Flags;
5128 unsigned OriginalAlignment =
5129 getTargetData()->getABITypeAlignment(ArgTy);
5131 if (F.paramHasAttr(j, Attribute::ZExt))
5133 if (F.paramHasAttr(j, Attribute::SExt))
5135 if (F.paramHasAttr(j, Attribute::InReg))
5137 if (F.paramHasAttr(j, Attribute::StructRet))
5139 if (F.paramHasAttr(j, Attribute::ByVal)) {
5141 const PointerType *Ty = cast<PointerType>(I->getType());
5142 const Type *ElementTy = Ty->getElementType();
5143 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5144 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
5145 // For ByVal, alignment should be passed from FE. BE will guess if
5146 // this info is not there but there are cases it cannot get right.
5147 if (F.getParamAlignment(j))
5148 FrameAlign = F.getParamAlignment(j);
5149 Flags.setByValAlign(FrameAlign);
5150 Flags.setByValSize(FrameSize);
5152 if (F.paramHasAttr(j, Attribute::Nest))
5154 Flags.setOrigAlign(OriginalAlignment);
5156 MVT RegisterVT = getRegisterType(VT);
5157 unsigned NumRegs = getNumRegisters(VT);
5158 for (unsigned i = 0; i != NumRegs; ++i) {
5159 RetVals.push_back(RegisterVT);
5160 ISD::ArgFlagsTy MyFlags = Flags;
5161 if (NumRegs > 1 && i == 0)
5163 // if it isn't first piece, alignment must be 1
5165 MyFlags.setOrigAlign(1);
5166 Ops.push_back(DAG.getArgFlags(MyFlags));
5171 RetVals.push_back(MVT::Other);
5174 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
5175 DAG.getVTList(&RetVals[0], RetVals.size()),
5176 &Ops[0], Ops.size()).getNode();
5178 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5179 // allows exposing the loads that may be part of the argument access to the
5180 // first DAGCombiner pass.
5181 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
5183 // The number of results should match up, except that the lowered one may have
5184 // an extra flag result.
5185 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5186 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5187 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5188 && "Lowering produced unexpected number of results!");
5190 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5191 if (Result != TmpRes.getNode() && Result->use_empty()) {
5192 HandleSDNode Dummy(DAG.getRoot());
5193 DAG.RemoveDeadNode(Result);
5196 Result = TmpRes.getNode();
5198 unsigned NumArgRegs = Result->getNumValues() - 1;
5199 DAG.setRoot(SDValue(Result, NumArgRegs));
5201 // Set up the return result vector.
5204 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5206 SmallVector<MVT, 4> ValueVTs;
5207 ComputeValueVTs(*this, I->getType(), ValueVTs);
5208 for (unsigned Value = 0, NumValues = ValueVTs.size();
5209 Value != NumValues; ++Value) {
5210 MVT VT = ValueVTs[Value];
5211 MVT PartVT = getRegisterType(VT);
5213 unsigned NumParts = getNumRegisters(VT);
5214 SmallVector<SDValue, 4> Parts(NumParts);
5215 for (unsigned j = 0; j != NumParts; ++j)
5216 Parts[j] = SDValue(Result, i++);
5218 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5219 if (F.paramHasAttr(Idx, Attribute::SExt))
5220 AssertOp = ISD::AssertSext;
5221 else if (F.paramHasAttr(Idx, Attribute::ZExt))
5222 AssertOp = ISD::AssertZext;
5224 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
5228 assert(i == NumArgRegs && "Argument register count mismatch!");
5232 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
5233 /// implementation, which just inserts an ISD::CALL node, which is later custom
5234 /// lowered by the target to something concrete. FIXME: When all targets are
5235 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5236 std::pair<SDValue, SDValue>
5237 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5238 bool RetSExt, bool RetZExt, bool isVarArg,
5240 unsigned CallingConv, bool isTailCall,
5242 ArgListTy &Args, SelectionDAG &DAG) {
5243 assert((!isTailCall || PerformTailCallOpt) &&
5244 "isTailCall set when tail-call optimizations are disabled!");
5246 SmallVector<SDValue, 32> Ops;
5247 Ops.push_back(Chain); // Op#0 - Chain
5248 Ops.push_back(Callee);
5250 // Handle all of the outgoing arguments.
5251 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5252 SmallVector<MVT, 4> ValueVTs;
5253 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5254 for (unsigned Value = 0, NumValues = ValueVTs.size();
5255 Value != NumValues; ++Value) {
5256 MVT VT = ValueVTs[Value];
5257 const Type *ArgTy = VT.getTypeForMVT();
5258 SDValue Op = SDValue(Args[i].Node.getNode(), Args[i].Node.getResNo() + Value);
5259 ISD::ArgFlagsTy Flags;
5260 unsigned OriginalAlignment =
5261 getTargetData()->getABITypeAlignment(ArgTy);
5267 if (Args[i].isInReg)
5271 if (Args[i].isByVal) {
5273 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5274 const Type *ElementTy = Ty->getElementType();
5275 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5276 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
5277 // For ByVal, alignment should come from FE. BE will guess if this
5278 // info is not there but there are cases it cannot get right.
5279 if (Args[i].Alignment)
5280 FrameAlign = Args[i].Alignment;
5281 Flags.setByValAlign(FrameAlign);
5282 Flags.setByValSize(FrameSize);
5286 Flags.setOrigAlign(OriginalAlignment);
5288 MVT PartVT = getRegisterType(VT);
5289 unsigned NumParts = getNumRegisters(VT);
5290 SmallVector<SDValue, 4> Parts(NumParts);
5291 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5294 ExtendKind = ISD::SIGN_EXTEND;
5295 else if (Args[i].isZExt)
5296 ExtendKind = ISD::ZERO_EXTEND;
5298 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5300 for (unsigned i = 0; i != NumParts; ++i) {
5301 // if it isn't first piece, alignment must be 1
5302 ISD::ArgFlagsTy MyFlags = Flags;
5303 if (NumParts > 1 && i == 0)
5306 MyFlags.setOrigAlign(1);
5308 Ops.push_back(Parts[i]);
5309 Ops.push_back(DAG.getArgFlags(MyFlags));
5314 // Figure out the result value types. We start by making a list of
5315 // the potentially illegal return value types.
5316 SmallVector<MVT, 4> LoweredRetTys;
5317 SmallVector<MVT, 4> RetTys;
5318 ComputeValueVTs(*this, RetTy, RetTys);
5320 // Then we translate that to a list of legal types.
5321 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5323 MVT RegisterVT = getRegisterType(VT);
5324 unsigned NumRegs = getNumRegisters(VT);
5325 for (unsigned i = 0; i != NumRegs; ++i)
5326 LoweredRetTys.push_back(RegisterVT);
5329 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
5331 // Create the CALL node.
5332 SDValue Res = DAG.getCall(CallingConv, isVarArg, isTailCall, isInreg,
5333 DAG.getVTList(&LoweredRetTys[0],
5334 LoweredRetTys.size()),
5337 Chain = Res.getValue(LoweredRetTys.size() - 1);
5339 // Gather up the call result into a single value.
5340 if (RetTy != Type::VoidTy) {
5341 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5344 AssertOp = ISD::AssertSext;
5346 AssertOp = ISD::AssertZext;
5348 SmallVector<SDValue, 4> ReturnValues;
5350 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5352 MVT RegisterVT = getRegisterType(VT);
5353 unsigned NumRegs = getNumRegisters(VT);
5354 unsigned RegNoEnd = NumRegs + RegNo;
5355 SmallVector<SDValue, 4> Results;
5356 for (; RegNo != RegNoEnd; ++RegNo)
5357 Results.push_back(Res.getValue(RegNo));
5358 SDValue ReturnValue =
5359 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
5361 ReturnValues.push_back(ReturnValue);
5363 Res = DAG.getMergeValues(DAG.getVTList(&RetTys[0], RetTys.size()),
5364 &ReturnValues[0], ReturnValues.size());
5367 return std::make_pair(Res, Chain);
5370 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5371 assert(0 && "LowerOperation not implemented for this target!");
5377 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5378 SDValue Op = getValue(V);
5379 assert((Op.getOpcode() != ISD::CopyFromReg ||
5380 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5381 "Copy from a reg to the same reg!");
5382 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5384 RegsForValue RFV(TLI, Reg, V->getType());
5385 SDValue Chain = DAG.getEntryNode();
5386 RFV.getCopyToRegs(Op, DAG, Chain, 0);
5387 PendingExports.push_back(Chain);
5390 #include "llvm/CodeGen/SelectionDAGISel.h"
5392 void SelectionDAGISel::
5393 LowerArguments(BasicBlock *LLVMBB) {
5394 // If this is the entry block, emit arguments.
5395 Function &F = *LLVMBB->getParent();
5396 SDValue OldRoot = SDL->DAG.getRoot();
5397 SmallVector<SDValue, 16> Args;
5398 TLI.LowerArguments(F, SDL->DAG, Args);
5401 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5403 SmallVector<MVT, 4> ValueVTs;
5404 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5405 unsigned NumValues = ValueVTs.size();
5406 if (!AI->use_empty()) {
5407 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues));
5408 // If this argument is live outside of the entry block, insert a copy from
5409 // whereever we got it to the vreg that other BB's will reference it as.
5410 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5411 if (VMI != FuncInfo->ValueMap.end()) {
5412 SDL->CopyValueToVirtualRegister(AI, VMI->second);
5418 // Finally, if the target has anything special to do, allow it to do so.
5419 // FIXME: this should insert code into the DAG!
5420 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5423 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5424 /// ensure constants are generated when needed. Remember the virtual registers
5425 /// that need to be added to the Machine PHI nodes as input. We cannot just
5426 /// directly add them, because expansion might result in multiple MBB's for one
5427 /// BB. As such, the start of the BB might correspond to a different MBB than
5431 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5432 TerminatorInst *TI = LLVMBB->getTerminator();
5434 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5436 // Check successor nodes' PHI nodes that expect a constant to be available
5438 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5439 BasicBlock *SuccBB = TI->getSuccessor(succ);
5440 if (!isa<PHINode>(SuccBB->begin())) continue;
5441 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5443 // If this terminator has multiple identical successors (common for
5444 // switches), only handle each succ once.
5445 if (!SuccsHandled.insert(SuccMBB)) continue;
5447 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5450 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5451 // nodes and Machine PHI nodes, but the incoming operands have not been
5453 for (BasicBlock::iterator I = SuccBB->begin();
5454 (PN = dyn_cast<PHINode>(I)); ++I) {
5455 // Ignore dead phi's.
5456 if (PN->use_empty()) continue;
5459 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5461 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5462 unsigned &RegOut = SDL->ConstantsOut[C];
5464 RegOut = FuncInfo->CreateRegForValue(C);
5465 SDL->CopyValueToVirtualRegister(C, RegOut);
5469 Reg = FuncInfo->ValueMap[PHIOp];
5471 assert(isa<AllocaInst>(PHIOp) &&
5472 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5473 "Didn't codegen value into a register!??");
5474 Reg = FuncInfo->CreateRegForValue(PHIOp);
5475 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5479 // Remember that this register needs to added to the machine PHI node as
5480 // the input for this MBB.
5481 SmallVector<MVT, 4> ValueVTs;
5482 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5483 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5484 MVT VT = ValueVTs[vti];
5485 unsigned NumRegisters = TLI.getNumRegisters(VT);
5486 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5487 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5488 Reg += NumRegisters;
5492 SDL->ConstantsOut.clear();
5495 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5496 /// supports legal types, and it emits MachineInstrs directly instead of
5497 /// creating SelectionDAG nodes.
5500 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5502 TerminatorInst *TI = LLVMBB->getTerminator();
5504 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5505 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5507 // Check successor nodes' PHI nodes that expect a constant to be available
5509 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5510 BasicBlock *SuccBB = TI->getSuccessor(succ);
5511 if (!isa<PHINode>(SuccBB->begin())) continue;
5512 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5514 // If this terminator has multiple identical successors (common for
5515 // switches), only handle each succ once.
5516 if (!SuccsHandled.insert(SuccMBB)) continue;
5518 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5521 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5522 // nodes and Machine PHI nodes, but the incoming operands have not been
5524 for (BasicBlock::iterator I = SuccBB->begin();
5525 (PN = dyn_cast<PHINode>(I)); ++I) {
5526 // Ignore dead phi's.
5527 if (PN->use_empty()) continue;
5529 // Only handle legal types. Two interesting things to note here. First,
5530 // by bailing out early, we may leave behind some dead instructions,
5531 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5532 // own moves. Second, this check is necessary becuase FastISel doesn't
5533 // use CreateRegForValue to create registers, so it always creates
5534 // exactly one register for each non-void instruction.
5535 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5536 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
5539 VT = TLI.getTypeToTransformTo(VT);
5541 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5546 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5548 unsigned Reg = F->getRegForValue(PHIOp);
5550 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5553 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));