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/Constants.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/InlineAsm.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Intrinsics.h"
28 #include "llvm/IntrinsicInst.h"
29 #include "llvm/LLVMContext.h"
30 #include "llvm/Module.h"
31 #include "llvm/CodeGen/FastISel.h"
32 #include "llvm/CodeGen/GCStrategy.h"
33 #include "llvm/CodeGen/GCMetadata.h"
34 #include "llvm/CodeGen/MachineFunction.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineInstrBuilder.h"
37 #include "llvm/CodeGen/MachineJumpTableInfo.h"
38 #include "llvm/CodeGen/MachineModuleInfo.h"
39 #include "llvm/CodeGen/MachineRegisterInfo.h"
40 #include "llvm/CodeGen/PseudoSourceValue.h"
41 #include "llvm/CodeGen/SelectionDAG.h"
42 #include "llvm/CodeGen/DwarfWriter.h"
43 #include "llvm/Analysis/DebugInfo.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/Target/TargetData.h"
46 #include "llvm/Target/TargetFrameInfo.h"
47 #include "llvm/Target/TargetInstrInfo.h"
48 #include "llvm/Target/TargetIntrinsicInfo.h"
49 #include "llvm/Target/TargetLowering.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/ErrorHandling.h"
55 #include "llvm/Support/MathExtras.h"
56 #include "llvm/Support/raw_ostream.h"
60 /// LimitFloatPrecision - Generate low-precision inline sequences for
61 /// some float libcalls (6, 8 or 12 bits).
62 static unsigned LimitFloatPrecision;
64 static cl::opt<unsigned, true>
65 LimitFPPrecision("limit-float-precision",
66 cl::desc("Generate low-precision inline sequences "
67 "for some float libcalls"),
68 cl::location(LimitFloatPrecision),
71 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
72 /// of insertvalue or extractvalue indices that identify a member, return
73 /// the linearized index of the start of the member.
75 static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
76 const unsigned *Indices,
77 const unsigned *IndicesEnd,
78 unsigned CurIndex = 0) {
79 // Base case: We're done.
80 if (Indices && Indices == IndicesEnd)
83 // Given a struct type, recursively traverse the elements.
84 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
85 for (StructType::element_iterator EB = STy->element_begin(),
87 EE = STy->element_end();
89 if (Indices && *Indices == unsigned(EI - EB))
90 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
91 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
95 // Given an array type, recursively traverse the elements.
96 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
97 const Type *EltTy = ATy->getElementType();
98 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
99 if (Indices && *Indices == i)
100 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
101 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
105 // We haven't found the type we're looking for, so keep searching.
109 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
110 /// EVTs that represent all the individual underlying
111 /// non-aggregate types that comprise it.
113 /// If Offsets is non-null, it points to a vector to be filled in
114 /// with the in-memory offsets of each of the individual values.
116 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
117 SmallVectorImpl<EVT> &ValueVTs,
118 SmallVectorImpl<uint64_t> *Offsets = 0,
119 uint64_t StartingOffset = 0) {
120 // Given a struct type, recursively traverse the elements.
121 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
122 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
123 for (StructType::element_iterator EB = STy->element_begin(),
125 EE = STy->element_end();
127 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
128 StartingOffset + SL->getElementOffset(EI - EB));
131 // Given an array type, recursively traverse the elements.
132 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
133 const Type *EltTy = ATy->getElementType();
134 uint64_t EltSize = TLI.getTargetData()->getTypeAllocSize(EltTy);
135 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
136 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
137 StartingOffset + i * EltSize);
140 // Interpret void as zero return values.
141 if (Ty == Type::getVoidTy(Ty->getContext()))
143 // Base case: we can get an EVT for this LLVM IR type.
144 ValueVTs.push_back(TLI.getValueType(Ty));
146 Offsets->push_back(StartingOffset);
150 /// RegsForValue - This struct represents the registers (physical or virtual)
151 /// that a particular set of values is assigned, and the type information about
152 /// the value. The most common situation is to represent one value at a time,
153 /// but struct or array values are handled element-wise as multiple values.
154 /// The splitting of aggregates is performed recursively, so that we never
155 /// have aggregate-typed registers. The values at this point do not necessarily
156 /// have legal types, so each value may require one or more registers of some
159 struct VISIBILITY_HIDDEN RegsForValue {
160 /// TLI - The TargetLowering object.
162 const TargetLowering *TLI;
164 /// ValueVTs - The value types of the values, which may not be legal, and
165 /// may need be promoted or synthesized from one or more registers.
167 SmallVector<EVT, 4> ValueVTs;
169 /// RegVTs - The value types of the registers. This is the same size as
170 /// ValueVTs and it records, for each value, what the type of the assigned
171 /// register or registers are. (Individual values are never synthesized
172 /// from more than one type of register.)
174 /// With virtual registers, the contents of RegVTs is redundant with TLI's
175 /// getRegisterType member function, however when with physical registers
176 /// it is necessary to have a separate record of the types.
178 SmallVector<EVT, 4> RegVTs;
180 /// Regs - This list holds the registers assigned to the values.
181 /// Each legal or promoted value requires one register, and each
182 /// expanded value requires multiple registers.
184 SmallVector<unsigned, 4> Regs;
186 RegsForValue() : TLI(0) {}
188 RegsForValue(const TargetLowering &tli,
189 const SmallVector<unsigned, 4> ®s,
190 EVT regvt, EVT valuevt)
191 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
192 RegsForValue(const TargetLowering &tli,
193 const SmallVector<unsigned, 4> ®s,
194 const SmallVector<EVT, 4> ®vts,
195 const SmallVector<EVT, 4> &valuevts)
196 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
197 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
198 unsigned Reg, const Type *Ty) : TLI(&tli) {
199 ComputeValueVTs(tli, Ty, ValueVTs);
201 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
202 EVT ValueVT = ValueVTs[Value];
203 unsigned NumRegs = TLI->getNumRegisters(Context, ValueVT);
204 EVT RegisterVT = TLI->getRegisterType(Context, ValueVT);
205 for (unsigned i = 0; i != NumRegs; ++i)
206 Regs.push_back(Reg + i);
207 RegVTs.push_back(RegisterVT);
212 /// append - Add the specified values to this one.
213 void append(const RegsForValue &RHS) {
215 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
216 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
217 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
221 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
222 /// this value and returns the result as a ValueVTs value. This uses
223 /// Chain/Flag as the input and updates them for the output Chain/Flag.
224 /// If the Flag pointer is NULL, no flag is used.
225 SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
226 SDValue &Chain, SDValue *Flag) const;
228 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
229 /// specified value into the registers specified by this object. This uses
230 /// Chain/Flag as the input and updates them for the output Chain/Flag.
231 /// If the Flag pointer is NULL, no flag is used.
232 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
233 SDValue &Chain, SDValue *Flag) const;
235 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
236 /// operand list. This adds the code marker, matching input operand index
237 /// (if applicable), and includes the number of values added into it.
238 void AddInlineAsmOperands(unsigned Code,
239 bool HasMatching, unsigned MatchingIdx,
240 SelectionDAG &DAG, std::vector<SDValue> &Ops) const;
244 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
245 /// PHI nodes or outside of the basic block that defines it, or used by a
246 /// switch or atomic instruction, which may expand to multiple basic blocks.
247 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
248 if (isa<PHINode>(I)) return true;
249 BasicBlock *BB = I->getParent();
250 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
251 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI))
256 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
257 /// entry block, return true. This includes arguments used by switches, since
258 /// the switch may expand into multiple basic blocks.
259 static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
260 // With FastISel active, we may be splitting blocks, so force creation
261 // of virtual registers for all non-dead arguments.
262 // Don't force virtual registers for byval arguments though, because
263 // fast-isel can't handle those in all cases.
264 if (EnableFastISel && !A->hasByValAttr())
265 return A->use_empty();
267 BasicBlock *Entry = A->getParent()->begin();
268 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
269 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
270 return false; // Use not in entry block.
274 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
278 void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
280 bool EnableFastISel) {
283 RegInfo = &MF->getRegInfo();
285 // Create a vreg for each argument register that is not dead and is used
286 // outside of the entry block for the function.
287 for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
289 if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
290 InitializeRegForValue(AI);
292 // Initialize the mapping of values to registers. This is only set up for
293 // instruction values that are used outside of the block that defines
295 Function::iterator BB = Fn->begin(), EB = Fn->end();
296 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
297 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
298 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
299 const Type *Ty = AI->getAllocatedType();
300 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
302 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
305 TySize *= CUI->getZExtValue(); // Get total allocated size.
306 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
307 StaticAllocaMap[AI] =
308 MF->getFrameInfo()->CreateStackObject(TySize, Align, false);
311 for (; BB != EB; ++BB)
312 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
313 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
314 if (!isa<AllocaInst>(I) ||
315 !StaticAllocaMap.count(cast<AllocaInst>(I)))
316 InitializeRegForValue(I);
318 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
319 // also creates the initial PHI MachineInstrs, though none of the input
320 // operands are populated.
321 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
322 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
326 // Transfer the address-taken flag. This is necessary because there could
327 // be multiple MachineBasicBlocks corresponding to one BasicBlock, and only
328 // the first one should be marked.
329 if (BB->hasAddressTaken())
330 MBB->setHasAddressTaken();
332 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
336 for (BasicBlock::iterator
337 I = BB->begin(), E = BB->end(); I != E; ++I) {
339 PN = dyn_cast<PHINode>(I);
340 if (!PN || PN->use_empty()) continue;
342 unsigned PHIReg = ValueMap[PN];
343 assert(PHIReg && "PHI node does not have an assigned virtual register!");
345 SmallVector<EVT, 4> ValueVTs;
346 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
347 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
348 EVT VT = ValueVTs[vti];
349 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
350 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
351 for (unsigned i = 0; i != NumRegisters; ++i)
352 BuildMI(MBB, DL, TII->get(TargetInstrInfo::PHI), PHIReg + i);
353 PHIReg += NumRegisters;
359 unsigned FunctionLoweringInfo::MakeReg(EVT VT) {
360 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
363 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
364 /// the correctly promoted or expanded types. Assign these registers
365 /// consecutive vreg numbers and return the first assigned number.
367 /// In the case that the given value has struct or array type, this function
368 /// will assign registers for each member or element.
370 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
371 SmallVector<EVT, 4> ValueVTs;
372 ComputeValueVTs(TLI, V->getType(), ValueVTs);
374 unsigned FirstReg = 0;
375 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
376 EVT ValueVT = ValueVTs[Value];
377 EVT RegisterVT = TLI.getRegisterType(V->getContext(), ValueVT);
379 unsigned NumRegs = TLI.getNumRegisters(V->getContext(), ValueVT);
380 for (unsigned i = 0; i != NumRegs; ++i) {
381 unsigned R = MakeReg(RegisterVT);
382 if (!FirstReg) FirstReg = R;
388 /// getCopyFromParts - Create a value that contains the specified legal parts
389 /// combined into the value they represent. If the parts combine to a type
390 /// larger then ValueVT then AssertOp can be used to specify whether the extra
391 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
392 /// (ISD::AssertSext).
393 static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
394 const SDValue *Parts,
395 unsigned NumParts, EVT PartVT, EVT ValueVT,
396 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
397 assert(NumParts > 0 && "No parts to assemble!");
398 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
399 SDValue Val = Parts[0];
402 // Assemble the value from multiple parts.
403 if (!ValueVT.isVector() && ValueVT.isInteger()) {
404 unsigned PartBits = PartVT.getSizeInBits();
405 unsigned ValueBits = ValueVT.getSizeInBits();
407 // Assemble the power of 2 part.
408 unsigned RoundParts = NumParts & (NumParts - 1) ?
409 1 << Log2_32(NumParts) : NumParts;
410 unsigned RoundBits = PartBits * RoundParts;
411 EVT RoundVT = RoundBits == ValueBits ?
412 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
415 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
417 if (RoundParts > 2) {
418 Lo = getCopyFromParts(DAG, dl, Parts, RoundParts/2, PartVT, HalfVT);
419 Hi = getCopyFromParts(DAG, dl, Parts+RoundParts/2, RoundParts/2,
422 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
423 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
425 if (TLI.isBigEndian())
427 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
429 if (RoundParts < NumParts) {
430 // Assemble the trailing non-power-of-2 part.
431 unsigned OddParts = NumParts - RoundParts;
432 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
433 Hi = getCopyFromParts(DAG, dl,
434 Parts+RoundParts, OddParts, PartVT, OddVT);
436 // Combine the round and odd parts.
438 if (TLI.isBigEndian())
440 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
441 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
442 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
443 DAG.getConstant(Lo.getValueType().getSizeInBits(),
444 TLI.getPointerTy()));
445 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
446 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
448 } else if (ValueVT.isVector()) {
449 // Handle a multi-element vector.
450 EVT IntermediateVT, RegisterVT;
451 unsigned NumIntermediates;
453 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
454 NumIntermediates, RegisterVT);
455 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
456 NumParts = NumRegs; // Silence a compiler warning.
457 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
458 assert(RegisterVT == Parts[0].getValueType() &&
459 "Part type doesn't match part!");
461 // Assemble the parts into intermediate operands.
462 SmallVector<SDValue, 8> Ops(NumIntermediates);
463 if (NumIntermediates == NumParts) {
464 // If the register was not expanded, truncate or copy the value,
466 for (unsigned i = 0; i != NumParts; ++i)
467 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
468 PartVT, IntermediateVT);
469 } else if (NumParts > 0) {
470 // If the intermediate type was expanded, build the intermediate operands
472 assert(NumParts % NumIntermediates == 0 &&
473 "Must expand into a divisible number of parts!");
474 unsigned Factor = NumParts / NumIntermediates;
475 for (unsigned i = 0; i != NumIntermediates; ++i)
476 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
477 PartVT, IntermediateVT);
480 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
482 Val = DAG.getNode(IntermediateVT.isVector() ?
483 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
484 ValueVT, &Ops[0], NumIntermediates);
485 } else if (PartVT.isFloatingPoint()) {
486 // FP split into multiple FP parts (for ppcf128)
487 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
490 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[0]);
491 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[1]);
492 if (TLI.isBigEndian())
494 Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi);
496 // FP split into integer parts (soft fp)
497 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
498 !PartVT.isVector() && "Unexpected split");
499 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
500 Val = getCopyFromParts(DAG, dl, Parts, NumParts, PartVT, IntVT);
504 // There is now one part, held in Val. Correct it to match ValueVT.
505 PartVT = Val.getValueType();
507 if (PartVT == ValueVT)
510 if (PartVT.isVector()) {
511 assert(ValueVT.isVector() && "Unknown vector conversion!");
512 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
515 if (ValueVT.isVector()) {
516 assert(ValueVT.getVectorElementType() == PartVT &&
517 ValueVT.getVectorNumElements() == 1 &&
518 "Only trivial scalar-to-vector conversions should get here!");
519 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
522 if (PartVT.isInteger() &&
523 ValueVT.isInteger()) {
524 if (ValueVT.bitsLT(PartVT)) {
525 // For a truncate, see if we have any information to
526 // indicate whether the truncated bits will always be
527 // zero or sign-extension.
528 if (AssertOp != ISD::DELETED_NODE)
529 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
530 DAG.getValueType(ValueVT));
531 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
533 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
537 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
538 if (ValueVT.bitsLT(Val.getValueType()))
539 // FP_ROUND's are always exact here.
540 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
541 DAG.getIntPtrConstant(1));
542 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
545 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
546 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
548 llvm_unreachable("Unknown mismatch!");
552 /// getCopyToParts - Create a series of nodes that contain the specified value
553 /// split into legal parts. If the parts contain more bits than Val, then, for
554 /// integers, ExtendKind can be used to specify how to generate the extra bits.
555 static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, SDValue Val,
556 SDValue *Parts, unsigned NumParts, EVT PartVT,
557 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
558 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
559 EVT PtrVT = TLI.getPointerTy();
560 EVT ValueVT = Val.getValueType();
561 unsigned PartBits = PartVT.getSizeInBits();
562 unsigned OrigNumParts = NumParts;
563 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
568 if (!ValueVT.isVector()) {
569 if (PartVT == ValueVT) {
570 assert(NumParts == 1 && "No-op copy with multiple parts!");
575 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
576 // If the parts cover more bits than the value has, promote the value.
577 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
578 assert(NumParts == 1 && "Do not know what to promote to!");
579 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
580 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
581 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
582 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
584 llvm_unreachable("Unknown mismatch!");
586 } else if (PartBits == ValueVT.getSizeInBits()) {
587 // Different types of the same size.
588 assert(NumParts == 1 && PartVT != ValueVT);
589 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
590 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
591 // If the parts cover less bits than value has, truncate the value.
592 if (PartVT.isInteger() && ValueVT.isInteger()) {
593 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
594 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
596 llvm_unreachable("Unknown mismatch!");
600 // The value may have changed - recompute ValueVT.
601 ValueVT = Val.getValueType();
602 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
603 "Failed to tile the value with PartVT!");
606 assert(PartVT == ValueVT && "Type conversion failed!");
611 // Expand the value into multiple parts.
612 if (NumParts & (NumParts - 1)) {
613 // The number of parts is not a power of 2. Split off and copy the tail.
614 assert(PartVT.isInteger() && ValueVT.isInteger() &&
615 "Do not know what to expand to!");
616 unsigned RoundParts = 1 << Log2_32(NumParts);
617 unsigned RoundBits = RoundParts * PartBits;
618 unsigned OddParts = NumParts - RoundParts;
619 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
620 DAG.getConstant(RoundBits,
621 TLI.getPointerTy()));
622 getCopyToParts(DAG, dl, OddVal, Parts + RoundParts, OddParts, PartVT);
623 if (TLI.isBigEndian())
624 // The odd parts were reversed by getCopyToParts - unreverse them.
625 std::reverse(Parts + RoundParts, Parts + NumParts);
626 NumParts = RoundParts;
627 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
628 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
631 // The number of parts is a power of 2. Repeatedly bisect the value using
633 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
634 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()),
636 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
637 for (unsigned i = 0; i < NumParts; i += StepSize) {
638 unsigned ThisBits = StepSize * PartBits / 2;
639 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
640 SDValue &Part0 = Parts[i];
641 SDValue &Part1 = Parts[i+StepSize/2];
643 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
645 DAG.getConstant(1, PtrVT));
646 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
648 DAG.getConstant(0, PtrVT));
650 if (ThisBits == PartBits && ThisVT != PartVT) {
651 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
653 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
659 if (TLI.isBigEndian())
660 std::reverse(Parts, Parts + OrigNumParts);
667 if (PartVT != ValueVT) {
668 if (PartVT.isVector()) {
669 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
671 assert(ValueVT.getVectorElementType() == PartVT &&
672 ValueVT.getVectorNumElements() == 1 &&
673 "Only trivial vector-to-scalar conversions should get here!");
674 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
676 DAG.getConstant(0, PtrVT));
684 // Handle a multi-element vector.
685 EVT IntermediateVT, RegisterVT;
686 unsigned NumIntermediates;
687 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
688 IntermediateVT, NumIntermediates, RegisterVT);
689 unsigned NumElements = ValueVT.getVectorNumElements();
691 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
692 NumParts = NumRegs; // Silence a compiler warning.
693 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
695 // Split the vector into intermediate operands.
696 SmallVector<SDValue, 8> Ops(NumIntermediates);
697 for (unsigned i = 0; i != NumIntermediates; ++i)
698 if (IntermediateVT.isVector())
699 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
701 DAG.getConstant(i * (NumElements / NumIntermediates),
704 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
706 DAG.getConstant(i, PtrVT));
708 // Split the intermediate operands into legal parts.
709 if (NumParts == NumIntermediates) {
710 // If the register was not expanded, promote or copy the value,
712 for (unsigned i = 0; i != NumParts; ++i)
713 getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
714 } else if (NumParts > 0) {
715 // If the intermediate type was expanded, split each the value into
717 assert(NumParts % NumIntermediates == 0 &&
718 "Must expand into a divisible number of parts!");
719 unsigned Factor = NumParts / NumIntermediates;
720 for (unsigned i = 0; i != NumIntermediates; ++i)
721 getCopyToParts(DAG, dl, Ops[i], &Parts[i * Factor], Factor, PartVT);
726 void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
729 TD = DAG.getTarget().getTargetData();
732 /// clear - Clear out the curret SelectionDAG and the associated
733 /// state and prepare this SelectionDAGLowering object to be used
734 /// for a new block. This doesn't clear out information about
735 /// additional blocks that are needed to complete switch lowering
736 /// or PHI node updating; that information is cleared out as it is
738 void SelectionDAGLowering::clear() {
740 PendingLoads.clear();
741 PendingExports.clear();
744 CurDebugLoc = DebugLoc::getUnknownLoc();
748 /// getRoot - Return the current virtual root of the Selection DAG,
749 /// flushing any PendingLoad items. This must be done before emitting
750 /// a store or any other node that may need to be ordered after any
751 /// prior load instructions.
753 SDValue SelectionDAGLowering::getRoot() {
754 if (PendingLoads.empty())
755 return DAG.getRoot();
757 if (PendingLoads.size() == 1) {
758 SDValue Root = PendingLoads[0];
760 PendingLoads.clear();
764 // Otherwise, we have to make a token factor node.
765 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
766 &PendingLoads[0], PendingLoads.size());
767 PendingLoads.clear();
772 /// getControlRoot - Similar to getRoot, but instead of flushing all the
773 /// PendingLoad items, flush all the PendingExports items. It is necessary
774 /// to do this before emitting a terminator instruction.
776 SDValue SelectionDAGLowering::getControlRoot() {
777 SDValue Root = DAG.getRoot();
779 if (PendingExports.empty())
782 // Turn all of the CopyToReg chains into one factored node.
783 if (Root.getOpcode() != ISD::EntryToken) {
784 unsigned i = 0, e = PendingExports.size();
785 for (; i != e; ++i) {
786 assert(PendingExports[i].getNode()->getNumOperands() > 1);
787 if (PendingExports[i].getNode()->getOperand(0) == Root)
788 break; // Don't add the root if we already indirectly depend on it.
792 PendingExports.push_back(Root);
795 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
797 PendingExports.size());
798 PendingExports.clear();
803 void SelectionDAGLowering::visit(Instruction &I) {
804 visit(I.getOpcode(), I);
807 void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
808 // Note: this doesn't use InstVisitor, because it has to work with
809 // ConstantExpr's in addition to instructions.
811 default: llvm_unreachable("Unknown instruction type encountered!");
812 // Build the switch statement using the Instruction.def file.
813 #define HANDLE_INST(NUM, OPCODE, CLASS) \
814 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
815 #include "llvm/Instruction.def"
819 SDValue SelectionDAGLowering::getValue(const Value *V) {
820 SDValue &N = NodeMap[V];
821 if (N.getNode()) return N;
823 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
824 EVT VT = TLI.getValueType(V->getType(), true);
826 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
827 return N = DAG.getConstant(*CI, VT);
829 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
830 return N = DAG.getGlobalAddress(GV, VT);
832 if (isa<ConstantPointerNull>(C))
833 return N = DAG.getConstant(0, TLI.getPointerTy());
835 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
836 return N = DAG.getConstantFP(*CFP, VT);
838 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
839 return N = DAG.getUNDEF(VT);
841 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
842 visit(CE->getOpcode(), *CE);
843 SDValue N1 = NodeMap[V];
844 assert(N1.getNode() && "visit didn't populate the ValueMap!");
848 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
849 SmallVector<SDValue, 4> Constants;
850 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
852 SDNode *Val = getValue(*OI).getNode();
853 // If the operand is an empty aggregate, there are no values.
855 // Add each leaf value from the operand to the Constants list
856 // to form a flattened list of all the values.
857 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
858 Constants.push_back(SDValue(Val, i));
860 return DAG.getMergeValues(&Constants[0], Constants.size(),
864 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
865 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
866 "Unknown struct or array constant!");
868 SmallVector<EVT, 4> ValueVTs;
869 ComputeValueVTs(TLI, C->getType(), ValueVTs);
870 unsigned NumElts = ValueVTs.size();
872 return SDValue(); // empty struct
873 SmallVector<SDValue, 4> Constants(NumElts);
874 for (unsigned i = 0; i != NumElts; ++i) {
875 EVT EltVT = ValueVTs[i];
876 if (isa<UndefValue>(C))
877 Constants[i] = DAG.getUNDEF(EltVT);
878 else if (EltVT.isFloatingPoint())
879 Constants[i] = DAG.getConstantFP(0, EltVT);
881 Constants[i] = DAG.getConstant(0, EltVT);
883 return DAG.getMergeValues(&Constants[0], NumElts, getCurDebugLoc());
886 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
887 return DAG.getBlockAddress(BA, getCurDebugLoc());
889 const VectorType *VecTy = cast<VectorType>(V->getType());
890 unsigned NumElements = VecTy->getNumElements();
892 // Now that we know the number and type of the elements, get that number of
893 // elements into the Ops array based on what kind of constant it is.
894 SmallVector<SDValue, 16> Ops;
895 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
896 for (unsigned i = 0; i != NumElements; ++i)
897 Ops.push_back(getValue(CP->getOperand(i)));
899 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
900 EVT EltVT = TLI.getValueType(VecTy->getElementType());
903 if (EltVT.isFloatingPoint())
904 Op = DAG.getConstantFP(0, EltVT);
906 Op = DAG.getConstant(0, EltVT);
907 Ops.assign(NumElements, Op);
910 // Create a BUILD_VECTOR node.
911 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
912 VT, &Ops[0], Ops.size());
915 // If this is a static alloca, generate it as the frameindex instead of
917 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
918 DenseMap<const AllocaInst*, int>::iterator SI =
919 FuncInfo.StaticAllocaMap.find(AI);
920 if (SI != FuncInfo.StaticAllocaMap.end())
921 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
924 unsigned InReg = FuncInfo.ValueMap[V];
925 assert(InReg && "Value not in map!");
927 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
928 SDValue Chain = DAG.getEntryNode();
929 return RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL);
932 /// Get the EVTs and ArgFlags collections that represent the return type
933 /// of the given function. This does not require a DAG or a return value, and
934 /// is suitable for use before any DAGs for the function are constructed.
935 static void getReturnInfo(const Type* ReturnType,
936 Attributes attr, SmallVectorImpl<EVT> &OutVTs,
937 SmallVectorImpl<ISD::ArgFlagsTy> &OutFlags,
939 SmallVectorImpl<uint64_t> *Offsets = 0) {
940 SmallVector<EVT, 4> ValueVTs;
941 ComputeValueVTs(TLI, ReturnType, ValueVTs, Offsets);
942 unsigned NumValues = ValueVTs.size();
943 if ( NumValues == 0 ) return;
945 for (unsigned j = 0, f = NumValues; j != f; ++j) {
946 EVT VT = ValueVTs[j];
947 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
949 if (attr & Attribute::SExt)
950 ExtendKind = ISD::SIGN_EXTEND;
951 else if (attr & Attribute::ZExt)
952 ExtendKind = ISD::ZERO_EXTEND;
954 // FIXME: C calling convention requires the return type to be promoted to
955 // at least 32-bit. But this is not necessary for non-C calling
956 // conventions. The frontend should mark functions whose return values
957 // require promoting with signext or zeroext attributes.
958 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
959 EVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
960 if (VT.bitsLT(MinVT))
964 unsigned NumParts = TLI.getNumRegisters(ReturnType->getContext(), VT);
965 EVT PartVT = TLI.getRegisterType(ReturnType->getContext(), VT);
966 // 'inreg' on function refers to return value
967 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
968 if (attr & Attribute::InReg)
971 // Propagate extension type if any
972 if (attr & Attribute::SExt)
974 else if (attr & Attribute::ZExt)
977 for (unsigned i = 0; i < NumParts; ++i) {
978 OutVTs.push_back(PartVT);
979 OutFlags.push_back(Flags);
984 void SelectionDAGLowering::visitRet(ReturnInst &I) {
985 SDValue Chain = getControlRoot();
986 SmallVector<ISD::OutputArg, 8> Outs;
987 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
989 if (!FLI.CanLowerReturn) {
990 unsigned DemoteReg = FLI.DemoteRegister;
991 const Function *F = I.getParent()->getParent();
993 // Emit a store of the return value through the virtual register.
994 // Leave Outs empty so that LowerReturn won't try to load return
995 // registers the usual way.
996 SmallVector<EVT, 1> PtrValueVTs;
997 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
1000 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1001 SDValue RetOp = getValue(I.getOperand(0));
1003 SmallVector<EVT, 4> ValueVTs;
1004 SmallVector<uint64_t, 4> Offsets;
1005 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1006 unsigned NumValues = ValueVTs.size();
1008 SmallVector<SDValue, 4> Chains(NumValues);
1009 EVT PtrVT = PtrValueVTs[0];
1010 for (unsigned i = 0; i != NumValues; ++i)
1011 Chains[i] = DAG.getStore(Chain, getCurDebugLoc(),
1012 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1013 DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, RetPtr,
1014 DAG.getConstant(Offsets[i], PtrVT)),
1015 NULL, Offsets[i], false, 0);
1016 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
1017 MVT::Other, &Chains[0], NumValues);
1020 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1021 SmallVector<EVT, 4> ValueVTs;
1022 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
1023 unsigned NumValues = ValueVTs.size();
1024 if (NumValues == 0) continue;
1026 SDValue RetOp = getValue(I.getOperand(i));
1027 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1028 EVT VT = ValueVTs[j];
1030 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1032 const Function *F = I.getParent()->getParent();
1033 if (F->paramHasAttr(0, Attribute::SExt))
1034 ExtendKind = ISD::SIGN_EXTEND;
1035 else if (F->paramHasAttr(0, Attribute::ZExt))
1036 ExtendKind = ISD::ZERO_EXTEND;
1038 // FIXME: C calling convention requires the return type to be promoted to
1039 // at least 32-bit. But this is not necessary for non-C calling
1040 // conventions. The frontend should mark functions whose return values
1041 // require promoting with signext or zeroext attributes.
1042 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
1043 EVT MinVT = TLI.getRegisterType(*DAG.getContext(), MVT::i32);
1044 if (VT.bitsLT(MinVT))
1048 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
1049 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
1050 SmallVector<SDValue, 4> Parts(NumParts);
1051 getCopyToParts(DAG, getCurDebugLoc(),
1052 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1053 &Parts[0], NumParts, PartVT, ExtendKind);
1055 // 'inreg' on function refers to return value
1056 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1057 if (F->paramHasAttr(0, Attribute::InReg))
1060 // Propagate extension type if any
1061 if (F->paramHasAttr(0, Attribute::SExt))
1063 else if (F->paramHasAttr(0, Attribute::ZExt))
1066 for (unsigned i = 0; i < NumParts; ++i)
1067 Outs.push_back(ISD::OutputArg(Flags, Parts[i], /*isfixed=*/true));
1072 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1073 CallingConv::ID CallConv =
1074 DAG.getMachineFunction().getFunction()->getCallingConv();
1075 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
1076 Outs, getCurDebugLoc(), DAG);
1078 // Verify that the target's LowerReturn behaved as expected.
1079 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1080 "LowerReturn didn't return a valid chain!");
1082 // Update the DAG with the new chain value resulting from return lowering.
1086 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1087 /// created for it, emit nodes to copy the value into the virtual
1089 void SelectionDAGLowering::CopyToExportRegsIfNeeded(Value *V) {
1090 if (!V->use_empty()) {
1091 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1092 if (VMI != FuncInfo.ValueMap.end())
1093 CopyValueToVirtualRegister(V, VMI->second);
1097 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1098 /// the current basic block, add it to ValueMap now so that we'll get a
1100 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1101 // No need to export constants.
1102 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1104 // Already exported?
1105 if (FuncInfo.isExportedInst(V)) return;
1107 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1108 CopyValueToVirtualRegister(V, Reg);
1111 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1112 const BasicBlock *FromBB) {
1113 // The operands of the setcc have to be in this block. We don't know
1114 // how to export them from some other block.
1115 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1116 // Can export from current BB.
1117 if (VI->getParent() == FromBB)
1120 // Is already exported, noop.
1121 return FuncInfo.isExportedInst(V);
1124 // If this is an argument, we can export it if the BB is the entry block or
1125 // if it is already exported.
1126 if (isa<Argument>(V)) {
1127 if (FromBB == &FromBB->getParent()->getEntryBlock())
1130 // Otherwise, can only export this if it is already exported.
1131 return FuncInfo.isExportedInst(V);
1134 // Otherwise, constants can always be exported.
1138 static bool InBlock(const Value *V, const BasicBlock *BB) {
1139 if (const Instruction *I = dyn_cast<Instruction>(V))
1140 return I->getParent() == BB;
1144 /// getFCmpCondCode - Return the ISD condition code corresponding to
1145 /// the given LLVM IR floating-point condition code. This includes
1146 /// consideration of global floating-point math flags.
1148 static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1149 ISD::CondCode FPC, FOC;
1151 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1152 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1153 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1154 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1155 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1156 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1157 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1158 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1159 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1160 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1161 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1162 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1163 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1164 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1165 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1166 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1168 llvm_unreachable("Invalid FCmp predicate opcode!");
1169 FOC = FPC = ISD::SETFALSE;
1172 if (FiniteOnlyFPMath())
1178 /// getICmpCondCode - Return the ISD condition code corresponding to
1179 /// the given LLVM IR integer condition code.
1181 static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1183 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1184 case ICmpInst::ICMP_NE: return ISD::SETNE;
1185 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1186 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1187 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1188 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1189 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1190 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1191 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1192 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1194 llvm_unreachable("Invalid ICmp predicate opcode!");
1199 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1200 /// This function emits a branch and is used at the leaves of an OR or an
1201 /// AND operator tree.
1204 SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1205 MachineBasicBlock *TBB,
1206 MachineBasicBlock *FBB,
1207 MachineBasicBlock *CurBB) {
1208 const BasicBlock *BB = CurBB->getBasicBlock();
1210 // If the leaf of the tree is a comparison, merge the condition into
1212 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1213 // The operands of the cmp have to be in this block. We don't know
1214 // how to export them from some other block. If this is the first block
1215 // of the sequence, no exporting is needed.
1216 if (CurBB == CurMBB ||
1217 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1218 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1219 ISD::CondCode Condition;
1220 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1221 Condition = getICmpCondCode(IC->getPredicate());
1222 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1223 Condition = getFCmpCondCode(FC->getPredicate());
1225 Condition = ISD::SETEQ; // silence warning.
1226 llvm_unreachable("Unknown compare instruction");
1229 CaseBlock CB(Condition, BOp->getOperand(0),
1230 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1231 SwitchCases.push_back(CB);
1236 // Create a CaseBlock record representing this branch.
1237 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1238 NULL, TBB, FBB, CurBB);
1239 SwitchCases.push_back(CB);
1242 /// FindMergedConditions - If Cond is an expression like
1243 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1244 MachineBasicBlock *TBB,
1245 MachineBasicBlock *FBB,
1246 MachineBasicBlock *CurBB,
1248 // If this node is not part of the or/and tree, emit it as a branch.
1249 Instruction *BOp = dyn_cast<Instruction>(Cond);
1250 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1251 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1252 BOp->getParent() != CurBB->getBasicBlock() ||
1253 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1254 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1255 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
1259 // Create TmpBB after CurBB.
1260 MachineFunction::iterator BBI = CurBB;
1261 MachineFunction &MF = DAG.getMachineFunction();
1262 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1263 CurBB->getParent()->insert(++BBI, TmpBB);
1265 if (Opc == Instruction::Or) {
1266 // Codegen X | Y as:
1274 // Emit the LHS condition.
1275 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1277 // Emit the RHS condition into TmpBB.
1278 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1280 assert(Opc == Instruction::And && "Unknown merge op!");
1281 // Codegen X & Y as:
1288 // This requires creation of TmpBB after CurBB.
1290 // Emit the LHS condition.
1291 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1293 // Emit the RHS condition into TmpBB.
1294 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1298 /// If the set of cases should be emitted as a series of branches, return true.
1299 /// If we should emit this as a bunch of and/or'd together conditions, return
1302 SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1303 if (Cases.size() != 2) return true;
1305 // If this is two comparisons of the same values or'd or and'd together, they
1306 // will get folded into a single comparison, so don't emit two blocks.
1307 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1308 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1309 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1310 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1317 void SelectionDAGLowering::visitBr(BranchInst &I) {
1318 // Update machine-CFG edges.
1319 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1321 // Figure out which block is immediately after the current one.
1322 MachineBasicBlock *NextBlock = 0;
1323 MachineFunction::iterator BBI = CurMBB;
1324 if (++BBI != FuncInfo.MF->end())
1327 if (I.isUnconditional()) {
1328 // Update machine-CFG edges.
1329 CurMBB->addSuccessor(Succ0MBB);
1331 // If this is not a fall-through branch, emit the branch.
1332 if (Succ0MBB != NextBlock)
1333 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1334 MVT::Other, getControlRoot(),
1335 DAG.getBasicBlock(Succ0MBB)));
1339 // If this condition is one of the special cases we handle, do special stuff
1341 Value *CondVal = I.getCondition();
1342 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1344 // If this is a series of conditions that are or'd or and'd together, emit
1345 // this as a sequence of branches instead of setcc's with and/or operations.
1346 // For example, instead of something like:
1359 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1360 if (BOp->hasOneUse() &&
1361 (BOp->getOpcode() == Instruction::And ||
1362 BOp->getOpcode() == Instruction::Or)) {
1363 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1364 // If the compares in later blocks need to use values not currently
1365 // exported from this block, export them now. This block should always
1366 // be the first entry.
1367 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1369 // Allow some cases to be rejected.
1370 if (ShouldEmitAsBranches(SwitchCases)) {
1371 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1372 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1373 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1376 // Emit the branch for this block.
1377 visitSwitchCase(SwitchCases[0]);
1378 SwitchCases.erase(SwitchCases.begin());
1382 // Okay, we decided not to do this, remove any inserted MBB's and clear
1384 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1385 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1387 SwitchCases.clear();
1391 // Create a CaseBlock record representing this branch.
1392 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1393 NULL, Succ0MBB, Succ1MBB, CurMBB);
1394 // Use visitSwitchCase to actually insert the fast branch sequence for this
1396 visitSwitchCase(CB);
1399 /// visitSwitchCase - Emits the necessary code to represent a single node in
1400 /// the binary search tree resulting from lowering a switch instruction.
1401 void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1403 SDValue CondLHS = getValue(CB.CmpLHS);
1404 DebugLoc dl = getCurDebugLoc();
1406 // Build the setcc now.
1407 if (CB.CmpMHS == NULL) {
1408 // Fold "(X == true)" to X and "(X == false)" to !X to
1409 // handle common cases produced by branch lowering.
1410 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1411 CB.CC == ISD::SETEQ)
1413 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1414 CB.CC == ISD::SETEQ) {
1415 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1416 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1418 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1420 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1422 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1423 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1425 SDValue CmpOp = getValue(CB.CmpMHS);
1426 EVT VT = CmpOp.getValueType();
1428 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1429 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1432 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1433 VT, CmpOp, DAG.getConstant(Low, VT));
1434 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1435 DAG.getConstant(High-Low, VT), ISD::SETULE);
1439 // Update successor info
1440 CurMBB->addSuccessor(CB.TrueBB);
1441 CurMBB->addSuccessor(CB.FalseBB);
1443 // Set NextBlock to be the MBB immediately after the current one, if any.
1444 // This is used to avoid emitting unnecessary branches to the next block.
1445 MachineBasicBlock *NextBlock = 0;
1446 MachineFunction::iterator BBI = CurMBB;
1447 if (++BBI != FuncInfo.MF->end())
1450 // If the lhs block is the next block, invert the condition so that we can
1451 // fall through to the lhs instead of the rhs block.
1452 if (CB.TrueBB == NextBlock) {
1453 std::swap(CB.TrueBB, CB.FalseBB);
1454 SDValue True = DAG.getConstant(1, Cond.getValueType());
1455 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1457 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1458 MVT::Other, getControlRoot(), Cond,
1459 DAG.getBasicBlock(CB.TrueBB));
1461 // If the branch was constant folded, fix up the CFG.
1462 if (BrCond.getOpcode() == ISD::BR) {
1463 CurMBB->removeSuccessor(CB.FalseBB);
1464 DAG.setRoot(BrCond);
1466 // Otherwise, go ahead and insert the false branch.
1467 if (BrCond == getControlRoot())
1468 CurMBB->removeSuccessor(CB.TrueBB);
1470 if (CB.FalseBB == NextBlock)
1471 DAG.setRoot(BrCond);
1473 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1474 DAG.getBasicBlock(CB.FalseBB)));
1478 /// visitJumpTable - Emit JumpTable node in the current MBB
1479 void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1480 // Emit the code for the jump table
1481 assert(JT.Reg != -1U && "Should lower JT Header first!");
1482 EVT PTy = TLI.getPointerTy();
1483 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1485 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1486 DAG.setRoot(DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1487 MVT::Other, Index.getValue(1),
1491 /// visitJumpTableHeader - This function emits necessary code to produce index
1492 /// in the JumpTable from switch case.
1493 void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1494 JumpTableHeader &JTH) {
1495 // Subtract the lowest switch case value from the value being switched on and
1496 // conditional branch to default mbb if the result is greater than the
1497 // difference between smallest and largest cases.
1498 SDValue SwitchOp = getValue(JTH.SValue);
1499 EVT VT = SwitchOp.getValueType();
1500 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1501 DAG.getConstant(JTH.First, VT));
1503 // The SDNode we just created, which holds the value being switched on minus
1504 // the the smallest case value, needs to be copied to a virtual register so it
1505 // can be used as an index into the jump table in a subsequent basic block.
1506 // This value may be smaller or larger than the target's pointer type, and
1507 // therefore require extension or truncating.
1508 SwitchOp = DAG.getZExtOrTrunc(SUB, getCurDebugLoc(), TLI.getPointerTy());
1510 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1511 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1512 JumpTableReg, SwitchOp);
1513 JT.Reg = JumpTableReg;
1515 // Emit the range check for the jump table, and branch to the default block
1516 // for the switch statement if the value being switched on exceeds the largest
1517 // case in the switch.
1518 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1519 TLI.getSetCCResultType(SUB.getValueType()), SUB,
1520 DAG.getConstant(JTH.Last-JTH.First,VT),
1523 // Set NextBlock to be the MBB immediately after the current one, if any.
1524 // This is used to avoid emitting unnecessary branches to the next block.
1525 MachineBasicBlock *NextBlock = 0;
1526 MachineFunction::iterator BBI = CurMBB;
1527 if (++BBI != FuncInfo.MF->end())
1530 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1531 MVT::Other, CopyTo, CMP,
1532 DAG.getBasicBlock(JT.Default));
1534 if (JT.MBB == NextBlock)
1535 DAG.setRoot(BrCond);
1537 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1538 DAG.getBasicBlock(JT.MBB)));
1541 /// visitBitTestHeader - This function emits necessary code to produce value
1542 /// suitable for "bit tests"
1543 void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1544 // Subtract the minimum value
1545 SDValue SwitchOp = getValue(B.SValue);
1546 EVT VT = SwitchOp.getValueType();
1547 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1548 DAG.getConstant(B.First, VT));
1551 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1552 TLI.getSetCCResultType(SUB.getValueType()),
1553 SUB, DAG.getConstant(B.Range, VT),
1556 SDValue ShiftOp = DAG.getZExtOrTrunc(SUB, getCurDebugLoc(), TLI.getPointerTy());
1558 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
1559 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1562 // Set NextBlock to be the MBB immediately after the current one, if any.
1563 // This is used to avoid emitting unnecessary branches to the next block.
1564 MachineBasicBlock *NextBlock = 0;
1565 MachineFunction::iterator BBI = CurMBB;
1566 if (++BBI != FuncInfo.MF->end())
1569 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1571 CurMBB->addSuccessor(B.Default);
1572 CurMBB->addSuccessor(MBB);
1574 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1575 MVT::Other, CopyTo, RangeCmp,
1576 DAG.getBasicBlock(B.Default));
1578 if (MBB == NextBlock)
1579 DAG.setRoot(BrRange);
1581 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1582 DAG.getBasicBlock(MBB)));
1585 /// visitBitTestCase - this function produces one "bit test"
1586 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1589 // Make desired shift
1590 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
1591 TLI.getPointerTy());
1592 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
1594 DAG.getConstant(1, TLI.getPointerTy()),
1597 // Emit bit tests and jumps
1598 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
1599 TLI.getPointerTy(), SwitchVal,
1600 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1601 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1602 TLI.getSetCCResultType(AndOp.getValueType()),
1603 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
1606 CurMBB->addSuccessor(B.TargetBB);
1607 CurMBB->addSuccessor(NextMBB);
1609 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1610 MVT::Other, getControlRoot(),
1611 AndCmp, DAG.getBasicBlock(B.TargetBB));
1613 // Set NextBlock to be the MBB immediately after the current one, if any.
1614 // This is used to avoid emitting unnecessary branches to the next block.
1615 MachineBasicBlock *NextBlock = 0;
1616 MachineFunction::iterator BBI = CurMBB;
1617 if (++BBI != FuncInfo.MF->end())
1620 if (NextMBB == NextBlock)
1623 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1624 DAG.getBasicBlock(NextMBB)));
1627 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1628 // Retrieve successors.
1629 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1630 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1632 const Value *Callee(I.getCalledValue());
1633 if (isa<InlineAsm>(Callee))
1636 LowerCallTo(&I, getValue(Callee), false, LandingPad);
1638 // If the value of the invoke is used outside of its defining block, make it
1639 // available as a virtual register.
1640 CopyToExportRegsIfNeeded(&I);
1642 // Update successor info
1643 CurMBB->addSuccessor(Return);
1644 CurMBB->addSuccessor(LandingPad);
1646 // Drop into normal successor.
1647 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1648 MVT::Other, getControlRoot(),
1649 DAG.getBasicBlock(Return)));
1652 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1655 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1656 /// small case ranges).
1657 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1658 CaseRecVector& WorkList,
1660 MachineBasicBlock* Default) {
1661 Case& BackCase = *(CR.Range.second-1);
1663 // Size is the number of Cases represented by this range.
1664 size_t Size = CR.Range.second - CR.Range.first;
1668 // Get the MachineFunction which holds the current MBB. This is used when
1669 // inserting any additional MBBs necessary to represent the switch.
1670 MachineFunction *CurMF = FuncInfo.MF;
1672 // Figure out which block is immediately after the current one.
1673 MachineBasicBlock *NextBlock = 0;
1674 MachineFunction::iterator BBI = CR.CaseBB;
1676 if (++BBI != FuncInfo.MF->end())
1679 // TODO: If any two of the cases has the same destination, and if one value
1680 // is the same as the other, but has one bit unset that the other has set,
1681 // use bit manipulation to do two compares at once. For example:
1682 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1684 // Rearrange the case blocks so that the last one falls through if possible.
1685 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1686 // The last case block won't fall through into 'NextBlock' if we emit the
1687 // branches in this order. See if rearranging a case value would help.
1688 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1689 if (I->BB == NextBlock) {
1690 std::swap(*I, BackCase);
1696 // Create a CaseBlock record representing a conditional branch to
1697 // the Case's target mbb if the value being switched on SV is equal
1699 MachineBasicBlock *CurBlock = CR.CaseBB;
1700 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1701 MachineBasicBlock *FallThrough;
1703 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1704 CurMF->insert(BBI, FallThrough);
1706 // Put SV in a virtual register to make it available from the new blocks.
1707 ExportFromCurrentBlock(SV);
1709 // If the last case doesn't match, go to the default block.
1710 FallThrough = Default;
1713 Value *RHS, *LHS, *MHS;
1715 if (I->High == I->Low) {
1716 // This is just small small case range :) containing exactly 1 case
1718 LHS = SV; RHS = I->High; MHS = NULL;
1721 LHS = I->Low; MHS = SV; RHS = I->High;
1723 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1725 // If emitting the first comparison, just call visitSwitchCase to emit the
1726 // code into the current block. Otherwise, push the CaseBlock onto the
1727 // vector to be later processed by SDISel, and insert the node's MBB
1728 // before the next MBB.
1729 if (CurBlock == CurMBB)
1730 visitSwitchCase(CB);
1732 SwitchCases.push_back(CB);
1734 CurBlock = FallThrough;
1740 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1741 return !DisableJumpTables &&
1742 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1743 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1746 static APInt ComputeRange(const APInt &First, const APInt &Last) {
1747 APInt LastExt(Last), FirstExt(First);
1748 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1749 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1750 return (LastExt - FirstExt + 1ULL);
1753 /// handleJTSwitchCase - Emit jumptable for current switch case range
1754 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1755 CaseRecVector& WorkList,
1757 MachineBasicBlock* Default) {
1758 Case& FrontCase = *CR.Range.first;
1759 Case& BackCase = *(CR.Range.second-1);
1761 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1762 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1764 APInt TSize(First.getBitWidth(), 0);
1765 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1769 if (!areJTsAllowed(TLI) || TSize.ult(APInt(First.getBitWidth(), 4)))
1772 APInt Range = ComputeRange(First, Last);
1773 double Density = TSize.roundToDouble() / Range.roundToDouble();
1777 DEBUG(errs() << "Lowering jump table\n"
1778 << "First entry: " << First << ". Last entry: " << Last << '\n'
1779 << "Range: " << Range
1780 << "Size: " << TSize << ". Density: " << Density << "\n\n");
1782 // Get the MachineFunction which holds the current MBB. This is used when
1783 // inserting any additional MBBs necessary to represent the switch.
1784 MachineFunction *CurMF = FuncInfo.MF;
1786 // Figure out which block is immediately after the current one.
1787 MachineFunction::iterator BBI = CR.CaseBB;
1790 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1792 // Create a new basic block to hold the code for loading the address
1793 // of the jump table, and jumping to it. Update successor information;
1794 // we will either branch to the default case for the switch, or the jump
1796 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1797 CurMF->insert(BBI, JumpTableBB);
1798 CR.CaseBB->addSuccessor(Default);
1799 CR.CaseBB->addSuccessor(JumpTableBB);
1801 // Build a vector of destination BBs, corresponding to each target
1802 // of the jump table. If the value of the jump table slot corresponds to
1803 // a case statement, push the case's BB onto the vector, otherwise, push
1805 std::vector<MachineBasicBlock*> DestBBs;
1807 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1808 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1809 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1811 if (Low.sle(TEI) && TEI.sle(High)) {
1812 DestBBs.push_back(I->BB);
1816 DestBBs.push_back(Default);
1820 // Update successor info. Add one edge to each unique successor.
1821 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1822 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1823 E = DestBBs.end(); I != E; ++I) {
1824 if (!SuccsHandled[(*I)->getNumber()]) {
1825 SuccsHandled[(*I)->getNumber()] = true;
1826 JumpTableBB->addSuccessor(*I);
1830 // Create a jump table index for this jump table, or return an existing
1832 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1834 // Set the jump table information so that we can codegen it as a second
1835 // MachineBasicBlock
1836 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1837 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1838 if (CR.CaseBB == CurMBB)
1839 visitJumpTableHeader(JT, JTH);
1841 JTCases.push_back(JumpTableBlock(JTH, JT));
1846 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1848 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1849 CaseRecVector& WorkList,
1851 MachineBasicBlock* Default) {
1852 // Get the MachineFunction which holds the current MBB. This is used when
1853 // inserting any additional MBBs necessary to represent the switch.
1854 MachineFunction *CurMF = FuncInfo.MF;
1856 // Figure out which block is immediately after the current one.
1857 MachineFunction::iterator BBI = CR.CaseBB;
1860 Case& FrontCase = *CR.Range.first;
1861 Case& BackCase = *(CR.Range.second-1);
1862 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1864 // Size is the number of Cases represented by this range.
1865 unsigned Size = CR.Range.second - CR.Range.first;
1867 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1868 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1870 CaseItr Pivot = CR.Range.first + Size/2;
1872 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1873 // (heuristically) allow us to emit JumpTable's later.
1874 APInt TSize(First.getBitWidth(), 0);
1875 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1879 APInt LSize = FrontCase.size();
1880 APInt RSize = TSize-LSize;
1881 DEBUG(errs() << "Selecting best pivot: \n"
1882 << "First: " << First << ", Last: " << Last <<'\n'
1883 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
1884 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1886 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
1887 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
1888 APInt Range = ComputeRange(LEnd, RBegin);
1889 assert((Range - 2ULL).isNonNegative() &&
1890 "Invalid case distance");
1891 double LDensity = (double)LSize.roundToDouble() /
1892 (LEnd - First + 1ULL).roundToDouble();
1893 double RDensity = (double)RSize.roundToDouble() /
1894 (Last - RBegin + 1ULL).roundToDouble();
1895 double Metric = Range.logBase2()*(LDensity+RDensity);
1896 // Should always split in some non-trivial place
1897 DEBUG(errs() <<"=>Step\n"
1898 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1899 << "LDensity: " << LDensity
1900 << ", RDensity: " << RDensity << '\n'
1901 << "Metric: " << Metric << '\n');
1902 if (FMetric < Metric) {
1905 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
1911 if (areJTsAllowed(TLI)) {
1912 // If our case is dense we *really* should handle it earlier!
1913 assert((FMetric > 0) && "Should handle dense range earlier!");
1915 Pivot = CR.Range.first + Size/2;
1918 CaseRange LHSR(CR.Range.first, Pivot);
1919 CaseRange RHSR(Pivot, CR.Range.second);
1920 Constant *C = Pivot->Low;
1921 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1923 // We know that we branch to the LHS if the Value being switched on is
1924 // less than the Pivot value, C. We use this to optimize our binary
1925 // tree a bit, by recognizing that if SV is greater than or equal to the
1926 // LHS's Case Value, and that Case Value is exactly one less than the
1927 // Pivot's Value, then we can branch directly to the LHS's Target,
1928 // rather than creating a leaf node for it.
1929 if ((LHSR.second - LHSR.first) == 1 &&
1930 LHSR.first->High == CR.GE &&
1931 cast<ConstantInt>(C)->getValue() ==
1932 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
1933 TrueBB = LHSR.first->BB;
1935 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1936 CurMF->insert(BBI, TrueBB);
1937 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1939 // Put SV in a virtual register to make it available from the new blocks.
1940 ExportFromCurrentBlock(SV);
1943 // Similar to the optimization above, if the Value being switched on is
1944 // known to be less than the Constant CR.LT, and the current Case Value
1945 // is CR.LT - 1, then we can branch directly to the target block for
1946 // the current Case Value, rather than emitting a RHS leaf node for it.
1947 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1948 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1949 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
1950 FalseBB = RHSR.first->BB;
1952 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1953 CurMF->insert(BBI, FalseBB);
1954 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1956 // Put SV in a virtual register to make it available from the new blocks.
1957 ExportFromCurrentBlock(SV);
1960 // Create a CaseBlock record representing a conditional branch to
1961 // the LHS node if the value being switched on SV is less than C.
1962 // Otherwise, branch to LHS.
1963 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1965 if (CR.CaseBB == CurMBB)
1966 visitSwitchCase(CB);
1968 SwitchCases.push_back(CB);
1973 /// handleBitTestsSwitchCase - if current case range has few destination and
1974 /// range span less, than machine word bitwidth, encode case range into series
1975 /// of masks and emit bit tests with these masks.
1976 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1977 CaseRecVector& WorkList,
1979 MachineBasicBlock* Default){
1980 EVT PTy = TLI.getPointerTy();
1981 unsigned IntPtrBits = PTy.getSizeInBits();
1983 Case& FrontCase = *CR.Range.first;
1984 Case& BackCase = *(CR.Range.second-1);
1986 // Get the MachineFunction which holds the current MBB. This is used when
1987 // inserting any additional MBBs necessary to represent the switch.
1988 MachineFunction *CurMF = FuncInfo.MF;
1990 // If target does not have legal shift left, do not emit bit tests at all.
1991 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
1995 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1997 // Single case counts one, case range - two.
1998 numCmps += (I->Low == I->High ? 1 : 2);
2001 // Count unique destinations
2002 SmallSet<MachineBasicBlock*, 4> Dests;
2003 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2004 Dests.insert(I->BB);
2005 if (Dests.size() > 3)
2006 // Don't bother the code below, if there are too much unique destinations
2009 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
2010 << "Total number of comparisons: " << numCmps << '\n');
2012 // Compute span of values.
2013 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2014 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
2015 APInt cmpRange = maxValue - minValue;
2017 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
2018 << "Low bound: " << minValue << '\n'
2019 << "High bound: " << maxValue << '\n');
2021 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
2022 (!(Dests.size() == 1 && numCmps >= 3) &&
2023 !(Dests.size() == 2 && numCmps >= 5) &&
2024 !(Dests.size() >= 3 && numCmps >= 6)))
2027 DEBUG(errs() << "Emitting bit tests\n");
2028 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2030 // Optimize the case where all the case values fit in a
2031 // word without having to subtract minValue. In this case,
2032 // we can optimize away the subtraction.
2033 if (minValue.isNonNegative() &&
2034 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
2035 cmpRange = maxValue;
2037 lowBound = minValue;
2040 CaseBitsVector CasesBits;
2041 unsigned i, count = 0;
2043 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2044 MachineBasicBlock* Dest = I->BB;
2045 for (i = 0; i < count; ++i)
2046 if (Dest == CasesBits[i].BB)
2050 assert((count < 3) && "Too much destinations to test!");
2051 CasesBits.push_back(CaseBits(0, Dest, 0));
2055 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2056 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2058 uint64_t lo = (lowValue - lowBound).getZExtValue();
2059 uint64_t hi = (highValue - lowBound).getZExtValue();
2061 for (uint64_t j = lo; j <= hi; j++) {
2062 CasesBits[i].Mask |= 1ULL << j;
2063 CasesBits[i].Bits++;
2067 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2071 // Figure out which block is immediately after the current one.
2072 MachineFunction::iterator BBI = CR.CaseBB;
2075 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2077 DEBUG(errs() << "Cases:\n");
2078 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2079 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
2080 << ", Bits: " << CasesBits[i].Bits
2081 << ", BB: " << CasesBits[i].BB << '\n');
2083 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2084 CurMF->insert(BBI, CaseBB);
2085 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2089 // Put SV in a virtual register to make it available from the new blocks.
2090 ExportFromCurrentBlock(SV);
2093 BitTestBlock BTB(lowBound, cmpRange, SV,
2094 -1U, (CR.CaseBB == CurMBB),
2095 CR.CaseBB, Default, BTC);
2097 if (CR.CaseBB == CurMBB)
2098 visitBitTestHeader(BTB);
2100 BitTestCases.push_back(BTB);
2106 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2107 size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
2108 const SwitchInst& SI) {
2111 // Start with "simple" cases
2112 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
2113 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2114 Cases.push_back(Case(SI.getSuccessorValue(i),
2115 SI.getSuccessorValue(i),
2118 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2120 // Merge case into clusters
2121 if (Cases.size() >= 2)
2122 // Must recompute end() each iteration because it may be
2123 // invalidated by erase if we hold on to it
2124 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
2125 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2126 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2127 MachineBasicBlock* nextBB = J->BB;
2128 MachineBasicBlock* currentBB = I->BB;
2130 // If the two neighboring cases go to the same destination, merge them
2131 // into a single case.
2132 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2140 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2141 if (I->Low != I->High)
2142 // A range counts double, since it requires two compares.
2149 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
2150 // Figure out which block is immediately after the current one.
2151 MachineBasicBlock *NextBlock = 0;
2153 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2155 // If there is only the default destination, branch to it if it is not the
2156 // next basic block. Otherwise, just fall through.
2157 if (SI.getNumOperands() == 2) {
2158 // Update machine-CFG edges.
2160 // If this is not a fall-through branch, emit the branch.
2161 CurMBB->addSuccessor(Default);
2162 if (Default != NextBlock)
2163 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
2164 MVT::Other, getControlRoot(),
2165 DAG.getBasicBlock(Default)));
2169 // If there are any non-default case statements, create a vector of Cases
2170 // representing each one, and sort the vector so that we can efficiently
2171 // create a binary search tree from them.
2173 size_t numCmps = Clusterify(Cases, SI);
2174 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2175 << ". Total compares: " << numCmps << '\n');
2178 // Get the Value to be switched on and default basic blocks, which will be
2179 // inserted into CaseBlock records, representing basic blocks in the binary
2181 Value *SV = SI.getOperand(0);
2183 // Push the initial CaseRec onto the worklist
2184 CaseRecVector WorkList;
2185 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2187 while (!WorkList.empty()) {
2188 // Grab a record representing a case range to process off the worklist
2189 CaseRec CR = WorkList.back();
2190 WorkList.pop_back();
2192 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2195 // If the range has few cases (two or less) emit a series of specific
2197 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2200 // If the switch has more than 5 blocks, and at least 40% dense, and the
2201 // target supports indirect branches, then emit a jump table rather than
2202 // lowering the switch to a binary tree of conditional branches.
2203 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2206 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2207 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2208 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2212 void SelectionDAGLowering::visitIndirectBr(IndirectBrInst &I) {
2213 // Update machine-CFG edges.
2214 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
2215 CurMBB->addSuccessor(FuncInfo.MBBMap[I.getSuccessor(i)]);
2217 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2218 MVT::Other, getControlRoot(),
2219 getValue(I.getAddress())));
2223 void SelectionDAGLowering::visitFSub(User &I) {
2224 // -0.0 - X --> fneg
2225 const Type *Ty = I.getType();
2226 if (isa<VectorType>(Ty)) {
2227 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2228 const VectorType *DestTy = cast<VectorType>(I.getType());
2229 const Type *ElTy = DestTy->getElementType();
2230 unsigned VL = DestTy->getNumElements();
2231 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2232 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2234 SDValue Op2 = getValue(I.getOperand(1));
2235 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2236 Op2.getValueType(), Op2));
2241 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2242 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2243 SDValue Op2 = getValue(I.getOperand(1));
2244 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2245 Op2.getValueType(), Op2));
2249 visitBinary(I, ISD::FSUB);
2252 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2253 SDValue Op1 = getValue(I.getOperand(0));
2254 SDValue Op2 = getValue(I.getOperand(1));
2256 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2257 Op1.getValueType(), Op1, Op2));
2260 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2261 SDValue Op1 = getValue(I.getOperand(0));
2262 SDValue Op2 = getValue(I.getOperand(1));
2263 if (!isa<VectorType>(I.getType()) &&
2264 Op2.getValueType() != TLI.getShiftAmountTy()) {
2265 // If the operand is smaller than the shift count type, promote it.
2266 EVT PTy = TLI.getPointerTy();
2267 EVT STy = TLI.getShiftAmountTy();
2268 if (STy.bitsGT(Op2.getValueType()))
2269 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2270 TLI.getShiftAmountTy(), Op2);
2271 // If the operand is larger than the shift count type but the shift
2272 // count type has enough bits to represent any shift value, truncate
2273 // it now. This is a common case and it exposes the truncate to
2274 // optimization early.
2275 else if (STy.getSizeInBits() >=
2276 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2277 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2278 TLI.getShiftAmountTy(), Op2);
2279 // Otherwise we'll need to temporarily settle for some other
2280 // convenient type; type legalization will make adjustments as
2282 else if (PTy.bitsLT(Op2.getValueType()))
2283 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2284 TLI.getPointerTy(), Op2);
2285 else if (PTy.bitsGT(Op2.getValueType()))
2286 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2287 TLI.getPointerTy(), Op2);
2290 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2291 Op1.getValueType(), Op1, Op2));
2294 void SelectionDAGLowering::visitICmp(User &I) {
2295 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2296 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2297 predicate = IC->getPredicate();
2298 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2299 predicate = ICmpInst::Predicate(IC->getPredicate());
2300 SDValue Op1 = getValue(I.getOperand(0));
2301 SDValue Op2 = getValue(I.getOperand(1));
2302 ISD::CondCode Opcode = getICmpCondCode(predicate);
2304 EVT DestVT = TLI.getValueType(I.getType());
2305 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
2308 void SelectionDAGLowering::visitFCmp(User &I) {
2309 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2310 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2311 predicate = FC->getPredicate();
2312 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2313 predicate = FCmpInst::Predicate(FC->getPredicate());
2314 SDValue Op1 = getValue(I.getOperand(0));
2315 SDValue Op2 = getValue(I.getOperand(1));
2316 ISD::CondCode Condition = getFCmpCondCode(predicate);
2317 EVT DestVT = TLI.getValueType(I.getType());
2318 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
2321 void SelectionDAGLowering::visitSelect(User &I) {
2322 SmallVector<EVT, 4> ValueVTs;
2323 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2324 unsigned NumValues = ValueVTs.size();
2325 if (NumValues != 0) {
2326 SmallVector<SDValue, 4> Values(NumValues);
2327 SDValue Cond = getValue(I.getOperand(0));
2328 SDValue TrueVal = getValue(I.getOperand(1));
2329 SDValue FalseVal = getValue(I.getOperand(2));
2331 for (unsigned i = 0; i != NumValues; ++i)
2332 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2333 TrueVal.getValueType(), Cond,
2334 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2335 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2337 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2338 DAG.getVTList(&ValueVTs[0], NumValues),
2339 &Values[0], NumValues));
2344 void SelectionDAGLowering::visitTrunc(User &I) {
2345 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2346 SDValue N = getValue(I.getOperand(0));
2347 EVT DestVT = TLI.getValueType(I.getType());
2348 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
2351 void SelectionDAGLowering::visitZExt(User &I) {
2352 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2353 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2354 SDValue N = getValue(I.getOperand(0));
2355 EVT DestVT = TLI.getValueType(I.getType());
2356 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
2359 void SelectionDAGLowering::visitSExt(User &I) {
2360 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2361 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2362 SDValue N = getValue(I.getOperand(0));
2363 EVT DestVT = TLI.getValueType(I.getType());
2364 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
2367 void SelectionDAGLowering::visitFPTrunc(User &I) {
2368 // FPTrunc is never a no-op cast, no need to check
2369 SDValue N = getValue(I.getOperand(0));
2370 EVT DestVT = TLI.getValueType(I.getType());
2371 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2372 DestVT, N, DAG.getIntPtrConstant(0)));
2375 void SelectionDAGLowering::visitFPExt(User &I){
2376 // FPTrunc is never a no-op cast, no need to check
2377 SDValue N = getValue(I.getOperand(0));
2378 EVT DestVT = TLI.getValueType(I.getType());
2379 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
2382 void SelectionDAGLowering::visitFPToUI(User &I) {
2383 // FPToUI is never a no-op cast, no need to check
2384 SDValue N = getValue(I.getOperand(0));
2385 EVT DestVT = TLI.getValueType(I.getType());
2386 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
2389 void SelectionDAGLowering::visitFPToSI(User &I) {
2390 // FPToSI is never a no-op cast, no need to check
2391 SDValue N = getValue(I.getOperand(0));
2392 EVT DestVT = TLI.getValueType(I.getType());
2393 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
2396 void SelectionDAGLowering::visitUIToFP(User &I) {
2397 // UIToFP is never a no-op cast, no need to check
2398 SDValue N = getValue(I.getOperand(0));
2399 EVT DestVT = TLI.getValueType(I.getType());
2400 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
2403 void SelectionDAGLowering::visitSIToFP(User &I){
2404 // SIToFP is never a no-op cast, no need to check
2405 SDValue N = getValue(I.getOperand(0));
2406 EVT DestVT = TLI.getValueType(I.getType());
2407 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
2410 void SelectionDAGLowering::visitPtrToInt(User &I) {
2411 // What to do depends on the size of the integer and the size of the pointer.
2412 // We can either truncate, zero extend, or no-op, accordingly.
2413 SDValue N = getValue(I.getOperand(0));
2414 EVT SrcVT = N.getValueType();
2415 EVT DestVT = TLI.getValueType(I.getType());
2416 SDValue Result = DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT);
2417 setValue(&I, Result);
2420 void SelectionDAGLowering::visitIntToPtr(User &I) {
2421 // What to do depends on the size of the integer and the size of the pointer.
2422 // We can either truncate, zero extend, or no-op, accordingly.
2423 SDValue N = getValue(I.getOperand(0));
2424 EVT SrcVT = N.getValueType();
2425 EVT DestVT = TLI.getValueType(I.getType());
2426 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2429 void SelectionDAGLowering::visitBitCast(User &I) {
2430 SDValue N = getValue(I.getOperand(0));
2431 EVT DestVT = TLI.getValueType(I.getType());
2433 // BitCast assures us that source and destination are the same size so this
2434 // is either a BIT_CONVERT or a no-op.
2435 if (DestVT != N.getValueType())
2436 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
2437 DestVT, N)); // convert types
2439 setValue(&I, N); // noop cast.
2442 void SelectionDAGLowering::visitInsertElement(User &I) {
2443 SDValue InVec = getValue(I.getOperand(0));
2444 SDValue InVal = getValue(I.getOperand(1));
2445 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2447 getValue(I.getOperand(2)));
2449 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2450 TLI.getValueType(I.getType()),
2451 InVec, InVal, InIdx));
2454 void SelectionDAGLowering::visitExtractElement(User &I) {
2455 SDValue InVec = getValue(I.getOperand(0));
2456 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2458 getValue(I.getOperand(1)));
2459 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2460 TLI.getValueType(I.getType()), InVec, InIdx));
2464 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2465 // from SIndx and increasing to the element length (undefs are allowed).
2466 static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2467 unsigned MaskNumElts = Mask.size();
2468 for (unsigned i = 0; i != MaskNumElts; ++i)
2469 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
2474 void SelectionDAGLowering::visitShuffleVector(User &I) {
2475 SmallVector<int, 8> Mask;
2476 SDValue Src1 = getValue(I.getOperand(0));
2477 SDValue Src2 = getValue(I.getOperand(1));
2479 // Convert the ConstantVector mask operand into an array of ints, with -1
2480 // representing undef values.
2481 SmallVector<Constant*, 8> MaskElts;
2482 cast<Constant>(I.getOperand(2))->getVectorElements(*DAG.getContext(),
2484 unsigned MaskNumElts = MaskElts.size();
2485 for (unsigned i = 0; i != MaskNumElts; ++i) {
2486 if (isa<UndefValue>(MaskElts[i]))
2489 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2492 EVT VT = TLI.getValueType(I.getType());
2493 EVT SrcVT = Src1.getValueType();
2494 unsigned SrcNumElts = SrcVT.getVectorNumElements();
2496 if (SrcNumElts == MaskNumElts) {
2497 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2502 // Normalize the shuffle vector since mask and vector length don't match.
2503 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2504 // Mask is longer than the source vectors and is a multiple of the source
2505 // vectors. We can use concatenate vector to make the mask and vectors
2507 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2508 // The shuffle is concatenating two vectors together.
2509 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2514 // Pad both vectors with undefs to make them the same length as the mask.
2515 unsigned NumConcat = MaskNumElts / SrcNumElts;
2516 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2517 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
2518 SDValue UndefVal = DAG.getUNDEF(SrcVT);
2520 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2521 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2525 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2526 getCurDebugLoc(), VT,
2527 &MOps1[0], NumConcat);
2528 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2529 getCurDebugLoc(), VT,
2530 &MOps2[0], NumConcat);
2532 // Readjust mask for new input vector length.
2533 SmallVector<int, 8> MappedOps;
2534 for (unsigned i = 0; i != MaskNumElts; ++i) {
2536 if (Idx < (int)SrcNumElts)
2537 MappedOps.push_back(Idx);
2539 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
2541 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2546 if (SrcNumElts > MaskNumElts) {
2547 // Analyze the access pattern of the vector to see if we can extract
2548 // two subvectors and do the shuffle. The analysis is done by calculating
2549 // the range of elements the mask access on both vectors.
2550 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2551 int MaxRange[2] = {-1, -1};
2553 for (unsigned i = 0; i != MaskNumElts; ++i) {
2559 if (Idx >= (int)SrcNumElts) {
2563 if (Idx > MaxRange[Input])
2564 MaxRange[Input] = Idx;
2565 if (Idx < MinRange[Input])
2566 MinRange[Input] = Idx;
2569 // Check if the access is smaller than the vector size and can we find
2570 // a reasonable extract index.
2571 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
2572 int StartIdx[2]; // StartIdx to extract from
2573 for (int Input=0; Input < 2; ++Input) {
2574 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
2575 RangeUse[Input] = 0; // Unused
2576 StartIdx[Input] = 0;
2577 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
2578 // Fits within range but we should see if we can find a good
2579 // start index that is a multiple of the mask length.
2580 if (MaxRange[Input] < (int)MaskNumElts) {
2581 RangeUse[Input] = 1; // Extract from beginning of the vector
2582 StartIdx[Input] = 0;
2584 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2585 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2586 StartIdx[Input] + MaskNumElts < SrcNumElts)
2587 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2592 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
2593 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
2596 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2597 // Extract appropriate subvector and generate a vector shuffle
2598 for (int Input=0; Input < 2; ++Input) {
2599 SDValue& Src = Input == 0 ? Src1 : Src2;
2600 if (RangeUse[Input] == 0) {
2601 Src = DAG.getUNDEF(VT);
2603 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
2604 Src, DAG.getIntPtrConstant(StartIdx[Input]));
2607 // Calculate new mask.
2608 SmallVector<int, 8> MappedOps;
2609 for (unsigned i = 0; i != MaskNumElts; ++i) {
2612 MappedOps.push_back(Idx);
2613 else if (Idx < (int)SrcNumElts)
2614 MappedOps.push_back(Idx - StartIdx[0]);
2616 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
2618 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2624 // We can't use either concat vectors or extract subvectors so fall back to
2625 // replacing the shuffle with extract and build vector.
2626 // to insert and build vector.
2627 EVT EltVT = VT.getVectorElementType();
2628 EVT PtrVT = TLI.getPointerTy();
2629 SmallVector<SDValue,8> Ops;
2630 for (unsigned i = 0; i != MaskNumElts; ++i) {
2632 Ops.push_back(DAG.getUNDEF(EltVT));
2635 if (Idx < (int)SrcNumElts)
2636 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2637 EltVT, Src1, DAG.getConstant(Idx, PtrVT)));
2639 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2641 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
2644 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2645 VT, &Ops[0], Ops.size()));
2648 void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2649 const Value *Op0 = I.getOperand(0);
2650 const Value *Op1 = I.getOperand(1);
2651 const Type *AggTy = I.getType();
2652 const Type *ValTy = Op1->getType();
2653 bool IntoUndef = isa<UndefValue>(Op0);
2654 bool FromUndef = isa<UndefValue>(Op1);
2656 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2657 I.idx_begin(), I.idx_end());
2659 SmallVector<EVT, 4> AggValueVTs;
2660 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2661 SmallVector<EVT, 4> ValValueVTs;
2662 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2664 unsigned NumAggValues = AggValueVTs.size();
2665 unsigned NumValValues = ValValueVTs.size();
2666 SmallVector<SDValue, 4> Values(NumAggValues);
2668 SDValue Agg = getValue(Op0);
2669 SDValue Val = getValue(Op1);
2671 // Copy the beginning value(s) from the original aggregate.
2672 for (; i != LinearIndex; ++i)
2673 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2674 SDValue(Agg.getNode(), Agg.getResNo() + i);
2675 // Copy values from the inserted value(s).
2676 for (; i != LinearIndex + NumValValues; ++i)
2677 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2678 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2679 // Copy remaining value(s) from the original aggregate.
2680 for (; i != NumAggValues; ++i)
2681 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2682 SDValue(Agg.getNode(), Agg.getResNo() + i);
2684 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2685 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2686 &Values[0], NumAggValues));
2689 void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2690 const Value *Op0 = I.getOperand(0);
2691 const Type *AggTy = Op0->getType();
2692 const Type *ValTy = I.getType();
2693 bool OutOfUndef = isa<UndefValue>(Op0);
2695 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2696 I.idx_begin(), I.idx_end());
2698 SmallVector<EVT, 4> ValValueVTs;
2699 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2701 unsigned NumValValues = ValValueVTs.size();
2702 SmallVector<SDValue, 4> Values(NumValValues);
2704 SDValue Agg = getValue(Op0);
2705 // Copy out the selected value(s).
2706 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2707 Values[i - LinearIndex] =
2709 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2710 SDValue(Agg.getNode(), Agg.getResNo() + i);
2712 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2713 DAG.getVTList(&ValValueVTs[0], NumValValues),
2714 &Values[0], NumValValues));
2718 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2719 SDValue N = getValue(I.getOperand(0));
2720 const Type *Ty = I.getOperand(0)->getType();
2722 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2725 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2726 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2729 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2730 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2731 DAG.getIntPtrConstant(Offset));
2733 Ty = StTy->getElementType(Field);
2735 Ty = cast<SequentialType>(Ty)->getElementType();
2737 // If this is a constant subscript, handle it quickly.
2738 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2739 if (CI->getZExtValue() == 0) continue;
2741 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2743 EVT PTy = TLI.getPointerTy();
2744 unsigned PtrBits = PTy.getSizeInBits();
2746 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2748 DAG.getConstant(Offs, MVT::i64));
2750 OffsVal = DAG.getIntPtrConstant(Offs);
2751 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2756 // N = N + Idx * ElementSize;
2757 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
2758 TD->getTypeAllocSize(Ty));
2759 SDValue IdxN = getValue(Idx);
2761 // If the index is smaller or larger than intptr_t, truncate or extend
2763 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
2765 // If this is a multiply by a power of two, turn it into a shl
2766 // immediately. This is a very common case.
2767 if (ElementSize != 1) {
2768 if (ElementSize.isPowerOf2()) {
2769 unsigned Amt = ElementSize.logBase2();
2770 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
2771 N.getValueType(), IdxN,
2772 DAG.getConstant(Amt, TLI.getPointerTy()));
2774 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
2775 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
2776 N.getValueType(), IdxN, Scale);
2780 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2781 N.getValueType(), N, IdxN);
2787 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2788 // If this is a fixed sized alloca in the entry block of the function,
2789 // allocate it statically on the stack.
2790 if (FuncInfo.StaticAllocaMap.count(&I))
2791 return; // getValue will auto-populate this.
2793 const Type *Ty = I.getAllocatedType();
2794 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
2796 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2799 SDValue AllocSize = getValue(I.getArraySize());
2801 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2803 DAG.getConstant(TySize, AllocSize.getValueType()));
2807 EVT IntPtr = TLI.getPointerTy();
2808 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
2810 // Handle alignment. If the requested alignment is less than or equal to
2811 // the stack alignment, ignore it. If the size is greater than or equal to
2812 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2813 unsigned StackAlign =
2814 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2815 if (Align <= StackAlign)
2818 // Round the size of the allocation up to the stack alignment size
2819 // by add SA-1 to the size.
2820 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2821 AllocSize.getValueType(), AllocSize,
2822 DAG.getIntPtrConstant(StackAlign-1));
2823 // Mask out the low bits for alignment purposes.
2824 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
2825 AllocSize.getValueType(), AllocSize,
2826 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2828 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2829 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
2830 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
2833 DAG.setRoot(DSA.getValue(1));
2835 // Inform the Frame Information that we have just allocated a variable-sized
2837 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject();
2840 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2841 const Value *SV = I.getOperand(0);
2842 SDValue Ptr = getValue(SV);
2844 const Type *Ty = I.getType();
2845 bool isVolatile = I.isVolatile();
2846 unsigned Alignment = I.getAlignment();
2848 SmallVector<EVT, 4> ValueVTs;
2849 SmallVector<uint64_t, 4> Offsets;
2850 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2851 unsigned NumValues = ValueVTs.size();
2856 bool ConstantMemory = false;
2858 // Serialize volatile loads with other side effects.
2860 else if (AA->pointsToConstantMemory(SV)) {
2861 // Do not serialize (non-volatile) loads of constant memory with anything.
2862 Root = DAG.getEntryNode();
2863 ConstantMemory = true;
2865 // Do not serialize non-volatile loads against each other.
2866 Root = DAG.getRoot();
2869 SmallVector<SDValue, 4> Values(NumValues);
2870 SmallVector<SDValue, 4> Chains(NumValues);
2871 EVT PtrVT = Ptr.getValueType();
2872 for (unsigned i = 0; i != NumValues; ++i) {
2873 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
2874 DAG.getNode(ISD::ADD, getCurDebugLoc(),
2876 DAG.getConstant(Offsets[i], PtrVT)),
2877 SV, Offsets[i], isVolatile, Alignment);
2879 Chains[i] = L.getValue(1);
2882 if (!ConstantMemory) {
2883 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2885 &Chains[0], NumValues);
2889 PendingLoads.push_back(Chain);
2892 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2893 DAG.getVTList(&ValueVTs[0], NumValues),
2894 &Values[0], NumValues));
2898 void SelectionDAGLowering::visitStore(StoreInst &I) {
2899 Value *SrcV = I.getOperand(0);
2900 Value *PtrV = I.getOperand(1);
2902 SmallVector<EVT, 4> ValueVTs;
2903 SmallVector<uint64_t, 4> Offsets;
2904 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2905 unsigned NumValues = ValueVTs.size();
2909 // Get the lowered operands. Note that we do this after
2910 // checking if NumResults is zero, because with zero results
2911 // the operands won't have values in the map.
2912 SDValue Src = getValue(SrcV);
2913 SDValue Ptr = getValue(PtrV);
2915 SDValue Root = getRoot();
2916 SmallVector<SDValue, 4> Chains(NumValues);
2917 EVT PtrVT = Ptr.getValueType();
2918 bool isVolatile = I.isVolatile();
2919 unsigned Alignment = I.getAlignment();
2920 for (unsigned i = 0; i != NumValues; ++i)
2921 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
2922 SDValue(Src.getNode(), Src.getResNo() + i),
2923 DAG.getNode(ISD::ADD, getCurDebugLoc(),
2925 DAG.getConstant(Offsets[i], PtrVT)),
2926 PtrV, Offsets[i], isVolatile, Alignment);
2928 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2929 MVT::Other, &Chains[0], NumValues));
2932 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2934 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2935 unsigned Intrinsic) {
2936 bool HasChain = !I.doesNotAccessMemory();
2937 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2939 // Build the operand list.
2940 SmallVector<SDValue, 8> Ops;
2941 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2943 // We don't need to serialize loads against other loads.
2944 Ops.push_back(DAG.getRoot());
2946 Ops.push_back(getRoot());
2950 // Info is set by getTgtMemInstrinsic
2951 TargetLowering::IntrinsicInfo Info;
2952 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2954 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
2955 if (!IsTgtIntrinsic)
2956 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2958 // Add all operands of the call to the operand list.
2959 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2960 SDValue Op = getValue(I.getOperand(i));
2961 assert(TLI.isTypeLegal(Op.getValueType()) &&
2962 "Intrinsic uses a non-legal type?");
2966 SmallVector<EVT, 4> ValueVTs;
2967 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2969 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
2970 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
2971 "Intrinsic uses a non-legal type?");
2975 ValueVTs.push_back(MVT::Other);
2977 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
2981 if (IsTgtIntrinsic) {
2982 // This is target intrinsic that touches memory
2983 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
2984 VTs, &Ops[0], Ops.size(),
2985 Info.memVT, Info.ptrVal, Info.offset,
2986 Info.align, Info.vol,
2987 Info.readMem, Info.writeMem);
2990 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
2991 VTs, &Ops[0], Ops.size());
2992 else if (I.getType() != Type::getVoidTy(*DAG.getContext()))
2993 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
2994 VTs, &Ops[0], Ops.size());
2996 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
2997 VTs, &Ops[0], Ops.size());
3000 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3002 PendingLoads.push_back(Chain);
3006 if (I.getType() != Type::getVoidTy(*DAG.getContext())) {
3007 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3008 EVT VT = TLI.getValueType(PTy);
3009 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
3011 setValue(&I, Result);
3015 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
3016 static GlobalVariable *ExtractTypeInfo(Value *V) {
3017 V = V->stripPointerCasts();
3018 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
3019 assert ((GV || isa<ConstantPointerNull>(V)) &&
3020 "TypeInfo must be a global variable or NULL");
3026 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
3027 /// call, and add them to the specified machine basic block.
3028 void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3029 MachineBasicBlock *MBB) {
3030 // Inform the MachineModuleInfo of the personality for this landing pad.
3031 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3032 assert(CE->getOpcode() == Instruction::BitCast &&
3033 isa<Function>(CE->getOperand(0)) &&
3034 "Personality should be a function");
3035 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3037 // Gather all the type infos for this landing pad and pass them along to
3038 // MachineModuleInfo.
3039 std::vector<GlobalVariable *> TyInfo;
3040 unsigned N = I.getNumOperands();
3042 for (unsigned i = N - 1; i > 2; --i) {
3043 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3044 unsigned FilterLength = CI->getZExtValue();
3045 unsigned FirstCatch = i + FilterLength + !FilterLength;
3046 assert (FirstCatch <= N && "Invalid filter length");
3048 if (FirstCatch < N) {
3049 TyInfo.reserve(N - FirstCatch);
3050 for (unsigned j = FirstCatch; j < N; ++j)
3051 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3052 MMI->addCatchTypeInfo(MBB, TyInfo);
3056 if (!FilterLength) {
3058 MMI->addCleanup(MBB);
3061 TyInfo.reserve(FilterLength - 1);
3062 for (unsigned j = i + 1; j < FirstCatch; ++j)
3063 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3064 MMI->addFilterTypeInfo(MBB, TyInfo);
3073 TyInfo.reserve(N - 3);
3074 for (unsigned j = 3; j < N; ++j)
3075 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3076 MMI->addCatchTypeInfo(MBB, TyInfo);
3082 /// GetSignificand - Get the significand and build it into a floating-point
3083 /// number with exponent of 1:
3085 /// Op = (Op & 0x007fffff) | 0x3f800000;
3087 /// where Op is the hexidecimal representation of floating point value.
3089 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
3090 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3091 DAG.getConstant(0x007fffff, MVT::i32));
3092 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3093 DAG.getConstant(0x3f800000, MVT::i32));
3094 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
3097 /// GetExponent - Get the exponent:
3099 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3101 /// where Op is the hexidecimal representation of floating point value.
3103 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3105 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3106 DAG.getConstant(0x7f800000, MVT::i32));
3107 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3108 DAG.getConstant(23, TLI.getPointerTy()));
3109 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3110 DAG.getConstant(127, MVT::i32));
3111 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3114 /// getF32Constant - Get 32-bit floating point constant.
3116 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3117 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3120 /// Inlined utility function to implement binary input atomic intrinsics for
3121 /// visitIntrinsicCall: I is a call instruction
3122 /// Op is the associated NodeType for I
3124 SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
3125 SDValue Root = getRoot();
3127 DAG.getAtomic(Op, getCurDebugLoc(),
3128 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
3130 getValue(I.getOperand(1)),
3131 getValue(I.getOperand(2)),
3134 DAG.setRoot(L.getValue(1));
3138 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
3140 SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
3141 SDValue Op1 = getValue(I.getOperand(1));
3142 SDValue Op2 = getValue(I.getOperand(2));
3144 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
3145 SDValue Result = DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2);
3147 setValue(&I, Result);
3151 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
3152 /// limited-precision mode.
3154 SelectionDAGLowering::visitExp(CallInst &I) {
3156 DebugLoc dl = getCurDebugLoc();
3158 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3159 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3160 SDValue Op = getValue(I.getOperand(1));
3162 // Put the exponent in the right bit position for later addition to the
3165 // #define LOG2OFe 1.4426950f
3166 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3167 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3168 getF32Constant(DAG, 0x3fb8aa3b));
3169 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3171 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3172 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3173 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3175 // IntegerPartOfX <<= 23;
3176 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3177 DAG.getConstant(23, TLI.getPointerTy()));
3179 if (LimitFloatPrecision <= 6) {
3180 // For floating-point precision of 6:
3182 // TwoToFractionalPartOfX =
3184 // (0.735607626f + 0.252464424f * x) * x;
3186 // error 0.0144103317, which is 6 bits
3187 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3188 getF32Constant(DAG, 0x3e814304));
3189 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3190 getF32Constant(DAG, 0x3f3c50c8));
3191 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3192 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3193 getF32Constant(DAG, 0x3f7f5e7e));
3194 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
3196 // Add the exponent into the result in integer domain.
3197 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3198 TwoToFracPartOfX, IntegerPartOfX);
3200 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
3201 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3202 // For floating-point precision of 12:
3204 // TwoToFractionalPartOfX =
3207 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3209 // 0.000107046256 error, which is 13 to 14 bits
3210 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3211 getF32Constant(DAG, 0x3da235e3));
3212 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3213 getF32Constant(DAG, 0x3e65b8f3));
3214 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3215 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3216 getF32Constant(DAG, 0x3f324b07));
3217 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3218 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3219 getF32Constant(DAG, 0x3f7ff8fd));
3220 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
3222 // Add the exponent into the result in integer domain.
3223 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3224 TwoToFracPartOfX, IntegerPartOfX);
3226 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
3227 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3228 // For floating-point precision of 18:
3230 // TwoToFractionalPartOfX =
3234 // (0.554906021e-1f +
3235 // (0.961591928e-2f +
3236 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3238 // error 2.47208000*10^(-7), which is better than 18 bits
3239 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3240 getF32Constant(DAG, 0x3924b03e));
3241 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3242 getF32Constant(DAG, 0x3ab24b87));
3243 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3244 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3245 getF32Constant(DAG, 0x3c1d8c17));
3246 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3247 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3248 getF32Constant(DAG, 0x3d634a1d));
3249 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3250 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3251 getF32Constant(DAG, 0x3e75fe14));
3252 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3253 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3254 getF32Constant(DAG, 0x3f317234));
3255 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3256 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3257 getF32Constant(DAG, 0x3f800000));
3258 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
3261 // Add the exponent into the result in integer domain.
3262 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3263 TwoToFracPartOfX, IntegerPartOfX);
3265 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
3268 // No special expansion.
3269 result = DAG.getNode(ISD::FEXP, dl,
3270 getValue(I.getOperand(1)).getValueType(),
3271 getValue(I.getOperand(1)));
3274 setValue(&I, result);
3277 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3278 /// limited-precision mode.
3280 SelectionDAGLowering::visitLog(CallInst &I) {
3282 DebugLoc dl = getCurDebugLoc();
3284 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3285 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3286 SDValue Op = getValue(I.getOperand(1));
3287 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3289 // Scale the exponent by log(2) [0.69314718f].
3290 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3291 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3292 getF32Constant(DAG, 0x3f317218));
3294 // Get the significand and build it into a floating-point number with
3296 SDValue X = GetSignificand(DAG, Op1, dl);
3298 if (LimitFloatPrecision <= 6) {
3299 // For floating-point precision of 6:
3303 // (1.4034025f - 0.23903021f * x) * x;
3305 // error 0.0034276066, which is better than 8 bits
3306 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3307 getF32Constant(DAG, 0xbe74c456));
3308 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3309 getF32Constant(DAG, 0x3fb3a2b1));
3310 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3311 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3312 getF32Constant(DAG, 0x3f949a29));
3314 result = DAG.getNode(ISD::FADD, dl,
3315 MVT::f32, LogOfExponent, LogOfMantissa);
3316 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3317 // For floating-point precision of 12:
3323 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3325 // error 0.000061011436, which is 14 bits
3326 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3327 getF32Constant(DAG, 0xbd67b6d6));
3328 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3329 getF32Constant(DAG, 0x3ee4f4b8));
3330 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3331 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3332 getF32Constant(DAG, 0x3fbc278b));
3333 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3334 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3335 getF32Constant(DAG, 0x40348e95));
3336 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3337 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3338 getF32Constant(DAG, 0x3fdef31a));
3340 result = DAG.getNode(ISD::FADD, dl,
3341 MVT::f32, LogOfExponent, LogOfMantissa);
3342 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3343 // For floating-point precision of 18:
3351 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3353 // error 0.0000023660568, which is better than 18 bits
3354 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3355 getF32Constant(DAG, 0xbc91e5ac));
3356 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3357 getF32Constant(DAG, 0x3e4350aa));
3358 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3359 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3360 getF32Constant(DAG, 0x3f60d3e3));
3361 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3362 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3363 getF32Constant(DAG, 0x4011cdf0));
3364 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3365 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3366 getF32Constant(DAG, 0x406cfd1c));
3367 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3368 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3369 getF32Constant(DAG, 0x408797cb));
3370 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3371 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3372 getF32Constant(DAG, 0x4006dcab));
3374 result = DAG.getNode(ISD::FADD, dl,
3375 MVT::f32, LogOfExponent, LogOfMantissa);
3378 // No special expansion.
3379 result = DAG.getNode(ISD::FLOG, dl,
3380 getValue(I.getOperand(1)).getValueType(),
3381 getValue(I.getOperand(1)));
3384 setValue(&I, result);
3387 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3388 /// limited-precision mode.
3390 SelectionDAGLowering::visitLog2(CallInst &I) {
3392 DebugLoc dl = getCurDebugLoc();
3394 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3395 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3396 SDValue Op = getValue(I.getOperand(1));
3397 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3399 // Get the exponent.
3400 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
3402 // Get the significand and build it into a floating-point number with
3404 SDValue X = GetSignificand(DAG, Op1, dl);
3406 // Different possible minimax approximations of significand in
3407 // floating-point for various degrees of accuracy over [1,2].
3408 if (LimitFloatPrecision <= 6) {
3409 // For floating-point precision of 6:
3411 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3413 // error 0.0049451742, which is more than 7 bits
3414 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3415 getF32Constant(DAG, 0xbeb08fe0));
3416 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3417 getF32Constant(DAG, 0x40019463));
3418 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3419 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3420 getF32Constant(DAG, 0x3fd6633d));
3422 result = DAG.getNode(ISD::FADD, dl,
3423 MVT::f32, LogOfExponent, Log2ofMantissa);
3424 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3425 // For floating-point precision of 12:
3431 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3433 // error 0.0000876136000, which is better than 13 bits
3434 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3435 getF32Constant(DAG, 0xbda7262e));
3436 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3437 getF32Constant(DAG, 0x3f25280b));
3438 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3439 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3440 getF32Constant(DAG, 0x4007b923));
3441 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3442 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3443 getF32Constant(DAG, 0x40823e2f));
3444 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3445 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3446 getF32Constant(DAG, 0x4020d29c));
3448 result = DAG.getNode(ISD::FADD, dl,
3449 MVT::f32, LogOfExponent, Log2ofMantissa);
3450 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3451 // For floating-point precision of 18:
3460 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3462 // error 0.0000018516, which is better than 18 bits
3463 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3464 getF32Constant(DAG, 0xbcd2769e));
3465 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3466 getF32Constant(DAG, 0x3e8ce0b9));
3467 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3468 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3469 getF32Constant(DAG, 0x3fa22ae7));
3470 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3471 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3472 getF32Constant(DAG, 0x40525723));
3473 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3474 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3475 getF32Constant(DAG, 0x40aaf200));
3476 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3477 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3478 getF32Constant(DAG, 0x40c39dad));
3479 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3480 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3481 getF32Constant(DAG, 0x4042902c));
3483 result = DAG.getNode(ISD::FADD, dl,
3484 MVT::f32, LogOfExponent, Log2ofMantissa);
3487 // No special expansion.
3488 result = DAG.getNode(ISD::FLOG2, dl,
3489 getValue(I.getOperand(1)).getValueType(),
3490 getValue(I.getOperand(1)));
3493 setValue(&I, result);
3496 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3497 /// limited-precision mode.
3499 SelectionDAGLowering::visitLog10(CallInst &I) {
3501 DebugLoc dl = getCurDebugLoc();
3503 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3504 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3505 SDValue Op = getValue(I.getOperand(1));
3506 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3508 // Scale the exponent by log10(2) [0.30102999f].
3509 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3510 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3511 getF32Constant(DAG, 0x3e9a209a));
3513 // Get the significand and build it into a floating-point number with
3515 SDValue X = GetSignificand(DAG, Op1, dl);
3517 if (LimitFloatPrecision <= 6) {
3518 // For floating-point precision of 6:
3520 // Log10ofMantissa =
3522 // (0.60948995f - 0.10380950f * x) * x;
3524 // error 0.0014886165, which is 6 bits
3525 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3526 getF32Constant(DAG, 0xbdd49a13));
3527 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3528 getF32Constant(DAG, 0x3f1c0789));
3529 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3530 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3531 getF32Constant(DAG, 0x3f011300));
3533 result = DAG.getNode(ISD::FADD, dl,
3534 MVT::f32, LogOfExponent, Log10ofMantissa);
3535 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3536 // For floating-point precision of 12:
3538 // Log10ofMantissa =
3541 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3543 // error 0.00019228036, which is better than 12 bits
3544 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3545 getF32Constant(DAG, 0x3d431f31));
3546 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3547 getF32Constant(DAG, 0x3ea21fb2));
3548 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3549 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3550 getF32Constant(DAG, 0x3f6ae232));
3551 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3552 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3553 getF32Constant(DAG, 0x3f25f7c3));
3555 result = DAG.getNode(ISD::FADD, dl,
3556 MVT::f32, LogOfExponent, Log10ofMantissa);
3557 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3558 // For floating-point precision of 18:
3560 // Log10ofMantissa =
3565 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3567 // error 0.0000037995730, which is better than 18 bits
3568 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3569 getF32Constant(DAG, 0x3c5d51ce));
3570 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3571 getF32Constant(DAG, 0x3e00685a));
3572 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3573 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3574 getF32Constant(DAG, 0x3efb6798));
3575 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3576 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3577 getF32Constant(DAG, 0x3f88d192));
3578 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3579 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3580 getF32Constant(DAG, 0x3fc4316c));
3581 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3582 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
3583 getF32Constant(DAG, 0x3f57ce70));
3585 result = DAG.getNode(ISD::FADD, dl,
3586 MVT::f32, LogOfExponent, Log10ofMantissa);
3589 // No special expansion.
3590 result = DAG.getNode(ISD::FLOG10, dl,
3591 getValue(I.getOperand(1)).getValueType(),
3592 getValue(I.getOperand(1)));
3595 setValue(&I, result);
3598 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3599 /// limited-precision mode.
3601 SelectionDAGLowering::visitExp2(CallInst &I) {
3603 DebugLoc dl = getCurDebugLoc();
3605 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3606 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3607 SDValue Op = getValue(I.getOperand(1));
3609 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
3611 // FractionalPartOfX = x - (float)IntegerPartOfX;
3612 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3613 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
3615 // IntegerPartOfX <<= 23;
3616 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3617 DAG.getConstant(23, TLI.getPointerTy()));
3619 if (LimitFloatPrecision <= 6) {
3620 // For floating-point precision of 6:
3622 // TwoToFractionalPartOfX =
3624 // (0.735607626f + 0.252464424f * x) * x;
3626 // error 0.0144103317, which is 6 bits
3627 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3628 getF32Constant(DAG, 0x3e814304));
3629 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3630 getF32Constant(DAG, 0x3f3c50c8));
3631 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3632 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3633 getF32Constant(DAG, 0x3f7f5e7e));
3634 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3635 SDValue TwoToFractionalPartOfX =
3636 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3638 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3639 MVT::f32, TwoToFractionalPartOfX);
3640 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3641 // For floating-point precision of 12:
3643 // TwoToFractionalPartOfX =
3646 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3648 // error 0.000107046256, which is 13 to 14 bits
3649 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3650 getF32Constant(DAG, 0x3da235e3));
3651 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3652 getF32Constant(DAG, 0x3e65b8f3));
3653 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3654 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3655 getF32Constant(DAG, 0x3f324b07));
3656 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3657 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3658 getF32Constant(DAG, 0x3f7ff8fd));
3659 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3660 SDValue TwoToFractionalPartOfX =
3661 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3663 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3664 MVT::f32, TwoToFractionalPartOfX);
3665 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3666 // For floating-point precision of 18:
3668 // TwoToFractionalPartOfX =
3672 // (0.554906021e-1f +
3673 // (0.961591928e-2f +
3674 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3675 // error 2.47208000*10^(-7), which is better than 18 bits
3676 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3677 getF32Constant(DAG, 0x3924b03e));
3678 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3679 getF32Constant(DAG, 0x3ab24b87));
3680 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3681 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3682 getF32Constant(DAG, 0x3c1d8c17));
3683 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3684 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3685 getF32Constant(DAG, 0x3d634a1d));
3686 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3687 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3688 getF32Constant(DAG, 0x3e75fe14));
3689 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3690 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3691 getF32Constant(DAG, 0x3f317234));
3692 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3693 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3694 getF32Constant(DAG, 0x3f800000));
3695 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3696 SDValue TwoToFractionalPartOfX =
3697 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3699 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3700 MVT::f32, TwoToFractionalPartOfX);
3703 // No special expansion.
3704 result = DAG.getNode(ISD::FEXP2, dl,
3705 getValue(I.getOperand(1)).getValueType(),
3706 getValue(I.getOperand(1)));
3709 setValue(&I, result);
3712 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3713 /// limited-precision mode with x == 10.0f.
3715 SelectionDAGLowering::visitPow(CallInst &I) {
3717 Value *Val = I.getOperand(1);
3718 DebugLoc dl = getCurDebugLoc();
3719 bool IsExp10 = false;
3721 if (getValue(Val).getValueType() == MVT::f32 &&
3722 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
3723 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3724 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3725 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3727 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3732 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3733 SDValue Op = getValue(I.getOperand(2));
3735 // Put the exponent in the right bit position for later addition to the
3738 // #define LOG2OF10 3.3219281f
3739 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3740 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3741 getF32Constant(DAG, 0x40549a78));
3742 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3744 // FractionalPartOfX = x - (float)IntegerPartOfX;
3745 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3746 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3748 // IntegerPartOfX <<= 23;
3749 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3750 DAG.getConstant(23, TLI.getPointerTy()));
3752 if (LimitFloatPrecision <= 6) {
3753 // For floating-point precision of 6:
3755 // twoToFractionalPartOfX =
3757 // (0.735607626f + 0.252464424f * x) * x;
3759 // error 0.0144103317, which is 6 bits
3760 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3761 getF32Constant(DAG, 0x3e814304));
3762 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3763 getF32Constant(DAG, 0x3f3c50c8));
3764 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3765 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3766 getF32Constant(DAG, 0x3f7f5e7e));
3767 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3768 SDValue TwoToFractionalPartOfX =
3769 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3771 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3772 MVT::f32, TwoToFractionalPartOfX);
3773 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3774 // For floating-point precision of 12:
3776 // TwoToFractionalPartOfX =
3779 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3781 // error 0.000107046256, which is 13 to 14 bits
3782 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3783 getF32Constant(DAG, 0x3da235e3));
3784 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3785 getF32Constant(DAG, 0x3e65b8f3));
3786 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3787 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3788 getF32Constant(DAG, 0x3f324b07));
3789 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3790 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3791 getF32Constant(DAG, 0x3f7ff8fd));
3792 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3793 SDValue TwoToFractionalPartOfX =
3794 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3796 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3797 MVT::f32, TwoToFractionalPartOfX);
3798 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3799 // For floating-point precision of 18:
3801 // TwoToFractionalPartOfX =
3805 // (0.554906021e-1f +
3806 // (0.961591928e-2f +
3807 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3808 // error 2.47208000*10^(-7), which is better than 18 bits
3809 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3810 getF32Constant(DAG, 0x3924b03e));
3811 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3812 getF32Constant(DAG, 0x3ab24b87));
3813 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3814 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3815 getF32Constant(DAG, 0x3c1d8c17));
3816 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3817 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3818 getF32Constant(DAG, 0x3d634a1d));
3819 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3820 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3821 getF32Constant(DAG, 0x3e75fe14));
3822 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3823 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3824 getF32Constant(DAG, 0x3f317234));
3825 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3826 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3827 getF32Constant(DAG, 0x3f800000));
3828 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3829 SDValue TwoToFractionalPartOfX =
3830 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3832 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3833 MVT::f32, TwoToFractionalPartOfX);
3836 // No special expansion.
3837 result = DAG.getNode(ISD::FPOW, dl,
3838 getValue(I.getOperand(1)).getValueType(),
3839 getValue(I.getOperand(1)),
3840 getValue(I.getOperand(2)));
3843 setValue(&I, result);
3846 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3847 /// we want to emit this as a call to a named external function, return the name
3848 /// otherwise lower it and return null.
3850 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3851 DebugLoc dl = getCurDebugLoc();
3852 switch (Intrinsic) {
3854 // By default, turn this into a target intrinsic node.
3855 visitTargetIntrinsic(I, Intrinsic);
3857 case Intrinsic::vastart: visitVAStart(I); return 0;
3858 case Intrinsic::vaend: visitVAEnd(I); return 0;
3859 case Intrinsic::vacopy: visitVACopy(I); return 0;
3860 case Intrinsic::returnaddress:
3861 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
3862 getValue(I.getOperand(1))));
3864 case Intrinsic::frameaddress:
3865 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
3866 getValue(I.getOperand(1))));
3868 case Intrinsic::setjmp:
3869 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3871 case Intrinsic::longjmp:
3872 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3874 case Intrinsic::memcpy: {
3875 SDValue Op1 = getValue(I.getOperand(1));
3876 SDValue Op2 = getValue(I.getOperand(2));
3877 SDValue Op3 = getValue(I.getOperand(3));
3878 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3879 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
3880 I.getOperand(1), 0, I.getOperand(2), 0));
3883 case Intrinsic::memset: {
3884 SDValue Op1 = getValue(I.getOperand(1));
3885 SDValue Op2 = getValue(I.getOperand(2));
3886 SDValue Op3 = getValue(I.getOperand(3));
3887 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3888 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
3889 I.getOperand(1), 0));
3892 case Intrinsic::memmove: {
3893 SDValue Op1 = getValue(I.getOperand(1));
3894 SDValue Op2 = getValue(I.getOperand(2));
3895 SDValue Op3 = getValue(I.getOperand(3));
3896 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3898 // If the source and destination are known to not be aliases, we can
3899 // lower memmove as memcpy.
3900 uint64_t Size = -1ULL;
3901 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3902 Size = C->getZExtValue();
3903 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3904 AliasAnalysis::NoAlias) {
3905 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
3906 I.getOperand(1), 0, I.getOperand(2), 0));
3910 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
3911 I.getOperand(1), 0, I.getOperand(2), 0));
3914 case Intrinsic::dbg_stoppoint:
3915 case Intrinsic::dbg_region_start:
3916 case Intrinsic::dbg_region_end:
3917 case Intrinsic::dbg_func_start:
3918 // FIXME - Remove this instructions once the dust settles.
3920 case Intrinsic::dbg_declare: {
3921 if (OptLevel != CodeGenOpt::None)
3922 // FIXME: Variable debug info is not supported here.
3924 DwarfWriter *DW = DAG.getDwarfWriter();
3927 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3928 if (!isValidDebugInfoIntrinsic(DI, CodeGenOpt::None))
3931 MDNode *Variable = DI.getVariable();
3932 Value *Address = DI.getAddress();
3933 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
3934 Address = BCI->getOperand(0);
3935 AllocaInst *AI = dyn_cast<AllocaInst>(Address);
3936 // Don't handle byval struct arguments or VLAs, for example.
3939 DenseMap<const AllocaInst*, int>::iterator SI =
3940 FuncInfo.StaticAllocaMap.find(AI);
3941 if (SI == FuncInfo.StaticAllocaMap.end())
3943 int FI = SI->second;
3945 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3947 MetadataContext &TheMetadata =
3948 DI.getParent()->getContext().getMetadata();
3949 unsigned MDDbgKind = TheMetadata.getMDKind("dbg");
3950 MDNode *Dbg = TheMetadata.getMD(MDDbgKind, &DI);
3951 MMI->setVariableDbgInfo(Variable, FI, Dbg);
3955 case Intrinsic::eh_exception: {
3956 // Insert the EXCEPTIONADDR instruction.
3957 assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!");
3958 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3960 Ops[0] = DAG.getRoot();
3961 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
3963 DAG.setRoot(Op.getValue(1));
3967 case Intrinsic::eh_selector: {
3968 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3970 if (CurMBB->isLandingPad())
3971 AddCatchInfo(I, MMI, CurMBB);
3974 FuncInfo.CatchInfoLost.insert(&I);
3976 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3977 unsigned Reg = TLI.getExceptionSelectorRegister();
3978 if (Reg) CurMBB->addLiveIn(Reg);
3981 // Insert the EHSELECTION instruction.
3982 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3984 Ops[0] = getValue(I.getOperand(1));
3986 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
3988 DAG.setRoot(Op.getValue(1));
3990 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
3994 case Intrinsic::eh_typeid_for: {
3995 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3998 // Find the type id for the given typeinfo.
3999 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
4001 unsigned TypeID = MMI->getTypeIDFor(GV);
4002 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
4004 // Return something different to eh_selector.
4005 setValue(&I, DAG.getConstant(1, MVT::i32));
4011 case Intrinsic::eh_return_i32:
4012 case Intrinsic::eh_return_i64:
4013 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4014 MMI->setCallsEHReturn(true);
4015 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
4018 getValue(I.getOperand(1)),
4019 getValue(I.getOperand(2))));
4021 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
4025 case Intrinsic::eh_unwind_init:
4026 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4027 MMI->setCallsUnwindInit(true);
4032 case Intrinsic::eh_dwarf_cfa: {
4033 EVT VT = getValue(I.getOperand(1)).getValueType();
4034 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), dl,
4035 TLI.getPointerTy());
4037 SDValue Offset = DAG.getNode(ISD::ADD, dl,
4039 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
4040 TLI.getPointerTy()),
4042 setValue(&I, DAG.getNode(ISD::ADD, dl,
4044 DAG.getNode(ISD::FRAMEADDR, dl,
4047 TLI.getPointerTy())),
4051 case Intrinsic::convertff:
4052 case Intrinsic::convertfsi:
4053 case Intrinsic::convertfui:
4054 case Intrinsic::convertsif:
4055 case Intrinsic::convertuif:
4056 case Intrinsic::convertss:
4057 case Intrinsic::convertsu:
4058 case Intrinsic::convertus:
4059 case Intrinsic::convertuu: {
4060 ISD::CvtCode Code = ISD::CVT_INVALID;
4061 switch (Intrinsic) {
4062 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4063 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4064 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4065 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4066 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4067 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4068 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4069 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4070 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4072 EVT DestVT = TLI.getValueType(I.getType());
4073 Value* Op1 = I.getOperand(1);
4074 setValue(&I, DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
4075 DAG.getValueType(DestVT),
4076 DAG.getValueType(getValue(Op1).getValueType()),
4077 getValue(I.getOperand(2)),
4078 getValue(I.getOperand(3)),
4083 case Intrinsic::sqrt:
4084 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
4085 getValue(I.getOperand(1)).getValueType(),
4086 getValue(I.getOperand(1))));
4088 case Intrinsic::powi:
4089 setValue(&I, DAG.getNode(ISD::FPOWI, dl,
4090 getValue(I.getOperand(1)).getValueType(),
4091 getValue(I.getOperand(1)),
4092 getValue(I.getOperand(2))));
4094 case Intrinsic::sin:
4095 setValue(&I, DAG.getNode(ISD::FSIN, dl,
4096 getValue(I.getOperand(1)).getValueType(),
4097 getValue(I.getOperand(1))));
4099 case Intrinsic::cos:
4100 setValue(&I, DAG.getNode(ISD::FCOS, dl,
4101 getValue(I.getOperand(1)).getValueType(),
4102 getValue(I.getOperand(1))));
4104 case Intrinsic::log:
4107 case Intrinsic::log2:
4110 case Intrinsic::log10:
4113 case Intrinsic::exp:
4116 case Intrinsic::exp2:
4119 case Intrinsic::pow:
4122 case Intrinsic::pcmarker: {
4123 SDValue Tmp = getValue(I.getOperand(1));
4124 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
4127 case Intrinsic::readcyclecounter: {
4128 SDValue Op = getRoot();
4129 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4130 DAG.getVTList(MVT::i64, MVT::Other),
4133 DAG.setRoot(Tmp.getValue(1));
4136 case Intrinsic::bswap:
4137 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
4138 getValue(I.getOperand(1)).getValueType(),
4139 getValue(I.getOperand(1))));
4141 case Intrinsic::cttz: {
4142 SDValue Arg = getValue(I.getOperand(1));
4143 EVT Ty = Arg.getValueType();
4144 SDValue result = DAG.getNode(ISD::CTTZ, dl, Ty, Arg);
4145 setValue(&I, result);
4148 case Intrinsic::ctlz: {
4149 SDValue Arg = getValue(I.getOperand(1));
4150 EVT Ty = Arg.getValueType();
4151 SDValue result = DAG.getNode(ISD::CTLZ, dl, Ty, Arg);
4152 setValue(&I, result);
4155 case Intrinsic::ctpop: {
4156 SDValue Arg = getValue(I.getOperand(1));
4157 EVT Ty = Arg.getValueType();
4158 SDValue result = DAG.getNode(ISD::CTPOP, dl, Ty, Arg);
4159 setValue(&I, result);
4162 case Intrinsic::stacksave: {
4163 SDValue Op = getRoot();
4164 SDValue Tmp = DAG.getNode(ISD::STACKSAVE, dl,
4165 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4167 DAG.setRoot(Tmp.getValue(1));
4170 case Intrinsic::stackrestore: {
4171 SDValue Tmp = getValue(I.getOperand(1));
4172 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Tmp));
4175 case Intrinsic::stackprotector: {
4176 // Emit code into the DAG to store the stack guard onto the stack.
4177 MachineFunction &MF = DAG.getMachineFunction();
4178 MachineFrameInfo *MFI = MF.getFrameInfo();
4179 EVT PtrTy = TLI.getPointerTy();
4181 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4182 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
4184 int FI = FuncInfo.StaticAllocaMap[Slot];
4185 MFI->setStackProtectorIndex(FI);
4187 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4189 // Store the stack protector onto the stack.
4190 SDValue Result = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4191 PseudoSourceValue::getFixedStack(FI),
4193 setValue(&I, Result);
4194 DAG.setRoot(Result);
4197 case Intrinsic::objectsize: {
4198 // If we don't know by now, we're never going to know.
4199 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2));
4201 assert(CI && "Non-constant type in __builtin_object_size?");
4203 SDValue Arg = getValue(I.getOperand(0));
4204 EVT Ty = Arg.getValueType();
4206 if (CI->getZExtValue() < 2)
4207 setValue(&I, DAG.getConstant(-1ULL, Ty));
4209 setValue(&I, DAG.getConstant(0, Ty));
4212 case Intrinsic::var_annotation:
4213 // Discard annotate attributes
4216 case Intrinsic::init_trampoline: {
4217 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4221 Ops[1] = getValue(I.getOperand(1));
4222 Ops[2] = getValue(I.getOperand(2));
4223 Ops[3] = getValue(I.getOperand(3));
4224 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4225 Ops[5] = DAG.getSrcValue(F);
4227 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE, dl,
4228 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4232 DAG.setRoot(Tmp.getValue(1));
4236 case Intrinsic::gcroot:
4238 Value *Alloca = I.getOperand(1);
4239 Constant *TypeMap = cast<Constant>(I.getOperand(2));
4241 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4242 GFI->addStackRoot(FI->getIndex(), TypeMap);
4246 case Intrinsic::gcread:
4247 case Intrinsic::gcwrite:
4248 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
4251 case Intrinsic::flt_rounds: {
4252 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
4256 case Intrinsic::trap: {
4257 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
4261 case Intrinsic::uadd_with_overflow:
4262 return implVisitAluOverflow(I, ISD::UADDO);
4263 case Intrinsic::sadd_with_overflow:
4264 return implVisitAluOverflow(I, ISD::SADDO);
4265 case Intrinsic::usub_with_overflow:
4266 return implVisitAluOverflow(I, ISD::USUBO);
4267 case Intrinsic::ssub_with_overflow:
4268 return implVisitAluOverflow(I, ISD::SSUBO);
4269 case Intrinsic::umul_with_overflow:
4270 return implVisitAluOverflow(I, ISD::UMULO);
4271 case Intrinsic::smul_with_overflow:
4272 return implVisitAluOverflow(I, ISD::SMULO);
4274 case Intrinsic::prefetch: {
4277 Ops[1] = getValue(I.getOperand(1));
4278 Ops[2] = getValue(I.getOperand(2));
4279 Ops[3] = getValue(I.getOperand(3));
4280 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
4284 case Intrinsic::memory_barrier: {
4287 for (int x = 1; x < 6; ++x)
4288 Ops[x] = getValue(I.getOperand(x));
4290 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
4293 case Intrinsic::atomic_cmp_swap: {
4294 SDValue Root = getRoot();
4296 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
4297 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4299 getValue(I.getOperand(1)),
4300 getValue(I.getOperand(2)),
4301 getValue(I.getOperand(3)),
4304 DAG.setRoot(L.getValue(1));
4307 case Intrinsic::atomic_load_add:
4308 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4309 case Intrinsic::atomic_load_sub:
4310 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4311 case Intrinsic::atomic_load_or:
4312 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4313 case Intrinsic::atomic_load_xor:
4314 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4315 case Intrinsic::atomic_load_and:
4316 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4317 case Intrinsic::atomic_load_nand:
4318 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4319 case Intrinsic::atomic_load_max:
4320 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4321 case Intrinsic::atomic_load_min:
4322 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4323 case Intrinsic::atomic_load_umin:
4324 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4325 case Intrinsic::atomic_load_umax:
4326 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4327 case Intrinsic::atomic_swap:
4328 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4330 case Intrinsic::invariant_start:
4331 case Intrinsic::lifetime_start:
4332 // Discard region information.
4333 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
4335 case Intrinsic::invariant_end:
4336 case Intrinsic::lifetime_end:
4337 // Discard region information.
4342 /// Test if the given instruction is in a position to be optimized
4343 /// with a tail-call. This roughly means that it's in a block with
4344 /// a return and there's nothing that needs to be scheduled
4345 /// between it and the return.
4347 /// This function only tests target-independent requirements.
4348 /// For target-dependent requirements, a target should override
4349 /// TargetLowering::IsEligibleForTailCallOptimization.
4352 isInTailCallPosition(const Instruction *I, Attributes RetAttr,
4353 const TargetLowering &TLI) {
4354 const BasicBlock *ExitBB = I->getParent();
4355 const TerminatorInst *Term = ExitBB->getTerminator();
4356 const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
4357 const Function *F = ExitBB->getParent();
4359 // The block must end in a return statement or an unreachable.
4360 if (!Ret && !isa<UnreachableInst>(Term)) return false;
4362 // If I will have a chain, make sure no other instruction that will have a
4363 // chain interposes between I and the return.
4364 if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
4365 !I->isSafeToSpeculativelyExecute())
4366 for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
4370 if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
4371 !BBI->isSafeToSpeculativelyExecute())
4375 // If the block ends with a void return or unreachable, it doesn't matter
4376 // what the call's return type is.
4377 if (!Ret || Ret->getNumOperands() == 0) return true;
4379 // Conservatively require the attributes of the call to match those of
4381 if (F->getAttributes().getRetAttributes() != RetAttr)
4384 // Otherwise, make sure the unmodified return value of I is the return value.
4385 for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ;
4386 U = dyn_cast<Instruction>(U->getOperand(0))) {
4389 if (!U->hasOneUse())
4393 // Check for a truly no-op truncate.
4394 if (isa<TruncInst>(U) &&
4395 TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType()))
4397 // Check for a truly no-op bitcast.
4398 if (isa<BitCastInst>(U) &&
4399 (U->getOperand(0)->getType() == U->getType() ||
4400 (isa<PointerType>(U->getOperand(0)->getType()) &&
4401 isa<PointerType>(U->getType()))))
4403 // Otherwise it's not a true no-op.
4410 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4412 MachineBasicBlock *LandingPad) {
4413 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4414 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4415 const Type *RetTy = FTy->getReturnType();
4416 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4417 unsigned BeginLabel = 0, EndLabel = 0;
4419 TargetLowering::ArgListTy Args;
4420 TargetLowering::ArgListEntry Entry;
4421 Args.reserve(CS.arg_size());
4423 // Check whether the function can return without sret-demotion.
4424 SmallVector<EVT, 4> OutVTs;
4425 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
4426 SmallVector<uint64_t, 4> Offsets;
4427 getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
4428 OutVTs, OutsFlags, TLI, &Offsets);
4431 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
4432 FTy->isVarArg(), OutVTs, OutsFlags, DAG);
4434 SDValue DemoteStackSlot;
4436 if (!CanLowerReturn) {
4437 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
4438 FTy->getReturnType());
4439 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
4440 FTy->getReturnType());
4441 MachineFunction &MF = DAG.getMachineFunction();
4442 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
4443 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
4445 DemoteStackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4446 Entry.Node = DemoteStackSlot;
4447 Entry.Ty = StackSlotPtrType;
4448 Entry.isSExt = false;
4449 Entry.isZExt = false;
4450 Entry.isInReg = false;
4451 Entry.isSRet = true;
4452 Entry.isNest = false;
4453 Entry.isByVal = false;
4454 Entry.Alignment = Align;
4455 Args.push_back(Entry);
4456 RetTy = Type::getVoidTy(FTy->getContext());
4459 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4461 SDValue ArgNode = getValue(*i);
4462 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4464 unsigned attrInd = i - CS.arg_begin() + 1;
4465 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4466 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4467 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4468 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4469 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4470 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4471 Entry.Alignment = CS.getParamAlignment(attrInd);
4472 Args.push_back(Entry);
4475 if (LandingPad && MMI) {
4476 // Insert a label before the invoke call to mark the try range. This can be
4477 // used to detect deletion of the invoke via the MachineModuleInfo.
4478 BeginLabel = MMI->NextLabelID();
4480 // Both PendingLoads and PendingExports must be flushed here;
4481 // this call might not return.
4483 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4484 getControlRoot(), BeginLabel));
4487 // Check if target-independent constraints permit a tail call here.
4488 // Target-dependent constraints are checked within TLI.LowerCallTo.
4490 !isInTailCallPosition(CS.getInstruction(),
4491 CS.getAttributes().getRetAttributes(),
4495 std::pair<SDValue,SDValue> Result =
4496 TLI.LowerCallTo(getRoot(), RetTy,
4497 CS.paramHasAttr(0, Attribute::SExt),
4498 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4499 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
4500 CS.getCallingConv(),
4502 !CS.getInstruction()->use_empty(),
4503 Callee, Args, DAG, getCurDebugLoc());
4504 assert((isTailCall || Result.second.getNode()) &&
4505 "Non-null chain expected with non-tail call!");
4506 assert((Result.second.getNode() || !Result.first.getNode()) &&
4507 "Null value expected with tail call!");
4508 if (Result.first.getNode())
4509 setValue(CS.getInstruction(), Result.first);
4510 else if (!CanLowerReturn && Result.second.getNode()) {
4511 // The instruction result is the result of loading from the
4512 // hidden sret parameter.
4513 SmallVector<EVT, 1> PVTs;
4514 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
4516 ComputeValueVTs(TLI, PtrRetTy, PVTs);
4517 assert(PVTs.size() == 1 && "Pointers should fit in one register");
4518 EVT PtrVT = PVTs[0];
4519 unsigned NumValues = OutVTs.size();
4520 SmallVector<SDValue, 4> Values(NumValues);
4521 SmallVector<SDValue, 4> Chains(NumValues);
4523 for (unsigned i = 0; i < NumValues; ++i) {
4524 SDValue L = DAG.getLoad(OutVTs[i], getCurDebugLoc(), Result.second,
4525 DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, DemoteStackSlot,
4526 DAG.getConstant(Offsets[i], PtrVT)),
4527 NULL, Offsets[i], false, 1);
4529 Chains[i] = L.getValue(1);
4531 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
4532 MVT::Other, &Chains[0], NumValues);
4533 PendingLoads.push_back(Chain);
4535 setValue(CS.getInstruction(), DAG.getNode(ISD::MERGE_VALUES,
4536 getCurDebugLoc(), DAG.getVTList(&OutVTs[0], NumValues),
4537 &Values[0], NumValues));
4539 // As a special case, a null chain means that a tail call has
4540 // been emitted and the DAG root is already updated.
4541 if (Result.second.getNode())
4542 DAG.setRoot(Result.second);
4546 if (LandingPad && MMI) {
4547 // Insert a label at the end of the invoke call to mark the try range. This
4548 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4549 EndLabel = MMI->NextLabelID();
4550 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4551 getRoot(), EndLabel));
4553 // Inform MachineModuleInfo of range.
4554 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4559 void SelectionDAGLowering::visitCall(CallInst &I) {
4560 const char *RenameFn = 0;
4561 if (Function *F = I.getCalledFunction()) {
4562 if (F->isDeclaration()) {
4563 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4565 if (unsigned IID = II->getIntrinsicID(F)) {
4566 RenameFn = visitIntrinsicCall(I, IID);
4571 if (unsigned IID = F->getIntrinsicID()) {
4572 RenameFn = visitIntrinsicCall(I, IID);
4578 // Check for well-known libc/libm calls. If the function is internal, it
4579 // can't be a library call.
4580 if (!F->hasLocalLinkage() && F->hasName()) {
4581 StringRef Name = F->getName();
4582 if (Name == "copysign" || Name == "copysignf") {
4583 if (I.getNumOperands() == 3 && // Basic sanity checks.
4584 I.getOperand(1)->getType()->isFloatingPoint() &&
4585 I.getType() == I.getOperand(1)->getType() &&
4586 I.getType() == I.getOperand(2)->getType()) {
4587 SDValue LHS = getValue(I.getOperand(1));
4588 SDValue RHS = getValue(I.getOperand(2));
4589 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
4590 LHS.getValueType(), LHS, RHS));
4593 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
4594 if (I.getNumOperands() == 2 && // Basic sanity checks.
4595 I.getOperand(1)->getType()->isFloatingPoint() &&
4596 I.getType() == I.getOperand(1)->getType()) {
4597 SDValue Tmp = getValue(I.getOperand(1));
4598 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
4599 Tmp.getValueType(), Tmp));
4602 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
4603 if (I.getNumOperands() == 2 && // Basic sanity checks.
4604 I.getOperand(1)->getType()->isFloatingPoint() &&
4605 I.getType() == I.getOperand(1)->getType() &&
4606 I.onlyReadsMemory()) {
4607 SDValue Tmp = getValue(I.getOperand(1));
4608 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
4609 Tmp.getValueType(), Tmp));
4612 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
4613 if (I.getNumOperands() == 2 && // Basic sanity checks.
4614 I.getOperand(1)->getType()->isFloatingPoint() &&
4615 I.getType() == I.getOperand(1)->getType() &&
4616 I.onlyReadsMemory()) {
4617 SDValue Tmp = getValue(I.getOperand(1));
4618 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
4619 Tmp.getValueType(), Tmp));
4622 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
4623 if (I.getNumOperands() == 2 && // Basic sanity checks.
4624 I.getOperand(1)->getType()->isFloatingPoint() &&
4625 I.getType() == I.getOperand(1)->getType() &&
4626 I.onlyReadsMemory()) {
4627 SDValue Tmp = getValue(I.getOperand(1));
4628 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
4629 Tmp.getValueType(), Tmp));
4634 } else if (isa<InlineAsm>(I.getOperand(0))) {
4641 Callee = getValue(I.getOperand(0));
4643 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
4645 // Check if we can potentially perform a tail call. More detailed
4646 // checking is be done within LowerCallTo, after more information
4647 // about the call is known.
4648 bool isTailCall = PerformTailCallOpt && I.isTailCall();
4650 LowerCallTo(&I, Callee, isTailCall);
4654 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4655 /// this value and returns the result as a ValueVT value. This uses
4656 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4657 /// If the Flag pointer is NULL, no flag is used.
4658 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
4660 SDValue *Flag) const {
4661 // Assemble the legal parts into the final values.
4662 SmallVector<SDValue, 4> Values(ValueVTs.size());
4663 SmallVector<SDValue, 8> Parts;
4664 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4665 // Copy the legal parts from the registers.
4666 EVT ValueVT = ValueVTs[Value];
4667 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
4668 EVT RegisterVT = RegVTs[Value];
4670 Parts.resize(NumRegs);
4671 for (unsigned i = 0; i != NumRegs; ++i) {
4674 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
4676 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
4677 *Flag = P.getValue(2);
4679 Chain = P.getValue(1);
4681 // If the source register was virtual and if we know something about it,
4682 // add an assert node.
4683 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4684 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4685 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4686 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4687 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4688 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4690 unsigned RegSize = RegisterVT.getSizeInBits();
4691 unsigned NumSignBits = LOI.NumSignBits;
4692 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4694 // FIXME: We capture more information than the dag can represent. For
4695 // now, just use the tightest assertzext/assertsext possible.
4697 EVT FromVT(MVT::Other);
4698 if (NumSignBits == RegSize)
4699 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4700 else if (NumZeroBits >= RegSize-1)
4701 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4702 else if (NumSignBits > RegSize-8)
4703 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4704 else if (NumZeroBits >= RegSize-8)
4705 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4706 else if (NumSignBits > RegSize-16)
4707 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
4708 else if (NumZeroBits >= RegSize-16)
4709 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
4710 else if (NumSignBits > RegSize-32)
4711 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
4712 else if (NumZeroBits >= RegSize-32)
4713 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
4715 if (FromVT != MVT::Other) {
4716 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
4717 RegisterVT, P, DAG.getValueType(FromVT));
4726 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
4727 NumRegs, RegisterVT, ValueVT);
4732 return DAG.getNode(ISD::MERGE_VALUES, dl,
4733 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4734 &Values[0], ValueVTs.size());
4737 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4738 /// specified value into the registers specified by this object. This uses
4739 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4740 /// If the Flag pointer is NULL, no flag is used.
4741 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
4742 SDValue &Chain, SDValue *Flag) const {
4743 // Get the list of the values's legal parts.
4744 unsigned NumRegs = Regs.size();
4745 SmallVector<SDValue, 8> Parts(NumRegs);
4746 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4747 EVT ValueVT = ValueVTs[Value];
4748 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
4749 EVT RegisterVT = RegVTs[Value];
4751 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
4752 &Parts[Part], NumParts, RegisterVT);
4756 // Copy the parts into the registers.
4757 SmallVector<SDValue, 8> Chains(NumRegs);
4758 for (unsigned i = 0; i != NumRegs; ++i) {
4761 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
4763 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
4764 *Flag = Part.getValue(1);
4766 Chains[i] = Part.getValue(0);
4769 if (NumRegs == 1 || Flag)
4770 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4771 // flagged to it. That is the CopyToReg nodes and the user are considered
4772 // a single scheduling unit. If we create a TokenFactor and return it as
4773 // chain, then the TokenFactor is both a predecessor (operand) of the
4774 // user as well as a successor (the TF operands are flagged to the user).
4775 // c1, f1 = CopyToReg
4776 // c2, f2 = CopyToReg
4777 // c3 = TokenFactor c1, c2
4780 Chain = Chains[NumRegs-1];
4782 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
4785 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
4786 /// operand list. This adds the code marker and includes the number of
4787 /// values added into it.
4788 void RegsForValue::AddInlineAsmOperands(unsigned Code,
4789 bool HasMatching,unsigned MatchingIdx,
4791 std::vector<SDValue> &Ops) const {
4792 EVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4793 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
4794 unsigned Flag = Code | (Regs.size() << 3);
4796 Flag |= 0x80000000 | (MatchingIdx << 16);
4797 Ops.push_back(DAG.getTargetConstant(Flag, IntPtrTy));
4798 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4799 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
4800 EVT RegisterVT = RegVTs[Value];
4801 for (unsigned i = 0; i != NumRegs; ++i) {
4802 assert(Reg < Regs.size() && "Mismatch in # registers expected");
4803 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
4808 /// isAllocatableRegister - If the specified register is safe to allocate,
4809 /// i.e. it isn't a stack pointer or some other special register, return the
4810 /// register class for the register. Otherwise, return null.
4811 static const TargetRegisterClass *
4812 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4813 const TargetLowering &TLI,
4814 const TargetRegisterInfo *TRI) {
4815 EVT FoundVT = MVT::Other;
4816 const TargetRegisterClass *FoundRC = 0;
4817 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4818 E = TRI->regclass_end(); RCI != E; ++RCI) {
4819 EVT ThisVT = MVT::Other;
4821 const TargetRegisterClass *RC = *RCI;
4822 // If none of the the value types for this register class are valid, we
4823 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4824 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4826 if (TLI.isTypeLegal(*I)) {
4827 // If we have already found this register in a different register class,
4828 // choose the one with the largest VT specified. For example, on
4829 // PowerPC, we favor f64 register classes over f32.
4830 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4837 if (ThisVT == MVT::Other) continue;
4839 // NOTE: This isn't ideal. In particular, this might allocate the
4840 // frame pointer in functions that need it (due to them not being taken
4841 // out of allocation, because a variable sized allocation hasn't been seen
4842 // yet). This is a slight code pessimization, but should still work.
4843 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4844 E = RC->allocation_order_end(MF); I != E; ++I)
4846 // We found a matching register class. Keep looking at others in case
4847 // we find one with larger registers that this physreg is also in.
4858 /// AsmOperandInfo - This contains information for each constraint that we are
4860 class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4861 public TargetLowering::AsmOperandInfo {
4863 /// CallOperand - If this is the result output operand or a clobber
4864 /// this is null, otherwise it is the incoming operand to the CallInst.
4865 /// This gets modified as the asm is processed.
4866 SDValue CallOperand;
4868 /// AssignedRegs - If this is a register or register class operand, this
4869 /// contains the set of register corresponding to the operand.
4870 RegsForValue AssignedRegs;
4872 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4873 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4876 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4877 /// busy in OutputRegs/InputRegs.
4878 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4879 std::set<unsigned> &OutputRegs,
4880 std::set<unsigned> &InputRegs,
4881 const TargetRegisterInfo &TRI) const {
4883 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4884 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4887 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4888 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4892 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
4893 /// corresponds to. If there is no Value* for this operand, it returns
4895 EVT getCallOperandValEVT(LLVMContext &Context,
4896 const TargetLowering &TLI,
4897 const TargetData *TD) const {
4898 if (CallOperandVal == 0) return MVT::Other;
4900 if (isa<BasicBlock>(CallOperandVal))
4901 return TLI.getPointerTy();
4903 const llvm::Type *OpTy = CallOperandVal->getType();
4905 // If this is an indirect operand, the operand is a pointer to the
4908 OpTy = cast<PointerType>(OpTy)->getElementType();
4910 // If OpTy is not a single value, it may be a struct/union that we
4911 // can tile with integers.
4912 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4913 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4922 OpTy = IntegerType::get(Context, BitSize);
4927 return TLI.getValueType(OpTy, true);
4931 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4933 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4934 const TargetRegisterInfo &TRI) {
4935 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4937 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4938 for (; *Aliases; ++Aliases)
4939 Regs.insert(*Aliases);
4942 } // end llvm namespace.
4945 /// GetRegistersForValue - Assign registers (virtual or physical) for the
4946 /// specified operand. We prefer to assign virtual registers, to allow the
4947 /// register allocator handle the assignment process. However, if the asm uses
4948 /// features that we can't model on machineinstrs, we have SDISel do the
4949 /// allocation. This produces generally horrible, but correct, code.
4951 /// OpInfo describes the operand.
4952 /// Input and OutputRegs are the set of already allocated physical registers.
4954 void SelectionDAGLowering::
4955 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
4956 std::set<unsigned> &OutputRegs,
4957 std::set<unsigned> &InputRegs) {
4958 LLVMContext &Context = FuncInfo.Fn->getContext();
4960 // Compute whether this value requires an input register, an output register,
4962 bool isOutReg = false;
4963 bool isInReg = false;
4964 switch (OpInfo.Type) {
4965 case InlineAsm::isOutput:
4968 // If there is an input constraint that matches this, we need to reserve
4969 // the input register so no other inputs allocate to it.
4970 isInReg = OpInfo.hasMatchingInput();
4972 case InlineAsm::isInput:
4976 case InlineAsm::isClobber:
4983 MachineFunction &MF = DAG.getMachineFunction();
4984 SmallVector<unsigned, 4> Regs;
4986 // If this is a constraint for a single physreg, or a constraint for a
4987 // register class, find it.
4988 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4989 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4990 OpInfo.ConstraintVT);
4992 unsigned NumRegs = 1;
4993 if (OpInfo.ConstraintVT != MVT::Other) {
4994 // If this is a FP input in an integer register (or visa versa) insert a bit
4995 // cast of the input value. More generally, handle any case where the input
4996 // value disagrees with the register class we plan to stick this in.
4997 if (OpInfo.Type == InlineAsm::isInput &&
4998 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4999 // Try to convert to the first EVT that the reg class contains. If the
5000 // types are identical size, use a bitcast to convert (e.g. two differing
5002 EVT RegVT = *PhysReg.second->vt_begin();
5003 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
5004 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5005 RegVT, OpInfo.CallOperand);
5006 OpInfo.ConstraintVT = RegVT;
5007 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5008 // If the input is a FP value and we want it in FP registers, do a
5009 // bitcast to the corresponding integer type. This turns an f64 value
5010 // into i64, which can be passed with two i32 values on a 32-bit
5012 RegVT = EVT::getIntegerVT(Context,
5013 OpInfo.ConstraintVT.getSizeInBits());
5014 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5015 RegVT, OpInfo.CallOperand);
5016 OpInfo.ConstraintVT = RegVT;
5020 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
5024 EVT ValueVT = OpInfo.ConstraintVT;
5026 // If this is a constraint for a specific physical register, like {r17},
5028 if (unsigned AssignedReg = PhysReg.first) {
5029 const TargetRegisterClass *RC = PhysReg.second;
5030 if (OpInfo.ConstraintVT == MVT::Other)
5031 ValueVT = *RC->vt_begin();
5033 // Get the actual register value type. This is important, because the user
5034 // may have asked for (e.g.) the AX register in i32 type. We need to
5035 // remember that AX is actually i16 to get the right extension.
5036 RegVT = *RC->vt_begin();
5038 // This is a explicit reference to a physical register.
5039 Regs.push_back(AssignedReg);
5041 // If this is an expanded reference, add the rest of the regs to Regs.
5043 TargetRegisterClass::iterator I = RC->begin();
5044 for (; *I != AssignedReg; ++I)
5045 assert(I != RC->end() && "Didn't find reg!");
5047 // Already added the first reg.
5049 for (; NumRegs; --NumRegs, ++I) {
5050 assert(I != RC->end() && "Ran out of registers to allocate!");
5054 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5055 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5056 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5060 // Otherwise, if this was a reference to an LLVM register class, create vregs
5061 // for this reference.
5062 if (const TargetRegisterClass *RC = PhysReg.second) {
5063 RegVT = *RC->vt_begin();
5064 if (OpInfo.ConstraintVT == MVT::Other)
5067 // Create the appropriate number of virtual registers.
5068 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5069 for (; NumRegs; --NumRegs)
5070 Regs.push_back(RegInfo.createVirtualRegister(RC));
5072 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
5076 // This is a reference to a register class that doesn't directly correspond
5077 // to an LLVM register class. Allocate NumRegs consecutive, available,
5078 // registers from the class.
5079 std::vector<unsigned> RegClassRegs
5080 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5081 OpInfo.ConstraintVT);
5083 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5084 unsigned NumAllocated = 0;
5085 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5086 unsigned Reg = RegClassRegs[i];
5087 // See if this register is available.
5088 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5089 (isInReg && InputRegs.count(Reg))) { // Already used.
5090 // Make sure we find consecutive registers.
5095 // Check to see if this register is allocatable (i.e. don't give out the
5097 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5098 if (!RC) { // Couldn't allocate this register.
5099 // Reset NumAllocated to make sure we return consecutive registers.
5104 // Okay, this register is good, we can use it.
5107 // If we allocated enough consecutive registers, succeed.
5108 if (NumAllocated == NumRegs) {
5109 unsigned RegStart = (i-NumAllocated)+1;
5110 unsigned RegEnd = i+1;
5111 // Mark all of the allocated registers used.
5112 for (unsigned i = RegStart; i != RegEnd; ++i)
5113 Regs.push_back(RegClassRegs[i]);
5115 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
5116 OpInfo.ConstraintVT);
5117 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5122 // Otherwise, we couldn't allocate enough registers for this.
5125 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5126 /// processed uses a memory 'm' constraint.
5128 hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
5129 const TargetLowering &TLI) {
5130 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5131 InlineAsm::ConstraintInfo &CI = CInfos[i];
5132 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5133 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5134 if (CType == TargetLowering::C_Memory)
5138 // Indirect operand accesses access memory.
5146 /// visitInlineAsm - Handle a call to an InlineAsm object.
5148 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
5149 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5151 /// ConstraintOperands - Information about all of the constraints.
5152 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
5154 std::set<unsigned> OutputRegs, InputRegs;
5156 // Do a prepass over the constraints, canonicalizing them, and building up the
5157 // ConstraintOperands list.
5158 std::vector<InlineAsm::ConstraintInfo>
5159 ConstraintInfos = IA->ParseConstraints();
5161 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
5163 SDValue Chain, Flag;
5165 // We won't need to flush pending loads if this asm doesn't touch
5166 // memory and is nonvolatile.
5167 if (hasMemory || IA->hasSideEffects())
5170 Chain = DAG.getRoot();
5172 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5173 unsigned ResNo = 0; // ResNo - The result number of the next output.
5174 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5175 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5176 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5178 EVT OpVT = MVT::Other;
5180 // Compute the value type for each operand.
5181 switch (OpInfo.Type) {
5182 case InlineAsm::isOutput:
5183 // Indirect outputs just consume an argument.
5184 if (OpInfo.isIndirect) {
5185 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5189 // The return value of the call is this value. As such, there is no
5190 // corresponding argument.
5191 assert(CS.getType() != Type::getVoidTy(*DAG.getContext()) &&
5193 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5194 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5196 assert(ResNo == 0 && "Asm only has one result!");
5197 OpVT = TLI.getValueType(CS.getType());
5201 case InlineAsm::isInput:
5202 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5204 case InlineAsm::isClobber:
5209 // If this is an input or an indirect output, process the call argument.
5210 // BasicBlocks are labels, currently appearing only in asm's.
5211 if (OpInfo.CallOperandVal) {
5212 // Strip bitcasts, if any. This mostly comes up for functions.
5213 OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts();
5215 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5216 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5218 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5221 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
5224 OpInfo.ConstraintVT = OpVT;
5227 // Second pass over the constraints: compute which constraint option to use
5228 // and assign registers to constraints that want a specific physreg.
5229 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5230 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5232 // If this is an output operand with a matching input operand, look up the
5233 // matching input. If their types mismatch, e.g. one is an integer, the
5234 // other is floating point, or their sizes are different, flag it as an
5236 if (OpInfo.hasMatchingInput()) {
5237 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5238 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5239 if ((OpInfo.ConstraintVT.isInteger() !=
5240 Input.ConstraintVT.isInteger()) ||
5241 (OpInfo.ConstraintVT.getSizeInBits() !=
5242 Input.ConstraintVT.getSizeInBits())) {
5243 llvm_report_error("Unsupported asm: input constraint"
5244 " with a matching output constraint of incompatible"
5247 Input.ConstraintVT = OpInfo.ConstraintVT;
5251 // Compute the constraint code and ConstraintType to use.
5252 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
5254 // If this is a memory input, and if the operand is not indirect, do what we
5255 // need to to provide an address for the memory input.
5256 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5257 !OpInfo.isIndirect) {
5258 assert(OpInfo.Type == InlineAsm::isInput &&
5259 "Can only indirectify direct input operands!");
5261 // Memory operands really want the address of the value. If we don't have
5262 // an indirect input, put it in the constpool if we can, otherwise spill
5263 // it to a stack slot.
5265 // If the operand is a float, integer, or vector constant, spill to a
5266 // constant pool entry to get its address.
5267 Value *OpVal = OpInfo.CallOperandVal;
5268 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5269 isa<ConstantVector>(OpVal)) {
5270 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5271 TLI.getPointerTy());
5273 // Otherwise, create a stack slot and emit a store to it before the
5275 const Type *Ty = OpVal->getType();
5276 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
5277 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5278 MachineFunction &MF = DAG.getMachineFunction();
5279 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5280 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5281 Chain = DAG.getStore(Chain, getCurDebugLoc(),
5282 OpInfo.CallOperand, StackSlot, NULL, 0);
5283 OpInfo.CallOperand = StackSlot;
5286 // There is no longer a Value* corresponding to this operand.
5287 OpInfo.CallOperandVal = 0;
5288 // It is now an indirect operand.
5289 OpInfo.isIndirect = true;
5292 // If this constraint is for a specific register, allocate it before
5294 if (OpInfo.ConstraintType == TargetLowering::C_Register)
5295 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5297 ConstraintInfos.clear();
5300 // Second pass - Loop over all of the operands, assigning virtual or physregs
5301 // to register class operands.
5302 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5303 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5305 // C_Register operands have already been allocated, Other/Memory don't need
5307 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
5308 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5311 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5312 std::vector<SDValue> AsmNodeOperands;
5313 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5314 AsmNodeOperands.push_back(
5315 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
5318 // Loop over all of the inputs, copying the operand values into the
5319 // appropriate registers and processing the output regs.
5320 RegsForValue RetValRegs;
5322 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5323 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
5325 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5326 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5328 switch (OpInfo.Type) {
5329 case InlineAsm::isOutput: {
5330 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5331 OpInfo.ConstraintType != TargetLowering::C_Register) {
5332 // Memory output, or 'other' output (e.g. 'X' constraint).
5333 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5335 // Add information to the INLINEASM node to know about this output.
5336 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5337 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5338 TLI.getPointerTy()));
5339 AsmNodeOperands.push_back(OpInfo.CallOperand);
5343 // Otherwise, this is a register or register class output.
5345 // Copy the output from the appropriate register. Find a register that
5347 if (OpInfo.AssignedRegs.Regs.empty()) {
5348 llvm_report_error("Couldn't allocate output reg for"
5349 " constraint '" + OpInfo.ConstraintCode + "'!");
5352 // If this is an indirect operand, store through the pointer after the
5354 if (OpInfo.isIndirect) {
5355 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5356 OpInfo.CallOperandVal));
5358 // This is the result value of the call.
5359 assert(CS.getType() != Type::getVoidTy(*DAG.getContext()) &&
5361 // Concatenate this output onto the outputs list.
5362 RetValRegs.append(OpInfo.AssignedRegs);
5365 // Add information to the INLINEASM node to know that this register is
5367 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5368 6 /* EARLYCLOBBER REGDEF */ :
5372 DAG, AsmNodeOperands);
5375 case InlineAsm::isInput: {
5376 SDValue InOperandVal = OpInfo.CallOperand;
5378 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
5379 // If this is required to match an output register we have already set,
5380 // just use its register.
5381 unsigned OperandNo = OpInfo.getMatchedOperand();
5383 // Scan until we find the definition we already emitted of this operand.
5384 // When we find it, create a RegsForValue operand.
5385 unsigned CurOp = 2; // The first operand.
5386 for (; OperandNo; --OperandNo) {
5387 // Advance to the next operand.
5389 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5390 assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5391 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5392 (OpFlag & 7) == 4 /*MEM*/) &&
5393 "Skipped past definitions?");
5394 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
5398 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5399 if ((OpFlag & 7) == 2 /*REGDEF*/
5400 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5401 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
5402 if (OpInfo.isIndirect) {
5403 llvm_report_error("Don't know how to handle tied indirect "
5404 "register inputs yet!");
5406 RegsForValue MatchedRegs;
5407 MatchedRegs.TLI = &TLI;
5408 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5409 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5410 MatchedRegs.RegVTs.push_back(RegVT);
5411 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
5412 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
5415 push_back(RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
5417 // Use the produced MatchedRegs object to
5418 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5420 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5421 true, OpInfo.getMatchedOperand(),
5422 DAG, AsmNodeOperands);
5425 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5426 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5427 "Unexpected number of operands");
5428 // Add information to the INLINEASM node to know about this input.
5429 // See InlineAsm.h isUseOperandTiedToDef.
5430 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
5431 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
5432 TLI.getPointerTy()));
5433 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5438 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5439 assert(!OpInfo.isIndirect &&
5440 "Don't know how to handle indirect other inputs yet!");
5442 std::vector<SDValue> Ops;
5443 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
5444 hasMemory, Ops, DAG);
5446 llvm_report_error("Invalid operand for inline asm"
5447 " constraint '" + OpInfo.ConstraintCode + "'!");
5450 // Add information to the INLINEASM node to know about this input.
5451 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
5452 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5453 TLI.getPointerTy()));
5454 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5456 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5457 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5458 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5459 "Memory operands expect pointer values");
5461 // Add information to the INLINEASM node to know about this input.
5462 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5463 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5464 TLI.getPointerTy()));
5465 AsmNodeOperands.push_back(InOperandVal);
5469 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5470 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5471 "Unknown constraint type!");
5472 assert(!OpInfo.isIndirect &&
5473 "Don't know how to handle indirect register inputs yet!");
5475 // Copy the input into the appropriate registers.
5476 if (OpInfo.AssignedRegs.Regs.empty()) {
5477 llvm_report_error("Couldn't allocate input reg for"
5478 " constraint '"+ OpInfo.ConstraintCode +"'!");
5481 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5484 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
5485 DAG, AsmNodeOperands);
5488 case InlineAsm::isClobber: {
5489 // Add the clobbered value to the operand list, so that the register
5490 // allocator is aware that the physreg got clobbered.
5491 if (!OpInfo.AssignedRegs.Regs.empty())
5492 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
5493 false, 0, DAG,AsmNodeOperands);
5499 // Finish up input operands.
5500 AsmNodeOperands[0] = Chain;
5501 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5503 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
5504 DAG.getVTList(MVT::Other, MVT::Flag),
5505 &AsmNodeOperands[0], AsmNodeOperands.size());
5506 Flag = Chain.getValue(1);
5508 // If this asm returns a register value, copy the result from that register
5509 // and set it as the value of the call.
5510 if (!RetValRegs.Regs.empty()) {
5511 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5514 // FIXME: Why don't we do this for inline asms with MRVs?
5515 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5516 EVT ResultType = TLI.getValueType(CS.getType());
5518 // If any of the results of the inline asm is a vector, it may have the
5519 // wrong width/num elts. This can happen for register classes that can
5520 // contain multiple different value types. The preg or vreg allocated may
5521 // not have the same VT as was expected. Convert it to the right type
5522 // with bit_convert.
5523 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5524 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5527 } else if (ResultType != Val.getValueType() &&
5528 ResultType.isInteger() && Val.getValueType().isInteger()) {
5529 // If a result value was tied to an input value, the computed result may
5530 // have a wider width than the expected result. Extract the relevant
5532 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
5535 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
5538 setValue(CS.getInstruction(), Val);
5539 // Don't need to use this as a chain in this case.
5540 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5544 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5546 // Process indirect outputs, first output all of the flagged copies out of
5548 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5549 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5550 Value *Ptr = IndirectStoresToEmit[i].second;
5551 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5553 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5557 // Emit the non-flagged stores from the physregs.
5558 SmallVector<SDValue, 8> OutChains;
5559 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5560 OutChains.push_back(DAG.getStore(Chain, getCurDebugLoc(),
5561 StoresToEmit[i].first,
5562 getValue(StoresToEmit[i].second),
5563 StoresToEmit[i].second, 0));
5564 if (!OutChains.empty())
5565 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
5566 &OutChains[0], OutChains.size());
5570 void SelectionDAGLowering::visitVAStart(CallInst &I) {
5571 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
5572 MVT::Other, getRoot(),
5573 getValue(I.getOperand(1)),
5574 DAG.getSrcValue(I.getOperand(1))));
5577 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
5578 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5579 getRoot(), getValue(I.getOperand(0)),
5580 DAG.getSrcValue(I.getOperand(0)));
5582 DAG.setRoot(V.getValue(1));
5585 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
5586 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
5587 MVT::Other, getRoot(),
5588 getValue(I.getOperand(1)),
5589 DAG.getSrcValue(I.getOperand(1))));
5592 void SelectionDAGLowering::visitVACopy(CallInst &I) {
5593 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
5594 MVT::Other, getRoot(),
5595 getValue(I.getOperand(1)),
5596 getValue(I.getOperand(2)),
5597 DAG.getSrcValue(I.getOperand(1)),
5598 DAG.getSrcValue(I.getOperand(2))));
5601 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
5602 /// implementation, which just calls LowerCall.
5603 /// FIXME: When all targets are
5604 /// migrated to using LowerCall, this hook should be integrated into SDISel.
5605 std::pair<SDValue, SDValue>
5606 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5607 bool RetSExt, bool RetZExt, bool isVarArg,
5608 bool isInreg, unsigned NumFixedArgs,
5609 CallingConv::ID CallConv, bool isTailCall,
5610 bool isReturnValueUsed,
5612 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
5614 assert((!isTailCall || PerformTailCallOpt) &&
5615 "isTailCall set when tail-call optimizations are disabled!");
5617 // Handle all of the outgoing arguments.
5618 SmallVector<ISD::OutputArg, 32> Outs;
5619 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5620 SmallVector<EVT, 4> ValueVTs;
5621 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5622 for (unsigned Value = 0, NumValues = ValueVTs.size();
5623 Value != NumValues; ++Value) {
5624 EVT VT = ValueVTs[Value];
5625 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
5626 SDValue Op = SDValue(Args[i].Node.getNode(),
5627 Args[i].Node.getResNo() + Value);
5628 ISD::ArgFlagsTy Flags;
5629 unsigned OriginalAlignment =
5630 getTargetData()->getABITypeAlignment(ArgTy);
5636 if (Args[i].isInReg)
5640 if (Args[i].isByVal) {
5642 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5643 const Type *ElementTy = Ty->getElementType();
5644 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5645 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
5646 // For ByVal, alignment should come from FE. BE will guess if this
5647 // info is not there but there are cases it cannot get right.
5648 if (Args[i].Alignment)
5649 FrameAlign = Args[i].Alignment;
5650 Flags.setByValAlign(FrameAlign);
5651 Flags.setByValSize(FrameSize);
5655 Flags.setOrigAlign(OriginalAlignment);
5657 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
5658 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
5659 SmallVector<SDValue, 4> Parts(NumParts);
5660 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5663 ExtendKind = ISD::SIGN_EXTEND;
5664 else if (Args[i].isZExt)
5665 ExtendKind = ISD::ZERO_EXTEND;
5667 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5669 for (unsigned j = 0; j != NumParts; ++j) {
5670 // if it isn't first piece, alignment must be 1
5671 ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs);
5672 if (NumParts > 1 && j == 0)
5673 MyFlags.Flags.setSplit();
5675 MyFlags.Flags.setOrigAlign(1);
5677 Outs.push_back(MyFlags);
5682 // Handle the incoming return values from the call.
5683 SmallVector<ISD::InputArg, 32> Ins;
5684 SmallVector<EVT, 4> RetTys;
5685 ComputeValueVTs(*this, RetTy, RetTys);
5686 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5688 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5689 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
5690 for (unsigned i = 0; i != NumRegs; ++i) {
5691 ISD::InputArg MyFlags;
5692 MyFlags.VT = RegisterVT;
5693 MyFlags.Used = isReturnValueUsed;
5695 MyFlags.Flags.setSExt();
5697 MyFlags.Flags.setZExt();
5699 MyFlags.Flags.setInReg();
5700 Ins.push_back(MyFlags);
5704 // Check if target-dependent constraints permit a tail call here.
5705 // Target-independent constraints should be checked by the caller.
5707 !IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, Ins, DAG))
5710 SmallVector<SDValue, 4> InVals;
5711 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
5712 Outs, Ins, dl, DAG, InVals);
5714 // Verify that the target's LowerCall behaved as expected.
5715 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
5716 "LowerCall didn't return a valid chain!");
5717 assert((!isTailCall || InVals.empty()) &&
5718 "LowerCall emitted a return value for a tail call!");
5719 assert((isTailCall || InVals.size() == Ins.size()) &&
5720 "LowerCall didn't emit the correct number of values!");
5721 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5722 assert(InVals[i].getNode() &&
5723 "LowerCall emitted a null value!");
5724 assert(Ins[i].VT == InVals[i].getValueType() &&
5725 "LowerCall emitted a value with the wrong type!");
5728 // For a tail call, the return value is merely live-out and there aren't
5729 // any nodes in the DAG representing it. Return a special value to
5730 // indicate that a tail call has been emitted and no more Instructions
5731 // should be processed in the current block.
5734 return std::make_pair(SDValue(), SDValue());
5737 // Collect the legal value parts into potentially illegal values
5738 // that correspond to the original function's return values.
5739 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5741 AssertOp = ISD::AssertSext;
5743 AssertOp = ISD::AssertZext;
5744 SmallVector<SDValue, 4> ReturnValues;
5745 unsigned CurReg = 0;
5746 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5748 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5749 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
5751 SDValue ReturnValue =
5752 getCopyFromParts(DAG, dl, &InVals[CurReg], NumRegs, RegisterVT, VT,
5754 ReturnValues.push_back(ReturnValue);
5758 // For a function returning void, there is no return value. We can't create
5759 // such a node, so we just return a null return value in that case. In
5760 // that case, nothing will actualy look at the value.
5761 if (ReturnValues.empty())
5762 return std::make_pair(SDValue(), Chain);
5764 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
5765 DAG.getVTList(&RetTys[0], RetTys.size()),
5766 &ReturnValues[0], ReturnValues.size());
5768 return std::make_pair(Res, Chain);
5771 void TargetLowering::LowerOperationWrapper(SDNode *N,
5772 SmallVectorImpl<SDValue> &Results,
5773 SelectionDAG &DAG) {
5774 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
5776 Results.push_back(Res);
5779 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5780 llvm_unreachable("LowerOperation not implemented for this target!");
5785 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5786 SDValue Op = getValue(V);
5787 assert((Op.getOpcode() != ISD::CopyFromReg ||
5788 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5789 "Copy from a reg to the same reg!");
5790 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5792 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
5793 SDValue Chain = DAG.getEntryNode();
5794 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
5795 PendingExports.push_back(Chain);
5798 #include "llvm/CodeGen/SelectionDAGISel.h"
5800 void SelectionDAGISel::LowerArguments(BasicBlock *LLVMBB) {
5801 // If this is the entry block, emit arguments.
5802 Function &F = *LLVMBB->getParent();
5803 SelectionDAG &DAG = SDL->DAG;
5804 SDValue OldRoot = DAG.getRoot();
5805 DebugLoc dl = SDL->getCurDebugLoc();
5806 const TargetData *TD = TLI.getTargetData();
5807 SmallVector<ISD::InputArg, 16> Ins;
5809 // Check whether the function can return without sret-demotion.
5810 SmallVector<EVT, 4> OutVTs;
5811 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
5812 getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
5813 OutVTs, OutsFlags, TLI);
5814 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
5816 FLI.CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(), F.isVarArg(),
5817 OutVTs, OutsFlags, DAG);
5818 if (!FLI.CanLowerReturn) {
5819 // Put in an sret pointer parameter before all the other parameters.
5820 SmallVector<EVT, 1> ValueVTs;
5821 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5823 // NOTE: Assuming that a pointer will never break down to more than one VT
5825 ISD::ArgFlagsTy Flags;
5827 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), ValueVTs[0]);
5828 ISD::InputArg RetArg(Flags, RegisterVT, true);
5829 Ins.push_back(RetArg);
5832 // Set up the incoming argument description vector.
5834 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5835 I != E; ++I, ++Idx) {
5836 SmallVector<EVT, 4> ValueVTs;
5837 ComputeValueVTs(TLI, I->getType(), ValueVTs);
5838 bool isArgValueUsed = !I->use_empty();
5839 for (unsigned Value = 0, NumValues = ValueVTs.size();
5840 Value != NumValues; ++Value) {
5841 EVT VT = ValueVTs[Value];
5842 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
5843 ISD::ArgFlagsTy Flags;
5844 unsigned OriginalAlignment =
5845 TD->getABITypeAlignment(ArgTy);
5847 if (F.paramHasAttr(Idx, Attribute::ZExt))
5849 if (F.paramHasAttr(Idx, Attribute::SExt))
5851 if (F.paramHasAttr(Idx, Attribute::InReg))
5853 if (F.paramHasAttr(Idx, Attribute::StructRet))
5855 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
5857 const PointerType *Ty = cast<PointerType>(I->getType());
5858 const Type *ElementTy = Ty->getElementType();
5859 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
5860 unsigned FrameSize = TD->getTypeAllocSize(ElementTy);
5861 // For ByVal, alignment should be passed from FE. BE will guess if
5862 // this info is not there but there are cases it cannot get right.
5863 if (F.getParamAlignment(Idx))
5864 FrameAlign = F.getParamAlignment(Idx);
5865 Flags.setByValAlign(FrameAlign);
5866 Flags.setByValSize(FrameSize);
5868 if (F.paramHasAttr(Idx, Attribute::Nest))
5870 Flags.setOrigAlign(OriginalAlignment);
5872 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5873 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
5874 for (unsigned i = 0; i != NumRegs; ++i) {
5875 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
5876 if (NumRegs > 1 && i == 0)
5877 MyFlags.Flags.setSplit();
5878 // if it isn't first piece, alignment must be 1
5880 MyFlags.Flags.setOrigAlign(1);
5881 Ins.push_back(MyFlags);
5886 // Call the target to set up the argument values.
5887 SmallVector<SDValue, 8> InVals;
5888 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
5892 // Verify that the target's LowerFormalArguments behaved as expected.
5893 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
5894 "LowerFormalArguments didn't return a valid chain!");
5895 assert(InVals.size() == Ins.size() &&
5896 "LowerFormalArguments didn't emit the correct number of values!");
5897 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5898 assert(InVals[i].getNode() &&
5899 "LowerFormalArguments emitted a null value!");
5900 assert(Ins[i].VT == InVals[i].getValueType() &&
5901 "LowerFormalArguments emitted a value with the wrong type!");
5904 // Update the DAG with the new chain value resulting from argument lowering.
5905 DAG.setRoot(NewRoot);
5907 // Set up the argument values.
5910 if (!FLI.CanLowerReturn) {
5911 // Create a virtual register for the sret pointer, and put in a copy
5912 // from the sret argument into it.
5913 SmallVector<EVT, 1> ValueVTs;
5914 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5915 EVT VT = ValueVTs[0];
5916 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5917 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5918 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT,
5921 MachineFunction& MF = SDL->DAG.getMachineFunction();
5922 MachineRegisterInfo& RegInfo = MF.getRegInfo();
5923 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
5924 FLI.DemoteRegister = SRetReg;
5925 NewRoot = SDL->DAG.getCopyToReg(NewRoot, SDL->getCurDebugLoc(), SRetReg, ArgValue);
5926 DAG.setRoot(NewRoot);
5928 // i indexes lowered arguments. Bump it past the hidden sret argument.
5929 // Idx indexes LLVM arguments. Don't touch it.
5932 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5934 SmallVector<SDValue, 4> ArgValues;
5935 SmallVector<EVT, 4> ValueVTs;
5936 ComputeValueVTs(TLI, I->getType(), ValueVTs);
5937 unsigned NumValues = ValueVTs.size();
5938 for (unsigned Value = 0; Value != NumValues; ++Value) {
5939 EVT VT = ValueVTs[Value];
5940 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5941 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
5943 if (!I->use_empty()) {
5944 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5945 if (F.paramHasAttr(Idx, Attribute::SExt))
5946 AssertOp = ISD::AssertSext;
5947 else if (F.paramHasAttr(Idx, Attribute::ZExt))
5948 AssertOp = ISD::AssertZext;
5950 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
5951 PartVT, VT, AssertOp));
5955 if (!I->use_empty()) {
5956 SDL->setValue(I, DAG.getMergeValues(&ArgValues[0], NumValues,
5957 SDL->getCurDebugLoc()));
5958 // If this argument is live outside of the entry block, insert a copy from
5959 // whereever we got it to the vreg that other BB's will reference it as.
5960 SDL->CopyToExportRegsIfNeeded(I);
5963 assert(i == InVals.size() && "Argument register count mismatch!");
5965 // Finally, if the target has anything special to do, allow it to do so.
5966 // FIXME: this should insert code into the DAG!
5967 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5970 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5971 /// ensure constants are generated when needed. Remember the virtual registers
5972 /// that need to be added to the Machine PHI nodes as input. We cannot just
5973 /// directly add them, because expansion might result in multiple MBB's for one
5974 /// BB. As such, the start of the BB might correspond to a different MBB than
5978 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5979 TerminatorInst *TI = LLVMBB->getTerminator();
5981 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5983 // Check successor nodes' PHI nodes that expect a constant to be available
5985 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5986 BasicBlock *SuccBB = TI->getSuccessor(succ);
5987 if (!isa<PHINode>(SuccBB->begin())) continue;
5988 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5990 // If this terminator has multiple identical successors (common for
5991 // switches), only handle each succ once.
5992 if (!SuccsHandled.insert(SuccMBB)) continue;
5994 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5997 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5998 // nodes and Machine PHI nodes, but the incoming operands have not been
6000 for (BasicBlock::iterator I = SuccBB->begin();
6001 (PN = dyn_cast<PHINode>(I)); ++I) {
6002 // Ignore dead phi's.
6003 if (PN->use_empty()) continue;
6006 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6008 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
6009 unsigned &RegOut = SDL->ConstantsOut[C];
6011 RegOut = FuncInfo->CreateRegForValue(C);
6012 SDL->CopyValueToVirtualRegister(C, RegOut);
6016 Reg = FuncInfo->ValueMap[PHIOp];
6018 assert(isa<AllocaInst>(PHIOp) &&
6019 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
6020 "Didn't codegen value into a register!??");
6021 Reg = FuncInfo->CreateRegForValue(PHIOp);
6022 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
6026 // Remember that this register needs to added to the machine PHI node as
6027 // the input for this MBB.
6028 SmallVector<EVT, 4> ValueVTs;
6029 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6030 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
6031 EVT VT = ValueVTs[vti];
6032 unsigned NumRegisters = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6033 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
6034 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
6035 Reg += NumRegisters;
6039 SDL->ConstantsOut.clear();
6042 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
6043 /// supports legal types, and it emits MachineInstrs directly instead of
6044 /// creating SelectionDAG nodes.
6047 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
6049 TerminatorInst *TI = LLVMBB->getTerminator();
6051 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6052 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
6054 // Check successor nodes' PHI nodes that expect a constant to be available
6056 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6057 BasicBlock *SuccBB = TI->getSuccessor(succ);
6058 if (!isa<PHINode>(SuccBB->begin())) continue;
6059 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
6061 // If this terminator has multiple identical successors (common for
6062 // switches), only handle each succ once.
6063 if (!SuccsHandled.insert(SuccMBB)) continue;
6065 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6068 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6069 // nodes and Machine PHI nodes, but the incoming operands have not been
6071 for (BasicBlock::iterator I = SuccBB->begin();
6072 (PN = dyn_cast<PHINode>(I)); ++I) {
6073 // Ignore dead phi's.
6074 if (PN->use_empty()) continue;
6076 // Only handle legal types. Two interesting things to note here. First,
6077 // by bailing out early, we may leave behind some dead instructions,
6078 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
6079 // own moves. Second, this check is necessary becuase FastISel doesn't
6080 // use CreateRegForValue to create registers, so it always creates
6081 // exactly one register for each non-void instruction.
6082 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
6083 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
6086 VT = TLI.getTypeToTransformTo(*CurDAG->getContext(), VT);
6088 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6093 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6095 unsigned Reg = F->getRegForValue(PHIOp);
6097 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
6100 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));