1 //===-- SelectionDAGBuild.cpp - Selection-DAG building --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements routines for translating from LLVM IR into SelectionDAG IR.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "isel"
15 #include "SelectionDAGBuild.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/Analysis/AliasAnalysis.h"
19 #include "llvm/Constants.h"
20 #include "llvm/CallingConv.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/InlineAsm.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/IntrinsicInst.h"
28 #include "llvm/Module.h"
29 #include "llvm/CodeGen/FastISel.h"
30 #include "llvm/CodeGen/GCStrategy.h"
31 #include "llvm/CodeGen/GCMetadata.h"
32 #include "llvm/CodeGen/MachineFunction.h"
33 #include "llvm/CodeGen/MachineFrameInfo.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfo.h"
37 #include "llvm/CodeGen/MachineRegisterInfo.h"
38 #include "llvm/CodeGen/PseudoSourceValue.h"
39 #include "llvm/CodeGen/SelectionDAG.h"
40 #include "llvm/CodeGen/DwarfWriter.h"
41 #include "llvm/Analysis/DebugInfo.h"
42 #include "llvm/Target/TargetRegisterInfo.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Target/TargetFrameInfo.h"
45 #include "llvm/Target/TargetInstrInfo.h"
46 #include "llvm/Target/TargetIntrinsicInfo.h"
47 #include "llvm/Target/TargetLowering.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/CommandLine.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/raw_ostream.h"
58 /// LimitFloatPrecision - Generate low-precision inline sequences for
59 /// some float libcalls (6, 8 or 12 bits).
60 static unsigned LimitFloatPrecision;
62 static cl::opt<unsigned, true>
63 LimitFPPrecision("limit-float-precision",
64 cl::desc("Generate low-precision inline sequences "
65 "for some float libcalls"),
66 cl::location(LimitFloatPrecision),
69 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
70 /// of insertvalue or extractvalue indices that identify a member, return
71 /// the linearized index of the start of the member.
73 static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
74 const unsigned *Indices,
75 const unsigned *IndicesEnd,
76 unsigned CurIndex = 0) {
77 // Base case: We're done.
78 if (Indices && Indices == IndicesEnd)
81 // Given a struct type, recursively traverse the elements.
82 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
83 for (StructType::element_iterator EB = STy->element_begin(),
85 EE = STy->element_end();
87 if (Indices && *Indices == unsigned(EI - EB))
88 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
89 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
93 // Given an array type, recursively traverse the elements.
94 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
95 const Type *EltTy = ATy->getElementType();
96 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
97 if (Indices && *Indices == i)
98 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
99 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
103 // We haven't found the type we're looking for, so keep searching.
107 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
108 /// MVTs that represent all the individual underlying
109 /// non-aggregate types that comprise it.
111 /// If Offsets is non-null, it points to a vector to be filled in
112 /// with the in-memory offsets of each of the individual values.
114 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
115 SmallVectorImpl<MVT> &ValueVTs,
116 SmallVectorImpl<uint64_t> *Offsets = 0,
117 uint64_t StartingOffset = 0) {
118 // Given a struct type, recursively traverse the elements.
119 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
120 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
121 for (StructType::element_iterator EB = STy->element_begin(),
123 EE = STy->element_end();
125 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
126 StartingOffset + SL->getElementOffset(EI - EB));
129 // Given an array type, recursively traverse the elements.
130 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
131 const Type *EltTy = ATy->getElementType();
132 uint64_t EltSize = TLI.getTargetData()->getTypePaddedSize(EltTy);
133 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
134 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
135 StartingOffset + i * EltSize);
138 // Base case: we can get an MVT for this LLVM IR type.
139 ValueVTs.push_back(TLI.getValueType(Ty));
141 Offsets->push_back(StartingOffset);
145 /// RegsForValue - This struct represents the registers (physical or virtual)
146 /// that a particular set of values is assigned, and the type information about
147 /// the value. The most common situation is to represent one value at a time,
148 /// but struct or array values are handled element-wise as multiple values.
149 /// The splitting of aggregates is performed recursively, so that we never
150 /// have aggregate-typed registers. The values at this point do not necessarily
151 /// have legal types, so each value may require one or more registers of some
154 struct VISIBILITY_HIDDEN RegsForValue {
155 /// TLI - The TargetLowering object.
157 const TargetLowering *TLI;
159 /// ValueVTs - The value types of the values, which may not be legal, and
160 /// may need be promoted or synthesized from one or more registers.
162 SmallVector<MVT, 4> ValueVTs;
164 /// RegVTs - The value types of the registers. This is the same size as
165 /// ValueVTs and it records, for each value, what the type of the assigned
166 /// register or registers are. (Individual values are never synthesized
167 /// from more than one type of register.)
169 /// With virtual registers, the contents of RegVTs is redundant with TLI's
170 /// getRegisterType member function, however when with physical registers
171 /// it is necessary to have a separate record of the types.
173 SmallVector<MVT, 4> RegVTs;
175 /// Regs - This list holds the registers assigned to the values.
176 /// Each legal or promoted value requires one register, and each
177 /// expanded value requires multiple registers.
179 SmallVector<unsigned, 4> Regs;
181 RegsForValue() : TLI(0) {}
183 RegsForValue(const TargetLowering &tli,
184 const SmallVector<unsigned, 4> ®s,
185 MVT regvt, MVT valuevt)
186 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
187 RegsForValue(const TargetLowering &tli,
188 const SmallVector<unsigned, 4> ®s,
189 const SmallVector<MVT, 4> ®vts,
190 const SmallVector<MVT, 4> &valuevts)
191 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
192 RegsForValue(const TargetLowering &tli,
193 unsigned Reg, const Type *Ty) : TLI(&tli) {
194 ComputeValueVTs(tli, Ty, ValueVTs);
196 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
197 MVT ValueVT = ValueVTs[Value];
198 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
199 MVT RegisterVT = TLI->getRegisterType(ValueVT);
200 for (unsigned i = 0; i != NumRegs; ++i)
201 Regs.push_back(Reg + i);
202 RegVTs.push_back(RegisterVT);
207 /// append - Add the specified values to this one.
208 void append(const RegsForValue &RHS) {
210 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
211 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
212 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
216 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
217 /// this value and returns the result as a ValueVTs value. This uses
218 /// Chain/Flag as the input and updates them for the output Chain/Flag.
219 /// If the Flag pointer is NULL, no flag is used.
220 SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
221 SDValue &Chain, SDValue *Flag) const;
223 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
224 /// specified value into the registers specified by this object. This uses
225 /// Chain/Flag as the input and updates them for the output Chain/Flag.
226 /// If the Flag pointer is NULL, no flag is used.
227 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
228 SDValue &Chain, SDValue *Flag) const;
230 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
231 /// operand list. This adds the code marker, matching input operand index
232 /// (if applicable), and includes the number of values added into it.
233 void AddInlineAsmOperands(unsigned Code,
234 bool HasMatching, unsigned MatchingIdx,
235 SelectionDAG &DAG, std::vector<SDValue> &Ops) const;
239 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
240 /// PHI nodes or outside of the basic block that defines it, or used by a
241 /// switch or atomic instruction, which may expand to multiple basic blocks.
242 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
243 if (isa<PHINode>(I)) return true;
244 BasicBlock *BB = I->getParent();
245 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
246 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
247 // FIXME: Remove switchinst special case.
248 isa<SwitchInst>(*UI))
253 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
254 /// entry block, return true. This includes arguments used by switches, since
255 /// the switch may expand into multiple basic blocks.
256 static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
257 // With FastISel active, we may be splitting blocks, so force creation
258 // of virtual registers for all non-dead arguments.
259 // Don't force virtual registers for byval arguments though, because
260 // fast-isel can't handle those in all cases.
261 if (EnableFastISel && !A->hasByValAttr())
262 return A->use_empty();
264 BasicBlock *Entry = A->getParent()->begin();
265 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
266 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
267 return false; // Use not in entry block.
271 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
275 void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
277 bool EnableFastISel) {
280 RegInfo = &MF->getRegInfo();
282 // Create a vreg for each argument register that is not dead and is used
283 // outside of the entry block for the function.
284 for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
286 if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
287 InitializeRegForValue(AI);
289 // Initialize the mapping of values to registers. This is only set up for
290 // instruction values that are used outside of the block that defines
292 Function::iterator BB = Fn->begin(), EB = Fn->end();
293 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
294 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
295 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
296 const Type *Ty = AI->getAllocatedType();
297 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
299 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
302 TySize *= CUI->getZExtValue(); // Get total allocated size.
303 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
304 StaticAllocaMap[AI] =
305 MF->getFrameInfo()->CreateStackObject(TySize, Align);
308 for (; BB != EB; ++BB)
309 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
310 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
311 if (!isa<AllocaInst>(I) ||
312 !StaticAllocaMap.count(cast<AllocaInst>(I)))
313 InitializeRegForValue(I);
315 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
316 // also creates the initial PHI MachineInstrs, though none of the input
317 // operands are populated.
318 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
319 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
323 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
327 for (BasicBlock::iterator
328 I = BB->begin(), E = BB->end(); I != E; ++I) {
329 if (CallInst *CI = dyn_cast<CallInst>(I)) {
330 if (Function *F = CI->getCalledFunction()) {
331 switch (F->getIntrinsicID()) {
333 case Intrinsic::dbg_stoppoint: {
334 DwarfWriter *DW = DAG.getDwarfWriter();
335 DbgStopPointInst *SPI = cast<DbgStopPointInst>(I);
337 if (DW && DW->ValidDebugInfo(SPI->getContext())) {
338 DICompileUnit CU(cast<GlobalVariable>(SPI->getContext()));
340 unsigned SrcFile = DW->getOrCreateSourceID(CU.getDirectory(Dir),
342 unsigned idx = MF->getOrCreateDebugLocID(SrcFile,
345 DL = DebugLoc::get(idx);
350 case Intrinsic::dbg_func_start: {
351 DwarfWriter *DW = DAG.getDwarfWriter();
353 DbgFuncStartInst *FSI = cast<DbgFuncStartInst>(I);
354 Value *SP = FSI->getSubprogram();
356 if (DW->ValidDebugInfo(SP)) {
357 DISubprogram Subprogram(cast<GlobalVariable>(SP));
358 DICompileUnit CU(Subprogram.getCompileUnit());
360 unsigned SrcFile = DW->getOrCreateSourceID(CU.getDirectory(Dir),
362 unsigned Line = Subprogram.getLineNumber();
363 DL = DebugLoc::get(MF->getOrCreateDebugLocID(SrcFile, Line, 0));
373 PN = dyn_cast<PHINode>(I);
374 if (!PN || PN->use_empty()) continue;
376 unsigned PHIReg = ValueMap[PN];
377 assert(PHIReg && "PHI node does not have an assigned virtual register!");
379 SmallVector<MVT, 4> ValueVTs;
380 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
381 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
382 MVT VT = ValueVTs[vti];
383 unsigned NumRegisters = TLI.getNumRegisters(VT);
384 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
385 for (unsigned i = 0; i != NumRegisters; ++i)
386 BuildMI(MBB, DL, TII->get(TargetInstrInfo::PHI), PHIReg + i);
387 PHIReg += NumRegisters;
393 unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
394 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
397 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
398 /// the correctly promoted or expanded types. Assign these registers
399 /// consecutive vreg numbers and return the first assigned number.
401 /// In the case that the given value has struct or array type, this function
402 /// will assign registers for each member or element.
404 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
405 SmallVector<MVT, 4> ValueVTs;
406 ComputeValueVTs(TLI, V->getType(), ValueVTs);
408 unsigned FirstReg = 0;
409 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
410 MVT ValueVT = ValueVTs[Value];
411 MVT RegisterVT = TLI.getRegisterType(ValueVT);
413 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
414 for (unsigned i = 0; i != NumRegs; ++i) {
415 unsigned R = MakeReg(RegisterVT);
416 if (!FirstReg) FirstReg = R;
422 /// getCopyFromParts - Create a value that contains the specified legal parts
423 /// combined into the value they represent. If the parts combine to a type
424 /// larger then ValueVT then AssertOp can be used to specify whether the extra
425 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
426 /// (ISD::AssertSext).
427 static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
428 const SDValue *Parts,
429 unsigned NumParts, MVT PartVT, MVT ValueVT,
430 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
431 assert(NumParts > 0 && "No parts to assemble!");
432 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
433 SDValue Val = Parts[0];
436 // Assemble the value from multiple parts.
437 if (!ValueVT.isVector()) {
438 unsigned PartBits = PartVT.getSizeInBits();
439 unsigned ValueBits = ValueVT.getSizeInBits();
441 // Assemble the power of 2 part.
442 unsigned RoundParts = NumParts & (NumParts - 1) ?
443 1 << Log2_32(NumParts) : NumParts;
444 unsigned RoundBits = PartBits * RoundParts;
445 MVT RoundVT = RoundBits == ValueBits ?
446 ValueVT : MVT::getIntegerVT(RoundBits);
449 MVT HalfVT = ValueVT.isInteger() ?
450 MVT::getIntegerVT(RoundBits/2) :
451 MVT::getFloatingPointVT(RoundBits/2);
453 if (RoundParts > 2) {
454 Lo = getCopyFromParts(DAG, dl, Parts, RoundParts/2, PartVT, HalfVT);
455 Hi = getCopyFromParts(DAG, dl, Parts+RoundParts/2, RoundParts/2,
458 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
459 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
461 if (TLI.isBigEndian())
463 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
465 if (RoundParts < NumParts) {
466 // Assemble the trailing non-power-of-2 part.
467 unsigned OddParts = NumParts - RoundParts;
468 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
469 Hi = getCopyFromParts(DAG, dl,
470 Parts+RoundParts, OddParts, PartVT, OddVT);
472 // Combine the round and odd parts.
474 if (TLI.isBigEndian())
476 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
477 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
478 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
479 DAG.getConstant(Lo.getValueType().getSizeInBits(),
480 TLI.getPointerTy()));
481 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
482 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
485 // Handle a multi-element vector.
486 MVT IntermediateVT, RegisterVT;
487 unsigned NumIntermediates;
489 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
491 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
492 NumParts = NumRegs; // Silence a compiler warning.
493 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
494 assert(RegisterVT == Parts[0].getValueType() &&
495 "Part type doesn't match part!");
497 // Assemble the parts into intermediate operands.
498 SmallVector<SDValue, 8> Ops(NumIntermediates);
499 if (NumIntermediates == NumParts) {
500 // If the register was not expanded, truncate or copy the value,
502 for (unsigned i = 0; i != NumParts; ++i)
503 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
504 PartVT, IntermediateVT);
505 } else if (NumParts > 0) {
506 // If the intermediate type was expanded, build the intermediate operands
508 assert(NumParts % NumIntermediates == 0 &&
509 "Must expand into a divisible number of parts!");
510 unsigned Factor = NumParts / NumIntermediates;
511 for (unsigned i = 0; i != NumIntermediates; ++i)
512 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
513 PartVT, IntermediateVT);
516 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
518 Val = DAG.getNode(IntermediateVT.isVector() ?
519 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
520 ValueVT, &Ops[0], NumIntermediates);
524 // There is now one part, held in Val. Correct it to match ValueVT.
525 PartVT = Val.getValueType();
527 if (PartVT == ValueVT)
530 if (PartVT.isVector()) {
531 assert(ValueVT.isVector() && "Unknown vector conversion!");
532 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
535 if (ValueVT.isVector()) {
536 assert(ValueVT.getVectorElementType() == PartVT &&
537 ValueVT.getVectorNumElements() == 1 &&
538 "Only trivial scalar-to-vector conversions should get here!");
539 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
542 if (PartVT.isInteger() &&
543 ValueVT.isInteger()) {
544 if (ValueVT.bitsLT(PartVT)) {
545 // For a truncate, see if we have any information to
546 // indicate whether the truncated bits will always be
547 // zero or sign-extension.
548 if (AssertOp != ISD::DELETED_NODE)
549 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
550 DAG.getValueType(ValueVT));
551 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
553 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
557 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
558 if (ValueVT.bitsLT(Val.getValueType()))
559 // FP_ROUND's are always exact here.
560 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
561 DAG.getIntPtrConstant(1));
562 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
565 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
566 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
568 assert(0 && "Unknown mismatch!");
572 /// getCopyToParts - Create a series of nodes that contain the specified value
573 /// split into legal parts. If the parts contain more bits than Val, then, for
574 /// integers, ExtendKind can be used to specify how to generate the extra bits.
575 static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, SDValue Val,
576 SDValue *Parts, unsigned NumParts, MVT PartVT,
577 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
578 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
579 MVT PtrVT = TLI.getPointerTy();
580 MVT ValueVT = Val.getValueType();
581 unsigned PartBits = PartVT.getSizeInBits();
582 unsigned OrigNumParts = NumParts;
583 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
588 if (!ValueVT.isVector()) {
589 if (PartVT == ValueVT) {
590 assert(NumParts == 1 && "No-op copy with multiple parts!");
595 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
596 // If the parts cover more bits than the value has, promote the value.
597 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
598 assert(NumParts == 1 && "Do not know what to promote to!");
599 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
600 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
601 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
602 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
604 assert(0 && "Unknown mismatch!");
606 } else if (PartBits == ValueVT.getSizeInBits()) {
607 // Different types of the same size.
608 assert(NumParts == 1 && PartVT != ValueVT);
609 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
610 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
611 // If the parts cover less bits than value has, truncate the value.
612 if (PartVT.isInteger() && ValueVT.isInteger()) {
613 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
614 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
616 assert(0 && "Unknown mismatch!");
620 // The value may have changed - recompute ValueVT.
621 ValueVT = Val.getValueType();
622 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
623 "Failed to tile the value with PartVT!");
626 assert(PartVT == ValueVT && "Type conversion failed!");
631 // Expand the value into multiple parts.
632 if (NumParts & (NumParts - 1)) {
633 // The number of parts is not a power of 2. Split off and copy the tail.
634 assert(PartVT.isInteger() && ValueVT.isInteger() &&
635 "Do not know what to expand to!");
636 unsigned RoundParts = 1 << Log2_32(NumParts);
637 unsigned RoundBits = RoundParts * PartBits;
638 unsigned OddParts = NumParts - RoundParts;
639 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
640 DAG.getConstant(RoundBits,
641 TLI.getPointerTy()));
642 getCopyToParts(DAG, dl, OddVal, Parts + RoundParts, OddParts, PartVT);
643 if (TLI.isBigEndian())
644 // The odd parts were reversed by getCopyToParts - unreverse them.
645 std::reverse(Parts + RoundParts, Parts + NumParts);
646 NumParts = RoundParts;
647 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
648 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
651 // The number of parts is a power of 2. Repeatedly bisect the value using
653 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
654 MVT::getIntegerVT(ValueVT.getSizeInBits()),
656 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
657 for (unsigned i = 0; i < NumParts; i += StepSize) {
658 unsigned ThisBits = StepSize * PartBits / 2;
659 MVT ThisVT = MVT::getIntegerVT (ThisBits);
660 SDValue &Part0 = Parts[i];
661 SDValue &Part1 = Parts[i+StepSize/2];
663 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
665 DAG.getConstant(1, PtrVT));
666 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
668 DAG.getConstant(0, PtrVT));
670 if (ThisBits == PartBits && ThisVT != PartVT) {
671 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
673 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
679 if (TLI.isBigEndian())
680 std::reverse(Parts, Parts + OrigNumParts);
687 if (PartVT != ValueVT) {
688 if (PartVT.isVector()) {
689 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
691 assert(ValueVT.getVectorElementType() == PartVT &&
692 ValueVT.getVectorNumElements() == 1 &&
693 "Only trivial vector-to-scalar conversions should get here!");
694 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
696 DAG.getConstant(0, PtrVT));
704 // Handle a multi-element vector.
705 MVT IntermediateVT, RegisterVT;
706 unsigned NumIntermediates;
707 unsigned NumRegs = TLI
708 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
710 unsigned NumElements = ValueVT.getVectorNumElements();
712 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
713 NumParts = NumRegs; // Silence a compiler warning.
714 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
716 // Split the vector into intermediate operands.
717 SmallVector<SDValue, 8> Ops(NumIntermediates);
718 for (unsigned i = 0; i != NumIntermediates; ++i)
719 if (IntermediateVT.isVector())
720 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
722 DAG.getConstant(i * (NumElements / NumIntermediates),
725 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
727 DAG.getConstant(i, PtrVT));
729 // Split the intermediate operands into legal parts.
730 if (NumParts == NumIntermediates) {
731 // If the register was not expanded, promote or copy the value,
733 for (unsigned i = 0; i != NumParts; ++i)
734 getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
735 } else if (NumParts > 0) {
736 // If the intermediate type was expanded, split each the value into
738 assert(NumParts % NumIntermediates == 0 &&
739 "Must expand into a divisible number of parts!");
740 unsigned Factor = NumParts / NumIntermediates;
741 for (unsigned i = 0; i != NumIntermediates; ++i)
742 getCopyToParts(DAG, dl, Ops[i], &Parts[i * Factor], Factor, PartVT);
747 void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
750 TD = DAG.getTarget().getTargetData();
753 /// clear - Clear out the curret SelectionDAG and the associated
754 /// state and prepare this SelectionDAGLowering object to be used
755 /// for a new block. This doesn't clear out information about
756 /// additional blocks that are needed to complete switch lowering
757 /// or PHI node updating; that information is cleared out as it is
759 void SelectionDAGLowering::clear() {
761 PendingLoads.clear();
762 PendingExports.clear();
764 CurDebugLoc = DebugLoc::getUnknownLoc();
767 /// getRoot - Return the current virtual root of the Selection DAG,
768 /// flushing any PendingLoad items. This must be done before emitting
769 /// a store or any other node that may need to be ordered after any
770 /// prior load instructions.
772 SDValue SelectionDAGLowering::getRoot() {
773 if (PendingLoads.empty())
774 return DAG.getRoot();
776 if (PendingLoads.size() == 1) {
777 SDValue Root = PendingLoads[0];
779 PendingLoads.clear();
783 // Otherwise, we have to make a token factor node.
784 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
785 &PendingLoads[0], PendingLoads.size());
786 PendingLoads.clear();
791 /// getControlRoot - Similar to getRoot, but instead of flushing all the
792 /// PendingLoad items, flush all the PendingExports items. It is necessary
793 /// to do this before emitting a terminator instruction.
795 SDValue SelectionDAGLowering::getControlRoot() {
796 SDValue Root = DAG.getRoot();
798 if (PendingExports.empty())
801 // Turn all of the CopyToReg chains into one factored node.
802 if (Root.getOpcode() != ISD::EntryToken) {
803 unsigned i = 0, e = PendingExports.size();
804 for (; i != e; ++i) {
805 assert(PendingExports[i].getNode()->getNumOperands() > 1);
806 if (PendingExports[i].getNode()->getOperand(0) == Root)
807 break; // Don't add the root if we already indirectly depend on it.
811 PendingExports.push_back(Root);
814 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
816 PendingExports.size());
817 PendingExports.clear();
822 void SelectionDAGLowering::visit(Instruction &I) {
823 visit(I.getOpcode(), I);
826 void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
827 // Note: this doesn't use InstVisitor, because it has to work with
828 // ConstantExpr's in addition to instructions.
830 default: assert(0 && "Unknown instruction type encountered!");
832 // Build the switch statement using the Instruction.def file.
833 #define HANDLE_INST(NUM, OPCODE, CLASS) \
834 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
835 #include "llvm/Instruction.def"
839 void SelectionDAGLowering::visitAdd(User &I) {
840 if (I.getType()->isFPOrFPVector())
841 visitBinary(I, ISD::FADD);
843 visitBinary(I, ISD::ADD);
846 void SelectionDAGLowering::visitMul(User &I) {
847 if (I.getType()->isFPOrFPVector())
848 visitBinary(I, ISD::FMUL);
850 visitBinary(I, ISD::MUL);
853 SDValue SelectionDAGLowering::getValue(const Value *V) {
854 SDValue &N = NodeMap[V];
855 if (N.getNode()) return N;
857 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
858 MVT VT = TLI.getValueType(V->getType(), true);
860 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
861 return N = DAG.getConstant(*CI, VT);
863 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
864 return N = DAG.getGlobalAddress(GV, VT);
866 if (isa<ConstantPointerNull>(C))
867 return N = DAG.getConstant(0, TLI.getPointerTy());
869 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
870 return N = DAG.getConstantFP(*CFP, VT);
872 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
873 !V->getType()->isAggregateType())
874 return N = DAG.getUNDEF(VT);
876 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
877 visit(CE->getOpcode(), *CE);
878 SDValue N1 = NodeMap[V];
879 assert(N1.getNode() && "visit didn't populate the ValueMap!");
883 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
884 SmallVector<SDValue, 4> Constants;
885 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
887 SDNode *Val = getValue(*OI).getNode();
888 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
889 Constants.push_back(SDValue(Val, i));
891 return DAG.getMergeValues(&Constants[0], Constants.size(),
895 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
896 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
897 "Unknown struct or array constant!");
899 SmallVector<MVT, 4> ValueVTs;
900 ComputeValueVTs(TLI, C->getType(), ValueVTs);
901 unsigned NumElts = ValueVTs.size();
903 return SDValue(); // empty struct
904 SmallVector<SDValue, 4> Constants(NumElts);
905 for (unsigned i = 0; i != NumElts; ++i) {
906 MVT EltVT = ValueVTs[i];
907 if (isa<UndefValue>(C))
908 Constants[i] = DAG.getUNDEF(EltVT);
909 else if (EltVT.isFloatingPoint())
910 Constants[i] = DAG.getConstantFP(0, EltVT);
912 Constants[i] = DAG.getConstant(0, EltVT);
914 return DAG.getMergeValues(&Constants[0], NumElts, getCurDebugLoc());
917 const VectorType *VecTy = cast<VectorType>(V->getType());
918 unsigned NumElements = VecTy->getNumElements();
920 // Now that we know the number and type of the elements, get that number of
921 // elements into the Ops array based on what kind of constant it is.
922 SmallVector<SDValue, 16> Ops;
923 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
924 for (unsigned i = 0; i != NumElements; ++i)
925 Ops.push_back(getValue(CP->getOperand(i)));
927 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
928 "Unknown vector constant!");
929 MVT EltVT = TLI.getValueType(VecTy->getElementType());
932 if (isa<UndefValue>(C))
933 Op = DAG.getUNDEF(EltVT);
934 else if (EltVT.isFloatingPoint())
935 Op = DAG.getConstantFP(0, EltVT);
937 Op = DAG.getConstant(0, EltVT);
938 Ops.assign(NumElements, Op);
941 // Create a BUILD_VECTOR node.
942 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
943 VT, &Ops[0], Ops.size());
946 // If this is a static alloca, generate it as the frameindex instead of
948 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
949 DenseMap<const AllocaInst*, int>::iterator SI =
950 FuncInfo.StaticAllocaMap.find(AI);
951 if (SI != FuncInfo.StaticAllocaMap.end())
952 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
955 unsigned InReg = FuncInfo.ValueMap[V];
956 assert(InReg && "Value not in map!");
958 RegsForValue RFV(TLI, InReg, V->getType());
959 SDValue Chain = DAG.getEntryNode();
960 return RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL);
964 void SelectionDAGLowering::visitRet(ReturnInst &I) {
965 if (I.getNumOperands() == 0) {
966 DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(),
967 MVT::Other, getControlRoot()));
971 SmallVector<SDValue, 8> NewValues;
972 NewValues.push_back(getControlRoot());
973 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
974 SmallVector<MVT, 4> ValueVTs;
975 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
976 unsigned NumValues = ValueVTs.size();
977 if (NumValues == 0) continue;
979 SDValue RetOp = getValue(I.getOperand(i));
980 for (unsigned j = 0, f = NumValues; j != f; ++j) {
981 MVT VT = ValueVTs[j];
983 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
985 const Function *F = I.getParent()->getParent();
986 if (F->paramHasAttr(0, Attribute::SExt))
987 ExtendKind = ISD::SIGN_EXTEND;
988 else if (F->paramHasAttr(0, Attribute::ZExt))
989 ExtendKind = ISD::ZERO_EXTEND;
991 // FIXME: C calling convention requires the return type to be promoted to
992 // at least 32-bit. But this is not necessary for non-C calling
993 // conventions. The frontend should mark functions whose return values
994 // require promoting with signext or zeroext attributes.
995 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
996 MVT MinVT = TLI.getRegisterType(MVT::i32);
997 if (VT.bitsLT(MinVT))
1001 unsigned NumParts = TLI.getNumRegisters(VT);
1002 MVT PartVT = TLI.getRegisterType(VT);
1003 SmallVector<SDValue, 4> Parts(NumParts);
1004 getCopyToParts(DAG, getCurDebugLoc(),
1005 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1006 &Parts[0], NumParts, PartVT, ExtendKind);
1008 // 'inreg' on function refers to return value
1009 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1010 if (F->paramHasAttr(0, Attribute::InReg))
1012 for (unsigned i = 0; i < NumParts; ++i) {
1013 NewValues.push_back(Parts[i]);
1014 NewValues.push_back(DAG.getArgFlags(Flags));
1018 DAG.setRoot(DAG.getNode(ISD::RET, getCurDebugLoc(), MVT::Other,
1019 &NewValues[0], NewValues.size()));
1022 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1023 /// the current basic block, add it to ValueMap now so that we'll get a
1025 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
1026 // No need to export constants.
1027 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1029 // Already exported?
1030 if (FuncInfo.isExportedInst(V)) return;
1032 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1033 CopyValueToVirtualRegister(V, Reg);
1036 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
1037 const BasicBlock *FromBB) {
1038 // The operands of the setcc have to be in this block. We don't know
1039 // how to export them from some other block.
1040 if (Instruction *VI = dyn_cast<Instruction>(V)) {
1041 // Can export from current BB.
1042 if (VI->getParent() == FromBB)
1045 // Is already exported, noop.
1046 return FuncInfo.isExportedInst(V);
1049 // If this is an argument, we can export it if the BB is the entry block or
1050 // if it is already exported.
1051 if (isa<Argument>(V)) {
1052 if (FromBB == &FromBB->getParent()->getEntryBlock())
1055 // Otherwise, can only export this if it is already exported.
1056 return FuncInfo.isExportedInst(V);
1059 // Otherwise, constants can always be exported.
1063 static bool InBlock(const Value *V, const BasicBlock *BB) {
1064 if (const Instruction *I = dyn_cast<Instruction>(V))
1065 return I->getParent() == BB;
1069 /// getFCmpCondCode - Return the ISD condition code corresponding to
1070 /// the given LLVM IR floating-point condition code. This includes
1071 /// consideration of global floating-point math flags.
1073 static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1074 ISD::CondCode FPC, FOC;
1076 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1077 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1078 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1079 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1080 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1081 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1082 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1083 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1084 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1085 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1086 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1087 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1088 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1089 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1090 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1091 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1093 assert(0 && "Invalid FCmp predicate opcode!");
1094 FOC = FPC = ISD::SETFALSE;
1097 if (FiniteOnlyFPMath())
1103 /// getICmpCondCode - Return the ISD condition code corresponding to
1104 /// the given LLVM IR integer condition code.
1106 static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1108 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1109 case ICmpInst::ICMP_NE: return ISD::SETNE;
1110 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1111 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1112 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1113 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1114 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1115 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1116 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1117 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1119 assert(0 && "Invalid ICmp predicate opcode!");
1124 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1125 /// This function emits a branch and is used at the leaves of an OR or an
1126 /// AND operator tree.
1129 SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1130 MachineBasicBlock *TBB,
1131 MachineBasicBlock *FBB,
1132 MachineBasicBlock *CurBB) {
1133 const BasicBlock *BB = CurBB->getBasicBlock();
1135 // If the leaf of the tree is a comparison, merge the condition into
1137 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1138 // The operands of the cmp have to be in this block. We don't know
1139 // how to export them from some other block. If this is the first block
1140 // of the sequence, no exporting is needed.
1141 if (CurBB == CurMBB ||
1142 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1143 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1144 ISD::CondCode Condition;
1145 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1146 Condition = getICmpCondCode(IC->getPredicate());
1147 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1148 Condition = getFCmpCondCode(FC->getPredicate());
1150 Condition = ISD::SETEQ; // silence warning.
1151 assert(0 && "Unknown compare instruction");
1154 CaseBlock CB(Condition, BOp->getOperand(0),
1155 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1156 SwitchCases.push_back(CB);
1161 // Create a CaseBlock record representing this branch.
1162 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1163 NULL, TBB, FBB, CurBB);
1164 SwitchCases.push_back(CB);
1167 /// FindMergedConditions - If Cond is an expression like
1168 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1169 MachineBasicBlock *TBB,
1170 MachineBasicBlock *FBB,
1171 MachineBasicBlock *CurBB,
1173 // If this node is not part of the or/and tree, emit it as a branch.
1174 Instruction *BOp = dyn_cast<Instruction>(Cond);
1175 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1176 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1177 BOp->getParent() != CurBB->getBasicBlock() ||
1178 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1179 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1180 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
1184 // Create TmpBB after CurBB.
1185 MachineFunction::iterator BBI = CurBB;
1186 MachineFunction &MF = DAG.getMachineFunction();
1187 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1188 CurBB->getParent()->insert(++BBI, TmpBB);
1190 if (Opc == Instruction::Or) {
1191 // Codegen X | Y as:
1199 // Emit the LHS condition.
1200 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1202 // Emit the RHS condition into TmpBB.
1203 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1205 assert(Opc == Instruction::And && "Unknown merge op!");
1206 // Codegen X & Y as:
1213 // This requires creation of TmpBB after CurBB.
1215 // Emit the LHS condition.
1216 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1218 // Emit the RHS condition into TmpBB.
1219 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1223 /// If the set of cases should be emitted as a series of branches, return true.
1224 /// If we should emit this as a bunch of and/or'd together conditions, return
1227 SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1228 if (Cases.size() != 2) return true;
1230 // If this is two comparisons of the same values or'd or and'd together, they
1231 // will get folded into a single comparison, so don't emit two blocks.
1232 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1233 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1234 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1235 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1242 void SelectionDAGLowering::visitBr(BranchInst &I) {
1243 // Update machine-CFG edges.
1244 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1246 // Figure out which block is immediately after the current one.
1247 MachineBasicBlock *NextBlock = 0;
1248 MachineFunction::iterator BBI = CurMBB;
1249 if (++BBI != CurMBB->getParent()->end())
1252 if (I.isUnconditional()) {
1253 // Update machine-CFG edges.
1254 CurMBB->addSuccessor(Succ0MBB);
1256 // If this is not a fall-through branch, emit the branch.
1257 if (Succ0MBB != NextBlock)
1258 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1259 MVT::Other, getControlRoot(),
1260 DAG.getBasicBlock(Succ0MBB)));
1264 // If this condition is one of the special cases we handle, do special stuff
1266 Value *CondVal = I.getCondition();
1267 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1269 // If this is a series of conditions that are or'd or and'd together, emit
1270 // this as a sequence of branches instead of setcc's with and/or operations.
1271 // For example, instead of something like:
1284 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1285 if (BOp->hasOneUse() &&
1286 (BOp->getOpcode() == Instruction::And ||
1287 BOp->getOpcode() == Instruction::Or)) {
1288 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1289 // If the compares in later blocks need to use values not currently
1290 // exported from this block, export them now. This block should always
1291 // be the first entry.
1292 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1294 // Allow some cases to be rejected.
1295 if (ShouldEmitAsBranches(SwitchCases)) {
1296 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1297 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1298 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1301 // Emit the branch for this block.
1302 visitSwitchCase(SwitchCases[0]);
1303 SwitchCases.erase(SwitchCases.begin());
1307 // Okay, we decided not to do this, remove any inserted MBB's and clear
1309 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1310 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
1312 SwitchCases.clear();
1316 // Create a CaseBlock record representing this branch.
1317 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1318 NULL, Succ0MBB, Succ1MBB, CurMBB);
1319 // Use visitSwitchCase to actually insert the fast branch sequence for this
1321 visitSwitchCase(CB);
1324 /// visitSwitchCase - Emits the necessary code to represent a single node in
1325 /// the binary search tree resulting from lowering a switch instruction.
1326 void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1328 SDValue CondLHS = getValue(CB.CmpLHS);
1329 DebugLoc dl = getCurDebugLoc();
1331 // Build the setcc now.
1332 if (CB.CmpMHS == NULL) {
1333 // Fold "(X == true)" to X and "(X == false)" to !X to
1334 // handle common cases produced by branch lowering.
1335 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1337 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1338 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1339 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1341 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1343 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1345 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1346 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1348 SDValue CmpOp = getValue(CB.CmpMHS);
1349 MVT VT = CmpOp.getValueType();
1351 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1352 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1355 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1356 VT, CmpOp, DAG.getConstant(Low, VT));
1357 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1358 DAG.getConstant(High-Low, VT), ISD::SETULE);
1362 // Update successor info
1363 CurMBB->addSuccessor(CB.TrueBB);
1364 CurMBB->addSuccessor(CB.FalseBB);
1366 // Set NextBlock to be the MBB immediately after the current one, if any.
1367 // This is used to avoid emitting unnecessary branches to the next block.
1368 MachineBasicBlock *NextBlock = 0;
1369 MachineFunction::iterator BBI = CurMBB;
1370 if (++BBI != CurMBB->getParent()->end())
1373 // If the lhs block is the next block, invert the condition so that we can
1374 // fall through to the lhs instead of the rhs block.
1375 if (CB.TrueBB == NextBlock) {
1376 std::swap(CB.TrueBB, CB.FalseBB);
1377 SDValue True = DAG.getConstant(1, Cond.getValueType());
1378 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1380 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1381 MVT::Other, getControlRoot(), Cond,
1382 DAG.getBasicBlock(CB.TrueBB));
1384 // If the branch was constant folded, fix up the CFG.
1385 if (BrCond.getOpcode() == ISD::BR) {
1386 CurMBB->removeSuccessor(CB.FalseBB);
1387 DAG.setRoot(BrCond);
1389 // Otherwise, go ahead and insert the false branch.
1390 if (BrCond == getControlRoot())
1391 CurMBB->removeSuccessor(CB.TrueBB);
1393 if (CB.FalseBB == NextBlock)
1394 DAG.setRoot(BrCond);
1396 DAG.setRoot(DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1397 DAG.getBasicBlock(CB.FalseBB)));
1401 /// visitJumpTable - Emit JumpTable node in the current MBB
1402 void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1403 // Emit the code for the jump table
1404 assert(JT.Reg != -1U && "Should lower JT Header first!");
1405 MVT PTy = TLI.getPointerTy();
1406 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1408 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1409 DAG.setRoot(DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1410 MVT::Other, Index.getValue(1),
1414 /// visitJumpTableHeader - This function emits necessary code to produce index
1415 /// in the JumpTable from switch case.
1416 void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1417 JumpTableHeader &JTH) {
1418 // Subtract the lowest switch case value from the value being switched on and
1419 // conditional branch to default mbb if the result is greater than the
1420 // difference between smallest and largest cases.
1421 SDValue SwitchOp = getValue(JTH.SValue);
1422 MVT VT = SwitchOp.getValueType();
1423 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1424 DAG.getConstant(JTH.First, VT));
1426 // The SDNode we just created, which holds the value being switched on minus
1427 // the the smallest case value, needs to be copied to a virtual register so it
1428 // can be used as an index into the jump table in a subsequent basic block.
1429 // This value may be smaller or larger than the target's pointer type, and
1430 // therefore require extension or truncating.
1431 if (VT.bitsGT(TLI.getPointerTy()))
1432 SwitchOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
1433 TLI.getPointerTy(), SUB);
1435 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
1436 TLI.getPointerTy(), SUB);
1438 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1439 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1440 JumpTableReg, SwitchOp);
1441 JT.Reg = JumpTableReg;
1443 // Emit the range check for the jump table, and branch to the default block
1444 // for the switch statement if the value being switched on exceeds the largest
1445 // case in the switch.
1446 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1447 TLI.getSetCCResultType(SUB.getValueType()), SUB,
1448 DAG.getConstant(JTH.Last-JTH.First,VT),
1451 // Set NextBlock to be the MBB immediately after the current one, if any.
1452 // This is used to avoid emitting unnecessary branches to the next block.
1453 MachineBasicBlock *NextBlock = 0;
1454 MachineFunction::iterator BBI = CurMBB;
1455 if (++BBI != CurMBB->getParent()->end())
1458 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1459 MVT::Other, CopyTo, CMP,
1460 DAG.getBasicBlock(JT.Default));
1462 if (JT.MBB == NextBlock)
1463 DAG.setRoot(BrCond);
1465 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1466 DAG.getBasicBlock(JT.MBB)));
1469 /// visitBitTestHeader - This function emits necessary code to produce value
1470 /// suitable for "bit tests"
1471 void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1472 // Subtract the minimum value
1473 SDValue SwitchOp = getValue(B.SValue);
1474 MVT VT = SwitchOp.getValueType();
1475 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1476 DAG.getConstant(B.First, VT));
1479 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1480 TLI.getSetCCResultType(SUB.getValueType()),
1481 SUB, DAG.getConstant(B.Range, VT),
1485 if (VT.bitsGT(TLI.getPointerTy()))
1486 ShiftOp = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
1487 TLI.getPointerTy(), SUB);
1489 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
1490 TLI.getPointerTy(), SUB);
1492 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
1493 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1496 // Set NextBlock to be the MBB immediately after the current one, if any.
1497 // This is used to avoid emitting unnecessary branches to the next block.
1498 MachineBasicBlock *NextBlock = 0;
1499 MachineFunction::iterator BBI = CurMBB;
1500 if (++BBI != CurMBB->getParent()->end())
1503 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1505 CurMBB->addSuccessor(B.Default);
1506 CurMBB->addSuccessor(MBB);
1508 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1509 MVT::Other, CopyTo, RangeCmp,
1510 DAG.getBasicBlock(B.Default));
1512 if (MBB == NextBlock)
1513 DAG.setRoot(BrRange);
1515 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1516 DAG.getBasicBlock(MBB)));
1519 /// visitBitTestCase - this function produces one "bit test"
1520 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1523 // Make desired shift
1524 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
1525 TLI.getPointerTy());
1526 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
1528 DAG.getConstant(1, TLI.getPointerTy()),
1531 // Emit bit tests and jumps
1532 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
1533 TLI.getPointerTy(), SwitchVal,
1534 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1535 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1536 TLI.getSetCCResultType(AndOp.getValueType()),
1537 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
1540 CurMBB->addSuccessor(B.TargetBB);
1541 CurMBB->addSuccessor(NextMBB);
1543 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1544 MVT::Other, getControlRoot(),
1545 AndCmp, DAG.getBasicBlock(B.TargetBB));
1547 // Set NextBlock to be the MBB immediately after the current one, if any.
1548 // This is used to avoid emitting unnecessary branches to the next block.
1549 MachineBasicBlock *NextBlock = 0;
1550 MachineFunction::iterator BBI = CurMBB;
1551 if (++BBI != CurMBB->getParent()->end())
1554 if (NextMBB == NextBlock)
1557 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1558 DAG.getBasicBlock(NextMBB)));
1561 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1562 // Retrieve successors.
1563 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1564 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1566 const Value *Callee(I.getCalledValue());
1567 if (isa<InlineAsm>(Callee))
1570 LowerCallTo(&I, getValue(Callee), false, LandingPad);
1572 // If the value of the invoke is used outside of its defining block, make it
1573 // available as a virtual register.
1574 if (!I.use_empty()) {
1575 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1576 if (VMI != FuncInfo.ValueMap.end())
1577 CopyValueToVirtualRegister(&I, VMI->second);
1580 // Update successor info
1581 CurMBB->addSuccessor(Return);
1582 CurMBB->addSuccessor(LandingPad);
1584 // Drop into normal successor.
1585 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1586 MVT::Other, getControlRoot(),
1587 DAG.getBasicBlock(Return)));
1590 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1593 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1594 /// small case ranges).
1595 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1596 CaseRecVector& WorkList,
1598 MachineBasicBlock* Default) {
1599 Case& BackCase = *(CR.Range.second-1);
1601 // Size is the number of Cases represented by this range.
1602 size_t Size = CR.Range.second - CR.Range.first;
1606 // Get the MachineFunction which holds the current MBB. This is used when
1607 // inserting any additional MBBs necessary to represent the switch.
1608 MachineFunction *CurMF = CurMBB->getParent();
1610 // Figure out which block is immediately after the current one.
1611 MachineBasicBlock *NextBlock = 0;
1612 MachineFunction::iterator BBI = CR.CaseBB;
1614 if (++BBI != CurMBB->getParent()->end())
1617 // TODO: If any two of the cases has the same destination, and if one value
1618 // is the same as the other, but has one bit unset that the other has set,
1619 // use bit manipulation to do two compares at once. For example:
1620 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1622 // Rearrange the case blocks so that the last one falls through if possible.
1623 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1624 // The last case block won't fall through into 'NextBlock' if we emit the
1625 // branches in this order. See if rearranging a case value would help.
1626 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1627 if (I->BB == NextBlock) {
1628 std::swap(*I, BackCase);
1634 // Create a CaseBlock record representing a conditional branch to
1635 // the Case's target mbb if the value being switched on SV is equal
1637 MachineBasicBlock *CurBlock = CR.CaseBB;
1638 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1639 MachineBasicBlock *FallThrough;
1641 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1642 CurMF->insert(BBI, FallThrough);
1644 // If the last case doesn't match, go to the default block.
1645 FallThrough = Default;
1648 Value *RHS, *LHS, *MHS;
1650 if (I->High == I->Low) {
1651 // This is just small small case range :) containing exactly 1 case
1653 LHS = SV; RHS = I->High; MHS = NULL;
1656 LHS = I->Low; MHS = SV; RHS = I->High;
1658 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1660 // If emitting the first comparison, just call visitSwitchCase to emit the
1661 // code into the current block. Otherwise, push the CaseBlock onto the
1662 // vector to be later processed by SDISel, and insert the node's MBB
1663 // before the next MBB.
1664 if (CurBlock == CurMBB)
1665 visitSwitchCase(CB);
1667 SwitchCases.push_back(CB);
1669 CurBlock = FallThrough;
1675 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1676 return !DisableJumpTables &&
1677 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1678 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1681 static APInt ComputeRange(const APInt &First, const APInt &Last) {
1682 APInt LastExt(Last), FirstExt(First);
1683 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1684 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1685 return (LastExt - FirstExt + 1ULL);
1688 /// handleJTSwitchCase - Emit jumptable for current switch case range
1689 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1690 CaseRecVector& WorkList,
1692 MachineBasicBlock* Default) {
1693 Case& FrontCase = *CR.Range.first;
1694 Case& BackCase = *(CR.Range.second-1);
1696 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1697 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
1700 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1704 if (!areJTsAllowed(TLI) || TSize <= 3)
1707 APInt Range = ComputeRange(First, Last);
1708 double Density = (double)TSize / Range.roundToDouble();
1712 DEBUG(errs() << "Lowering jump table\n"
1713 << "First entry: " << First << ". Last entry: " << Last << '\n'
1714 << "Range: " << Range
1715 << "Size: " << TSize << ". Density: " << Density << "\n\n");
1717 // Get the MachineFunction which holds the current MBB. This is used when
1718 // inserting any additional MBBs necessary to represent the switch.
1719 MachineFunction *CurMF = CurMBB->getParent();
1721 // Figure out which block is immediately after the current one.
1722 MachineBasicBlock *NextBlock = 0;
1723 MachineFunction::iterator BBI = CR.CaseBB;
1725 if (++BBI != CurMBB->getParent()->end())
1728 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1730 // Create a new basic block to hold the code for loading the address
1731 // of the jump table, and jumping to it. Update successor information;
1732 // we will either branch to the default case for the switch, or the jump
1734 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1735 CurMF->insert(BBI, JumpTableBB);
1736 CR.CaseBB->addSuccessor(Default);
1737 CR.CaseBB->addSuccessor(JumpTableBB);
1739 // Build a vector of destination BBs, corresponding to each target
1740 // of the jump table. If the value of the jump table slot corresponds to
1741 // a case statement, push the case's BB onto the vector, otherwise, push
1743 std::vector<MachineBasicBlock*> DestBBs;
1745 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1746 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1747 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1749 if (Low.sle(TEI) && TEI.sle(High)) {
1750 DestBBs.push_back(I->BB);
1754 DestBBs.push_back(Default);
1758 // Update successor info. Add one edge to each unique successor.
1759 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1760 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1761 E = DestBBs.end(); I != E; ++I) {
1762 if (!SuccsHandled[(*I)->getNumber()]) {
1763 SuccsHandled[(*I)->getNumber()] = true;
1764 JumpTableBB->addSuccessor(*I);
1768 // Create a jump table index for this jump table, or return an existing
1770 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1772 // Set the jump table information so that we can codegen it as a second
1773 // MachineBasicBlock
1774 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1775 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1776 if (CR.CaseBB == CurMBB)
1777 visitJumpTableHeader(JT, JTH);
1779 JTCases.push_back(JumpTableBlock(JTH, JT));
1784 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1786 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1787 CaseRecVector& WorkList,
1789 MachineBasicBlock* Default) {
1790 // Get the MachineFunction which holds the current MBB. This is used when
1791 // inserting any additional MBBs necessary to represent the switch.
1792 MachineFunction *CurMF = CurMBB->getParent();
1794 // Figure out which block is immediately after the current one.
1795 MachineBasicBlock *NextBlock = 0;
1796 MachineFunction::iterator BBI = CR.CaseBB;
1798 if (++BBI != CurMBB->getParent()->end())
1801 Case& FrontCase = *CR.Range.first;
1802 Case& BackCase = *(CR.Range.second-1);
1803 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1805 // Size is the number of Cases represented by this range.
1806 unsigned Size = CR.Range.second - CR.Range.first;
1808 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1809 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
1811 CaseItr Pivot = CR.Range.first + Size/2;
1813 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1814 // (heuristically) allow us to emit JumpTable's later.
1816 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1820 size_t LSize = FrontCase.size();
1821 size_t RSize = TSize-LSize;
1822 DEBUG(errs() << "Selecting best pivot: \n"
1823 << "First: " << First << ", Last: " << Last <<'\n'
1824 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
1825 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1827 const APInt& LEnd = cast<ConstantInt>(I->High)->getValue();
1828 const APInt& RBegin = cast<ConstantInt>(J->Low)->getValue();
1829 APInt Range = ComputeRange(LEnd, RBegin);
1830 assert((Range - 2ULL).isNonNegative() &&
1831 "Invalid case distance");
1832 double LDensity = (double)LSize / (LEnd - First + 1ULL).roundToDouble();
1833 double RDensity = (double)RSize / (Last - RBegin + 1ULL).roundToDouble();
1834 double Metric = Range.logBase2()*(LDensity+RDensity);
1835 // Should always split in some non-trivial place
1836 DEBUG(errs() <<"=>Step\n"
1837 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1838 << "LDensity: " << LDensity
1839 << ", RDensity: " << RDensity << '\n'
1840 << "Metric: " << Metric << '\n');
1841 if (FMetric < Metric) {
1844 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
1850 if (areJTsAllowed(TLI)) {
1851 // If our case is dense we *really* should handle it earlier!
1852 assert((FMetric > 0) && "Should handle dense range earlier!");
1854 Pivot = CR.Range.first + Size/2;
1857 CaseRange LHSR(CR.Range.first, Pivot);
1858 CaseRange RHSR(Pivot, CR.Range.second);
1859 Constant *C = Pivot->Low;
1860 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1862 // We know that we branch to the LHS if the Value being switched on is
1863 // less than the Pivot value, C. We use this to optimize our binary
1864 // tree a bit, by recognizing that if SV is greater than or equal to the
1865 // LHS's Case Value, and that Case Value is exactly one less than the
1866 // Pivot's Value, then we can branch directly to the LHS's Target,
1867 // rather than creating a leaf node for it.
1868 if ((LHSR.second - LHSR.first) == 1 &&
1869 LHSR.first->High == CR.GE &&
1870 cast<ConstantInt>(C)->getValue() ==
1871 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
1872 TrueBB = LHSR.first->BB;
1874 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1875 CurMF->insert(BBI, TrueBB);
1876 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1879 // Similar to the optimization above, if the Value being switched on is
1880 // known to be less than the Constant CR.LT, and the current Case Value
1881 // is CR.LT - 1, then we can branch directly to the target block for
1882 // the current Case Value, rather than emitting a RHS leaf node for it.
1883 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1884 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1885 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
1886 FalseBB = RHSR.first->BB;
1888 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1889 CurMF->insert(BBI, FalseBB);
1890 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1893 // Create a CaseBlock record representing a conditional branch to
1894 // the LHS node if the value being switched on SV is less than C.
1895 // Otherwise, branch to LHS.
1896 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1898 if (CR.CaseBB == CurMBB)
1899 visitSwitchCase(CB);
1901 SwitchCases.push_back(CB);
1906 /// handleBitTestsSwitchCase - if current case range has few destination and
1907 /// range span less, than machine word bitwidth, encode case range into series
1908 /// of masks and emit bit tests with these masks.
1909 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1910 CaseRecVector& WorkList,
1912 MachineBasicBlock* Default){
1913 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1915 Case& FrontCase = *CR.Range.first;
1916 Case& BackCase = *(CR.Range.second-1);
1918 // Get the MachineFunction which holds the current MBB. This is used when
1919 // inserting any additional MBBs necessary to represent the switch.
1920 MachineFunction *CurMF = CurMBB->getParent();
1923 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1925 // Single case counts one, case range - two.
1926 numCmps += (I->Low == I->High ? 1 : 2);
1929 // Count unique destinations
1930 SmallSet<MachineBasicBlock*, 4> Dests;
1931 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1932 Dests.insert(I->BB);
1933 if (Dests.size() > 3)
1934 // Don't bother the code below, if there are too much unique destinations
1937 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1938 << "Total number of comparisons: " << numCmps << '\n');
1940 // Compute span of values.
1941 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1942 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
1943 APInt cmpRange = maxValue - minValue;
1945 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1946 << "Low bound: " << minValue << '\n'
1947 << "High bound: " << maxValue << '\n');
1949 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
1950 (!(Dests.size() == 1 && numCmps >= 3) &&
1951 !(Dests.size() == 2 && numCmps >= 5) &&
1952 !(Dests.size() >= 3 && numCmps >= 6)))
1955 DEBUG(errs() << "Emitting bit tests\n");
1956 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1958 // Optimize the case where all the case values fit in a
1959 // word without having to subtract minValue. In this case,
1960 // we can optimize away the subtraction.
1961 if (minValue.isNonNegative() &&
1962 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1963 cmpRange = maxValue;
1965 lowBound = minValue;
1968 CaseBitsVector CasesBits;
1969 unsigned i, count = 0;
1971 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1972 MachineBasicBlock* Dest = I->BB;
1973 for (i = 0; i < count; ++i)
1974 if (Dest == CasesBits[i].BB)
1978 assert((count < 3) && "Too much destinations to test!");
1979 CasesBits.push_back(CaseBits(0, Dest, 0));
1983 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1984 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1986 uint64_t lo = (lowValue - lowBound).getZExtValue();
1987 uint64_t hi = (highValue - lowBound).getZExtValue();
1989 for (uint64_t j = lo; j <= hi; j++) {
1990 CasesBits[i].Mask |= 1ULL << j;
1991 CasesBits[i].Bits++;
1995 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1999 // Figure out which block is immediately after the current one.
2000 MachineFunction::iterator BBI = CR.CaseBB;
2003 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2005 DEBUG(errs() << "Cases:\n");
2006 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2007 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
2008 << ", Bits: " << CasesBits[i].Bits
2009 << ", BB: " << CasesBits[i].BB << '\n');
2011 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2012 CurMF->insert(BBI, CaseBB);
2013 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2018 BitTestBlock BTB(lowBound, cmpRange, SV,
2019 -1U, (CR.CaseBB == CurMBB),
2020 CR.CaseBB, Default, BTC);
2022 if (CR.CaseBB == CurMBB)
2023 visitBitTestHeader(BTB);
2025 BitTestCases.push_back(BTB);
2031 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2032 size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
2033 const SwitchInst& SI) {
2036 // Start with "simple" cases
2037 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
2038 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2039 Cases.push_back(Case(SI.getSuccessorValue(i),
2040 SI.getSuccessorValue(i),
2043 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2045 // Merge case into clusters
2046 if (Cases.size() >= 2)
2047 // Must recompute end() each iteration because it may be
2048 // invalidated by erase if we hold on to it
2049 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
2050 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2051 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2052 MachineBasicBlock* nextBB = J->BB;
2053 MachineBasicBlock* currentBB = I->BB;
2055 // If the two neighboring cases go to the same destination, merge them
2056 // into a single case.
2057 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2065 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2066 if (I->Low != I->High)
2067 // A range counts double, since it requires two compares.
2074 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
2075 // Figure out which block is immediately after the current one.
2076 MachineBasicBlock *NextBlock = 0;
2077 MachineFunction::iterator BBI = CurMBB;
2079 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2081 // If there is only the default destination, branch to it if it is not the
2082 // next basic block. Otherwise, just fall through.
2083 if (SI.getNumOperands() == 2) {
2084 // Update machine-CFG edges.
2086 // If this is not a fall-through branch, emit the branch.
2087 CurMBB->addSuccessor(Default);
2088 if (Default != NextBlock)
2089 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
2090 MVT::Other, getControlRoot(),
2091 DAG.getBasicBlock(Default)));
2095 // If there are any non-default case statements, create a vector of Cases
2096 // representing each one, and sort the vector so that we can efficiently
2097 // create a binary search tree from them.
2099 size_t numCmps = Clusterify(Cases, SI);
2100 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
2101 << ". Total compares: " << numCmps << '\n');
2104 // Get the Value to be switched on and default basic blocks, which will be
2105 // inserted into CaseBlock records, representing basic blocks in the binary
2107 Value *SV = SI.getOperand(0);
2109 // Push the initial CaseRec onto the worklist
2110 CaseRecVector WorkList;
2111 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2113 while (!WorkList.empty()) {
2114 // Grab a record representing a case range to process off the worklist
2115 CaseRec CR = WorkList.back();
2116 WorkList.pop_back();
2118 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2121 // If the range has few cases (two or less) emit a series of specific
2123 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2126 // If the switch has more than 5 blocks, and at least 40% dense, and the
2127 // target supports indirect branches, then emit a jump table rather than
2128 // lowering the switch to a binary tree of conditional branches.
2129 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2132 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2133 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2134 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2139 void SelectionDAGLowering::visitSub(User &I) {
2140 // -0.0 - X --> fneg
2141 const Type *Ty = I.getType();
2142 if (isa<VectorType>(Ty)) {
2143 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2144 const VectorType *DestTy = cast<VectorType>(I.getType());
2145 const Type *ElTy = DestTy->getElementType();
2146 if (ElTy->isFloatingPoint()) {
2147 unsigned VL = DestTy->getNumElements();
2148 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2149 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2151 SDValue Op2 = getValue(I.getOperand(1));
2152 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2153 Op2.getValueType(), Op2));
2159 if (Ty->isFloatingPoint()) {
2160 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2161 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2162 SDValue Op2 = getValue(I.getOperand(1));
2163 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2164 Op2.getValueType(), Op2));
2169 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2172 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2173 SDValue Op1 = getValue(I.getOperand(0));
2174 SDValue Op2 = getValue(I.getOperand(1));
2176 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2177 Op1.getValueType(), Op1, Op2));
2180 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2181 SDValue Op1 = getValue(I.getOperand(0));
2182 SDValue Op2 = getValue(I.getOperand(1));
2183 if (!isa<VectorType>(I.getType())) {
2184 if (TLI.getPointerTy().bitsLT(Op2.getValueType()))
2185 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2186 TLI.getPointerTy(), Op2);
2187 else if (TLI.getPointerTy().bitsGT(Op2.getValueType()))
2188 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2189 TLI.getPointerTy(), Op2);
2192 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2193 Op1.getValueType(), Op1, Op2));
2196 void SelectionDAGLowering::visitICmp(User &I) {
2197 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2198 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2199 predicate = IC->getPredicate();
2200 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2201 predicate = ICmpInst::Predicate(IC->getPredicate());
2202 SDValue Op1 = getValue(I.getOperand(0));
2203 SDValue Op2 = getValue(I.getOperand(1));
2204 ISD::CondCode Opcode = getICmpCondCode(predicate);
2205 setValue(&I, DAG.getSetCC(getCurDebugLoc(),MVT::i1, Op1, Op2, Opcode));
2208 void SelectionDAGLowering::visitFCmp(User &I) {
2209 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2210 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2211 predicate = FC->getPredicate();
2212 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2213 predicate = FCmpInst::Predicate(FC->getPredicate());
2214 SDValue Op1 = getValue(I.getOperand(0));
2215 SDValue Op2 = getValue(I.getOperand(1));
2216 ISD::CondCode Condition = getFCmpCondCode(predicate);
2217 setValue(&I, DAG.getSetCC(getCurDebugLoc(), MVT::i1, Op1, Op2, Condition));
2220 void SelectionDAGLowering::visitVICmp(User &I) {
2221 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2222 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2223 predicate = IC->getPredicate();
2224 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2225 predicate = ICmpInst::Predicate(IC->getPredicate());
2226 SDValue Op1 = getValue(I.getOperand(0));
2227 SDValue Op2 = getValue(I.getOperand(1));
2228 ISD::CondCode Opcode = getICmpCondCode(predicate);
2229 setValue(&I, DAG.getVSetCC(getCurDebugLoc(), Op1.getValueType(),
2233 void SelectionDAGLowering::visitVFCmp(User &I) {
2234 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2235 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2236 predicate = FC->getPredicate();
2237 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2238 predicate = FCmpInst::Predicate(FC->getPredicate());
2239 SDValue Op1 = getValue(I.getOperand(0));
2240 SDValue Op2 = getValue(I.getOperand(1));
2241 ISD::CondCode Condition = getFCmpCondCode(predicate);
2242 MVT DestVT = TLI.getValueType(I.getType());
2244 setValue(&I, DAG.getVSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
2247 void SelectionDAGLowering::visitSelect(User &I) {
2248 SmallVector<MVT, 4> ValueVTs;
2249 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2250 unsigned NumValues = ValueVTs.size();
2251 if (NumValues != 0) {
2252 SmallVector<SDValue, 4> Values(NumValues);
2253 SDValue Cond = getValue(I.getOperand(0));
2254 SDValue TrueVal = getValue(I.getOperand(1));
2255 SDValue FalseVal = getValue(I.getOperand(2));
2257 for (unsigned i = 0; i != NumValues; ++i)
2258 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2259 TrueVal.getValueType(), Cond,
2260 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2261 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2263 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2264 DAG.getVTList(&ValueVTs[0], NumValues),
2265 &Values[0], NumValues));
2270 void SelectionDAGLowering::visitTrunc(User &I) {
2271 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2272 SDValue N = getValue(I.getOperand(0));
2273 MVT DestVT = TLI.getValueType(I.getType());
2274 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
2277 void SelectionDAGLowering::visitZExt(User &I) {
2278 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2279 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2280 SDValue N = getValue(I.getOperand(0));
2281 MVT DestVT = TLI.getValueType(I.getType());
2282 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
2285 void SelectionDAGLowering::visitSExt(User &I) {
2286 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2287 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2288 SDValue N = getValue(I.getOperand(0));
2289 MVT DestVT = TLI.getValueType(I.getType());
2290 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
2293 void SelectionDAGLowering::visitFPTrunc(User &I) {
2294 // FPTrunc is never a no-op cast, no need to check
2295 SDValue N = getValue(I.getOperand(0));
2296 MVT DestVT = TLI.getValueType(I.getType());
2297 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2298 DestVT, N, DAG.getIntPtrConstant(0)));
2301 void SelectionDAGLowering::visitFPExt(User &I){
2302 // FPTrunc is never a no-op cast, no need to check
2303 SDValue N = getValue(I.getOperand(0));
2304 MVT DestVT = TLI.getValueType(I.getType());
2305 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
2308 void SelectionDAGLowering::visitFPToUI(User &I) {
2309 // FPToUI is never a no-op cast, no need to check
2310 SDValue N = getValue(I.getOperand(0));
2311 MVT DestVT = TLI.getValueType(I.getType());
2312 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
2315 void SelectionDAGLowering::visitFPToSI(User &I) {
2316 // FPToSI is never a no-op cast, no need to check
2317 SDValue N = getValue(I.getOperand(0));
2318 MVT DestVT = TLI.getValueType(I.getType());
2319 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
2322 void SelectionDAGLowering::visitUIToFP(User &I) {
2323 // UIToFP is never a no-op cast, no need to check
2324 SDValue N = getValue(I.getOperand(0));
2325 MVT DestVT = TLI.getValueType(I.getType());
2326 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
2329 void SelectionDAGLowering::visitSIToFP(User &I){
2330 // SIToFP is never a no-op cast, no need to check
2331 SDValue N = getValue(I.getOperand(0));
2332 MVT DestVT = TLI.getValueType(I.getType());
2333 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
2336 void SelectionDAGLowering::visitPtrToInt(User &I) {
2337 // What to do depends on the size of the integer and the size of the pointer.
2338 // We can either truncate, zero extend, or no-op, accordingly.
2339 SDValue N = getValue(I.getOperand(0));
2340 MVT SrcVT = N.getValueType();
2341 MVT DestVT = TLI.getValueType(I.getType());
2343 if (DestVT.bitsLT(SrcVT))
2344 Result = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N);
2346 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2347 Result = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N);
2348 setValue(&I, Result);
2351 void SelectionDAGLowering::visitIntToPtr(User &I) {
2352 // What to do depends on the size of the integer and the size of the pointer.
2353 // We can either truncate, zero extend, or no-op, accordingly.
2354 SDValue N = getValue(I.getOperand(0));
2355 MVT SrcVT = N.getValueType();
2356 MVT DestVT = TLI.getValueType(I.getType());
2357 if (DestVT.bitsLT(SrcVT))
2358 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
2360 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2361 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2365 void SelectionDAGLowering::visitBitCast(User &I) {
2366 SDValue N = getValue(I.getOperand(0));
2367 MVT DestVT = TLI.getValueType(I.getType());
2369 // BitCast assures us that source and destination are the same size so this
2370 // is either a BIT_CONVERT or a no-op.
2371 if (DestVT != N.getValueType())
2372 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
2373 DestVT, N)); // convert types
2375 setValue(&I, N); // noop cast.
2378 void SelectionDAGLowering::visitInsertElement(User &I) {
2379 SDValue InVec = getValue(I.getOperand(0));
2380 SDValue InVal = getValue(I.getOperand(1));
2381 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2383 getValue(I.getOperand(2)));
2385 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2386 TLI.getValueType(I.getType()),
2387 InVec, InVal, InIdx));
2390 void SelectionDAGLowering::visitExtractElement(User &I) {
2391 SDValue InVec = getValue(I.getOperand(0));
2392 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2394 getValue(I.getOperand(1)));
2395 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2396 TLI.getValueType(I.getType()), InVec, InIdx));
2400 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2401 // from SIndx and increasing to the element length (undefs are allowed).
2402 static bool SequentialMask(SDValue Mask, unsigned SIndx) {
2403 unsigned MaskNumElts = Mask.getNumOperands();
2404 for (unsigned i = 0; i != MaskNumElts; ++i) {
2405 if (Mask.getOperand(i).getOpcode() != ISD::UNDEF) {
2406 unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2407 if (Idx != i + SIndx)
2414 void SelectionDAGLowering::visitShuffleVector(User &I) {
2415 SDValue Src1 = getValue(I.getOperand(0));
2416 SDValue Src2 = getValue(I.getOperand(1));
2417 SDValue Mask = getValue(I.getOperand(2));
2419 MVT VT = TLI.getValueType(I.getType());
2420 MVT SrcVT = Src1.getValueType();
2421 int MaskNumElts = Mask.getNumOperands();
2422 int SrcNumElts = SrcVT.getVectorNumElements();
2424 if (SrcNumElts == MaskNumElts) {
2425 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(),
2426 VT, Src1, Src2, Mask));
2430 // Normalize the shuffle vector since mask and vector length don't match.
2431 MVT MaskEltVT = Mask.getValueType().getVectorElementType();
2433 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2434 // Mask is longer than the source vectors and is a multiple of the source
2435 // vectors. We can use concatenate vector to make the mask and vectors
2437 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2438 // The shuffle is concatenating two vectors together.
2439 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2444 // Pad both vectors with undefs to make them the same length as the mask.
2445 unsigned NumConcat = MaskNumElts / SrcNumElts;
2446 SDValue UndefVal = DAG.getUNDEF(SrcVT);
2448 SDValue* MOps1 = new SDValue[NumConcat];
2449 SDValue* MOps2 = new SDValue[NumConcat];
2452 for (unsigned i = 1; i != NumConcat; ++i) {
2453 MOps1[i] = UndefVal;
2454 MOps2[i] = UndefVal;
2456 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2457 VT, MOps1, NumConcat);
2458 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2459 VT, MOps2, NumConcat);
2464 // Readjust mask for new input vector length.
2465 SmallVector<SDValue, 8> MappedOps;
2466 for (int i = 0; i != MaskNumElts; ++i) {
2467 if (Mask.getOperand(i).getOpcode() == ISD::UNDEF) {
2468 MappedOps.push_back(Mask.getOperand(i));
2470 int Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2471 if (Idx < SrcNumElts)
2472 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2474 MappedOps.push_back(DAG.getConstant(Idx + MaskNumElts - SrcNumElts,
2478 Mask = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2479 Mask.getValueType(),
2480 &MappedOps[0], MappedOps.size());
2482 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(),
2483 VT, Src1, Src2, Mask));
2487 if (SrcNumElts > MaskNumElts) {
2488 // Resulting vector is shorter than the incoming vector.
2489 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,0)) {
2490 // Shuffle extracts 1st vector.
2495 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,MaskNumElts)) {
2496 // Shuffle extracts 2nd vector.
2501 // Analyze the access pattern of the vector to see if we can extract
2502 // two subvectors and do the shuffle. The analysis is done by calculating
2503 // the range of elements the mask access on both vectors.
2504 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2505 int MaxRange[2] = {-1, -1};
2507 for (int i = 0; i != MaskNumElts; ++i) {
2508 SDValue Arg = Mask.getOperand(i);
2509 if (Arg.getOpcode() != ISD::UNDEF) {
2510 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2511 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2513 if (Idx >= SrcNumElts) {
2517 if (Idx > MaxRange[Input])
2518 MaxRange[Input] = Idx;
2519 if (Idx < MinRange[Input])
2520 MinRange[Input] = Idx;
2524 // Check if the access is smaller than the vector size and can we find
2525 // a reasonable extract index.
2526 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
2527 int StartIdx[2]; // StartIdx to extract from
2528 for (int Input=0; Input < 2; ++Input) {
2529 if (MinRange[Input] == SrcNumElts+1 && MaxRange[Input] == -1) {
2530 RangeUse[Input] = 0; // Unused
2531 StartIdx[Input] = 0;
2532 } else if (MaxRange[Input] - MinRange[Input] < MaskNumElts) {
2533 // Fits within range but we should see if we can find a good
2534 // start index that is a multiple of the mask length.
2535 if (MaxRange[Input] < MaskNumElts) {
2536 RangeUse[Input] = 1; // Extract from beginning of the vector
2537 StartIdx[Input] = 0;
2539 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2540 if (MaxRange[Input] - StartIdx[Input] < MaskNumElts &&
2541 StartIdx[Input] + MaskNumElts < SrcNumElts)
2542 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2547 if (RangeUse[0] == 0 && RangeUse[0] == 0) {
2548 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
2551 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2552 // Extract appropriate subvector and generate a vector shuffle
2553 for (int Input=0; Input < 2; ++Input) {
2554 SDValue& Src = Input == 0 ? Src1 : Src2;
2555 if (RangeUse[Input] == 0) {
2556 Src = DAG.getUNDEF(VT);
2558 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
2559 Src, DAG.getIntPtrConstant(StartIdx[Input]));
2562 // Calculate new mask.
2563 SmallVector<SDValue, 8> MappedOps;
2564 for (int i = 0; i != MaskNumElts; ++i) {
2565 SDValue Arg = Mask.getOperand(i);
2566 if (Arg.getOpcode() == ISD::UNDEF) {
2567 MappedOps.push_back(Arg);
2569 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2570 if (Idx < SrcNumElts)
2571 MappedOps.push_back(DAG.getConstant(Idx - StartIdx[0], MaskEltVT));
2573 Idx = Idx - SrcNumElts - StartIdx[1] + MaskNumElts;
2574 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2578 Mask = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2579 Mask.getValueType(),
2580 &MappedOps[0], MappedOps.size());
2581 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, getCurDebugLoc(),
2582 VT, Src1, Src2, Mask));
2587 // We can't use either concat vectors or extract subvectors so fall back to
2588 // replacing the shuffle with extract and build vector.
2589 // to insert and build vector.
2590 MVT EltVT = VT.getVectorElementType();
2591 MVT PtrVT = TLI.getPointerTy();
2592 SmallVector<SDValue,8> Ops;
2593 for (int i = 0; i != MaskNumElts; ++i) {
2594 SDValue Arg = Mask.getOperand(i);
2595 if (Arg.getOpcode() == ISD::UNDEF) {
2596 Ops.push_back(DAG.getUNDEF(EltVT));
2598 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2599 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2600 if (Idx < SrcNumElts)
2601 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2602 EltVT, Src1, DAG.getConstant(Idx, PtrVT)));
2604 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2606 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
2609 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2610 VT, &Ops[0], Ops.size()));
2613 void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2614 const Value *Op0 = I.getOperand(0);
2615 const Value *Op1 = I.getOperand(1);
2616 const Type *AggTy = I.getType();
2617 const Type *ValTy = Op1->getType();
2618 bool IntoUndef = isa<UndefValue>(Op0);
2619 bool FromUndef = isa<UndefValue>(Op1);
2621 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2622 I.idx_begin(), I.idx_end());
2624 SmallVector<MVT, 4> AggValueVTs;
2625 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2626 SmallVector<MVT, 4> ValValueVTs;
2627 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2629 unsigned NumAggValues = AggValueVTs.size();
2630 unsigned NumValValues = ValValueVTs.size();
2631 SmallVector<SDValue, 4> Values(NumAggValues);
2633 SDValue Agg = getValue(Op0);
2634 SDValue Val = getValue(Op1);
2636 // Copy the beginning value(s) from the original aggregate.
2637 for (; i != LinearIndex; ++i)
2638 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2639 SDValue(Agg.getNode(), Agg.getResNo() + i);
2640 // Copy values from the inserted value(s).
2641 for (; i != LinearIndex + NumValValues; ++i)
2642 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2643 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2644 // Copy remaining value(s) from the original aggregate.
2645 for (; i != NumAggValues; ++i)
2646 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2647 SDValue(Agg.getNode(), Agg.getResNo() + i);
2649 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2650 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2651 &Values[0], NumAggValues));
2654 void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2655 const Value *Op0 = I.getOperand(0);
2656 const Type *AggTy = Op0->getType();
2657 const Type *ValTy = I.getType();
2658 bool OutOfUndef = isa<UndefValue>(Op0);
2660 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2661 I.idx_begin(), I.idx_end());
2663 SmallVector<MVT, 4> ValValueVTs;
2664 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2666 unsigned NumValValues = ValValueVTs.size();
2667 SmallVector<SDValue, 4> Values(NumValValues);
2669 SDValue Agg = getValue(Op0);
2670 // Copy out the selected value(s).
2671 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2672 Values[i - LinearIndex] =
2674 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2675 SDValue(Agg.getNode(), Agg.getResNo() + i);
2677 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2678 DAG.getVTList(&ValValueVTs[0], NumValValues),
2679 &Values[0], NumValValues));
2683 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2684 SDValue N = getValue(I.getOperand(0));
2685 const Type *Ty = I.getOperand(0)->getType();
2687 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2690 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2691 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2694 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2695 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2696 DAG.getIntPtrConstant(Offset));
2698 Ty = StTy->getElementType(Field);
2700 Ty = cast<SequentialType>(Ty)->getElementType();
2702 // If this is a constant subscript, handle it quickly.
2703 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2704 if (CI->getZExtValue() == 0) continue;
2706 TD->getTypePaddedSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2708 unsigned PtrBits = TLI.getPointerTy().getSizeInBits();
2710 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2712 DAG.getConstant(Offs, MVT::i64));
2714 OffsVal = DAG.getIntPtrConstant(Offs);
2715 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2720 // N = N + Idx * ElementSize;
2721 uint64_t ElementSize = TD->getTypePaddedSize(Ty);
2722 SDValue IdxN = getValue(Idx);
2724 // If the index is smaller or larger than intptr_t, truncate or extend
2726 if (IdxN.getValueType().bitsLT(N.getValueType()))
2727 IdxN = DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(),
2728 N.getValueType(), IdxN);
2729 else if (IdxN.getValueType().bitsGT(N.getValueType()))
2730 IdxN = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2731 N.getValueType(), IdxN);
2733 // If this is a multiply by a power of two, turn it into a shl
2734 // immediately. This is a very common case.
2735 if (ElementSize != 1) {
2736 if (isPowerOf2_64(ElementSize)) {
2737 unsigned Amt = Log2_64(ElementSize);
2738 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
2739 N.getValueType(), IdxN,
2740 DAG.getConstant(Amt, TLI.getPointerTy()));
2742 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2743 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
2744 N.getValueType(), IdxN, Scale);
2748 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2749 N.getValueType(), N, IdxN);
2755 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2756 // If this is a fixed sized alloca in the entry block of the function,
2757 // allocate it statically on the stack.
2758 if (FuncInfo.StaticAllocaMap.count(&I))
2759 return; // getValue will auto-populate this.
2761 const Type *Ty = I.getAllocatedType();
2762 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
2764 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2767 SDValue AllocSize = getValue(I.getArraySize());
2769 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2771 DAG.getConstant(TySize, AllocSize.getValueType()));
2775 MVT IntPtr = TLI.getPointerTy();
2776 if (IntPtr.bitsLT(AllocSize.getValueType()))
2777 AllocSize = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2779 else if (IntPtr.bitsGT(AllocSize.getValueType()))
2780 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2783 // Handle alignment. If the requested alignment is less than or equal to
2784 // the stack alignment, ignore it. If the size is greater than or equal to
2785 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2786 unsigned StackAlign =
2787 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2788 if (Align <= StackAlign)
2791 // Round the size of the allocation up to the stack alignment size
2792 // by add SA-1 to the size.
2793 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2794 AllocSize.getValueType(), AllocSize,
2795 DAG.getIntPtrConstant(StackAlign-1));
2796 // Mask out the low bits for alignment purposes.
2797 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
2798 AllocSize.getValueType(), AllocSize,
2799 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2801 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2802 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2804 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
2807 DAG.setRoot(DSA.getValue(1));
2809 // Inform the Frame Information that we have just allocated a variable-sized
2811 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2814 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2815 const Value *SV = I.getOperand(0);
2816 SDValue Ptr = getValue(SV);
2818 const Type *Ty = I.getType();
2819 bool isVolatile = I.isVolatile();
2820 unsigned Alignment = I.getAlignment();
2822 SmallVector<MVT, 4> ValueVTs;
2823 SmallVector<uint64_t, 4> Offsets;
2824 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2825 unsigned NumValues = ValueVTs.size();
2830 bool ConstantMemory = false;
2832 // Serialize volatile loads with other side effects.
2834 else if (AA->pointsToConstantMemory(SV)) {
2835 // Do not serialize (non-volatile) loads of constant memory with anything.
2836 Root = DAG.getEntryNode();
2837 ConstantMemory = true;
2839 // Do not serialize non-volatile loads against each other.
2840 Root = DAG.getRoot();
2843 SmallVector<SDValue, 4> Values(NumValues);
2844 SmallVector<SDValue, 4> Chains(NumValues);
2845 MVT PtrVT = Ptr.getValueType();
2846 for (unsigned i = 0; i != NumValues; ++i) {
2847 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
2848 DAG.getNode(ISD::ADD, getCurDebugLoc(),
2850 DAG.getConstant(Offsets[i], PtrVT)),
2852 isVolatile, Alignment);
2854 Chains[i] = L.getValue(1);
2857 if (!ConstantMemory) {
2858 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2860 &Chains[0], NumValues);
2864 PendingLoads.push_back(Chain);
2867 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2868 DAG.getVTList(&ValueVTs[0], NumValues),
2869 &Values[0], NumValues));
2873 void SelectionDAGLowering::visitStore(StoreInst &I) {
2874 Value *SrcV = I.getOperand(0);
2875 Value *PtrV = I.getOperand(1);
2877 SmallVector<MVT, 4> ValueVTs;
2878 SmallVector<uint64_t, 4> Offsets;
2879 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2880 unsigned NumValues = ValueVTs.size();
2884 // Get the lowered operands. Note that we do this after
2885 // checking if NumResults is zero, because with zero results
2886 // the operands won't have values in the map.
2887 SDValue Src = getValue(SrcV);
2888 SDValue Ptr = getValue(PtrV);
2890 SDValue Root = getRoot();
2891 SmallVector<SDValue, 4> Chains(NumValues);
2892 MVT PtrVT = Ptr.getValueType();
2893 bool isVolatile = I.isVolatile();
2894 unsigned Alignment = I.getAlignment();
2895 for (unsigned i = 0; i != NumValues; ++i)
2896 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
2897 SDValue(Src.getNode(), Src.getResNo() + i),
2898 DAG.getNode(ISD::ADD, getCurDebugLoc(),
2900 DAG.getConstant(Offsets[i], PtrVT)),
2902 isVolatile, Alignment);
2904 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2905 MVT::Other, &Chains[0], NumValues));
2908 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2910 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2911 unsigned Intrinsic) {
2912 bool HasChain = !I.doesNotAccessMemory();
2913 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2915 // Build the operand list.
2916 SmallVector<SDValue, 8> Ops;
2917 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2919 // We don't need to serialize loads against other loads.
2920 Ops.push_back(DAG.getRoot());
2922 Ops.push_back(getRoot());
2926 // Info is set by getTgtMemInstrinsic
2927 TargetLowering::IntrinsicInfo Info;
2928 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2930 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
2931 if (!IsTgtIntrinsic)
2932 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2934 // Add all operands of the call to the operand list.
2935 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2936 SDValue Op = getValue(I.getOperand(i));
2937 assert(TLI.isTypeLegal(Op.getValueType()) &&
2938 "Intrinsic uses a non-legal type?");
2942 std::vector<MVT> VTs;
2943 if (I.getType() != Type::VoidTy) {
2944 MVT VT = TLI.getValueType(I.getType());
2945 if (VT.isVector()) {
2946 const VectorType *DestTy = cast<VectorType>(I.getType());
2947 MVT EltVT = TLI.getValueType(DestTy->getElementType());
2949 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2950 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2953 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2957 VTs.push_back(MVT::Other);
2959 const MVT *VTList = DAG.getNodeValueTypes(VTs);
2963 if (IsTgtIntrinsic) {
2964 // This is target intrinsic that touches memory
2965 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
2967 &Ops[0], Ops.size(),
2968 Info.memVT, Info.ptrVal, Info.offset,
2969 Info.align, Info.vol,
2970 Info.readMem, Info.writeMem);
2973 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
2975 &Ops[0], Ops.size());
2976 else if (I.getType() != Type::VoidTy)
2977 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
2979 &Ops[0], Ops.size());
2981 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
2983 &Ops[0], Ops.size());
2986 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2988 PendingLoads.push_back(Chain);
2992 if (I.getType() != Type::VoidTy) {
2993 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2994 MVT VT = TLI.getValueType(PTy);
2995 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
2997 setValue(&I, Result);
3001 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
3002 static GlobalVariable *ExtractTypeInfo(Value *V) {
3003 V = V->stripPointerCasts();
3004 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
3005 assert ((GV || isa<ConstantPointerNull>(V)) &&
3006 "TypeInfo must be a global variable or NULL");
3012 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
3013 /// call, and add them to the specified machine basic block.
3014 void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
3015 MachineBasicBlock *MBB) {
3016 // Inform the MachineModuleInfo of the personality for this landing pad.
3017 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
3018 assert(CE->getOpcode() == Instruction::BitCast &&
3019 isa<Function>(CE->getOperand(0)) &&
3020 "Personality should be a function");
3021 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
3023 // Gather all the type infos for this landing pad and pass them along to
3024 // MachineModuleInfo.
3025 std::vector<GlobalVariable *> TyInfo;
3026 unsigned N = I.getNumOperands();
3028 for (unsigned i = N - 1; i > 2; --i) {
3029 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
3030 unsigned FilterLength = CI->getZExtValue();
3031 unsigned FirstCatch = i + FilterLength + !FilterLength;
3032 assert (FirstCatch <= N && "Invalid filter length");
3034 if (FirstCatch < N) {
3035 TyInfo.reserve(N - FirstCatch);
3036 for (unsigned j = FirstCatch; j < N; ++j)
3037 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3038 MMI->addCatchTypeInfo(MBB, TyInfo);
3042 if (!FilterLength) {
3044 MMI->addCleanup(MBB);
3047 TyInfo.reserve(FilterLength - 1);
3048 for (unsigned j = i + 1; j < FirstCatch; ++j)
3049 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3050 MMI->addFilterTypeInfo(MBB, TyInfo);
3059 TyInfo.reserve(N - 3);
3060 for (unsigned j = 3; j < N; ++j)
3061 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
3062 MMI->addCatchTypeInfo(MBB, TyInfo);
3068 /// GetSignificand - Get the significand and build it into a floating-point
3069 /// number with exponent of 1:
3071 /// Op = (Op & 0x007fffff) | 0x3f800000;
3073 /// where Op is the hexidecimal representation of floating point value.
3075 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
3076 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3077 DAG.getConstant(0x007fffff, MVT::i32));
3078 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3079 DAG.getConstant(0x3f800000, MVT::i32));
3080 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
3083 /// GetExponent - Get the exponent:
3085 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3087 /// where Op is the hexidecimal representation of floating point value.
3089 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3091 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3092 DAG.getConstant(0x7f800000, MVT::i32));
3093 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3094 DAG.getConstant(23, TLI.getPointerTy()));
3095 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3096 DAG.getConstant(127, MVT::i32));
3097 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3100 /// getF32Constant - Get 32-bit floating point constant.
3102 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3103 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3106 /// Inlined utility function to implement binary input atomic intrinsics for
3107 /// visitIntrinsicCall: I is a call instruction
3108 /// Op is the associated NodeType for I
3110 SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
3111 SDValue Root = getRoot();
3113 DAG.getAtomic(Op, getCurDebugLoc(),
3114 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
3116 getValue(I.getOperand(1)),
3117 getValue(I.getOperand(2)),
3120 DAG.setRoot(L.getValue(1));
3124 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
3126 SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
3127 SDValue Op1 = getValue(I.getOperand(1));
3128 SDValue Op2 = getValue(I.getOperand(2));
3130 MVT ValueVTs[] = { Op1.getValueType(), MVT::i1 };
3131 SDValue Ops[] = { Op1, Op2 };
3133 SDValue Result = DAG.getNode(Op, getCurDebugLoc(),
3134 DAG.getVTList(&ValueVTs[0], 2), &Ops[0], 2);
3136 setValue(&I, Result);
3140 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
3141 /// limited-precision mode.
3143 SelectionDAGLowering::visitExp(CallInst &I) {
3145 DebugLoc dl = getCurDebugLoc();
3147 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3148 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3149 SDValue Op = getValue(I.getOperand(1));
3151 // Put the exponent in the right bit position for later addition to the
3154 // #define LOG2OFe 1.4426950f
3155 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3156 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3157 getF32Constant(DAG, 0x3fb8aa3b));
3158 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3160 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3161 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3162 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3164 // IntegerPartOfX <<= 23;
3165 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3166 DAG.getConstant(23, TLI.getPointerTy()));
3168 if (LimitFloatPrecision <= 6) {
3169 // For floating-point precision of 6:
3171 // TwoToFractionalPartOfX =
3173 // (0.735607626f + 0.252464424f * x) * x;
3175 // error 0.0144103317, which is 6 bits
3176 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3177 getF32Constant(DAG, 0x3e814304));
3178 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3179 getF32Constant(DAG, 0x3f3c50c8));
3180 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3181 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3182 getF32Constant(DAG, 0x3f7f5e7e));
3183 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
3185 // Add the exponent into the result in integer domain.
3186 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3187 TwoToFracPartOfX, IntegerPartOfX);
3189 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
3190 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3191 // For floating-point precision of 12:
3193 // TwoToFractionalPartOfX =
3196 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3198 // 0.000107046256 error, which is 13 to 14 bits
3199 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3200 getF32Constant(DAG, 0x3da235e3));
3201 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3202 getF32Constant(DAG, 0x3e65b8f3));
3203 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3204 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3205 getF32Constant(DAG, 0x3f324b07));
3206 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3207 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3208 getF32Constant(DAG, 0x3f7ff8fd));
3209 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
3211 // Add the exponent into the result in integer domain.
3212 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3213 TwoToFracPartOfX, IntegerPartOfX);
3215 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
3216 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3217 // For floating-point precision of 18:
3219 // TwoToFractionalPartOfX =
3223 // (0.554906021e-1f +
3224 // (0.961591928e-2f +
3225 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3227 // error 2.47208000*10^(-7), which is better than 18 bits
3228 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3229 getF32Constant(DAG, 0x3924b03e));
3230 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3231 getF32Constant(DAG, 0x3ab24b87));
3232 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3233 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3234 getF32Constant(DAG, 0x3c1d8c17));
3235 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3236 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3237 getF32Constant(DAG, 0x3d634a1d));
3238 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3239 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3240 getF32Constant(DAG, 0x3e75fe14));
3241 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3242 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3243 getF32Constant(DAG, 0x3f317234));
3244 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3245 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3246 getF32Constant(DAG, 0x3f800000));
3247 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
3250 // Add the exponent into the result in integer domain.
3251 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3252 TwoToFracPartOfX, IntegerPartOfX);
3254 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
3257 // No special expansion.
3258 result = DAG.getNode(ISD::FEXP, dl,
3259 getValue(I.getOperand(1)).getValueType(),
3260 getValue(I.getOperand(1)));
3263 setValue(&I, result);
3266 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3267 /// limited-precision mode.
3269 SelectionDAGLowering::visitLog(CallInst &I) {
3271 DebugLoc dl = getCurDebugLoc();
3273 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3274 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3275 SDValue Op = getValue(I.getOperand(1));
3276 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3278 // Scale the exponent by log(2) [0.69314718f].
3279 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3280 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3281 getF32Constant(DAG, 0x3f317218));
3283 // Get the significand and build it into a floating-point number with
3285 SDValue X = GetSignificand(DAG, Op1, dl);
3287 if (LimitFloatPrecision <= 6) {
3288 // For floating-point precision of 6:
3292 // (1.4034025f - 0.23903021f * x) * x;
3294 // error 0.0034276066, which is better than 8 bits
3295 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3296 getF32Constant(DAG, 0xbe74c456));
3297 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3298 getF32Constant(DAG, 0x3fb3a2b1));
3299 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3300 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3301 getF32Constant(DAG, 0x3f949a29));
3303 result = DAG.getNode(ISD::FADD, dl,
3304 MVT::f32, LogOfExponent, LogOfMantissa);
3305 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3306 // For floating-point precision of 12:
3312 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3314 // error 0.000061011436, which is 14 bits
3315 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3316 getF32Constant(DAG, 0xbd67b6d6));
3317 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3318 getF32Constant(DAG, 0x3ee4f4b8));
3319 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3320 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3321 getF32Constant(DAG, 0x3fbc278b));
3322 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3323 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3324 getF32Constant(DAG, 0x40348e95));
3325 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3326 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3327 getF32Constant(DAG, 0x3fdef31a));
3329 result = DAG.getNode(ISD::FADD, dl,
3330 MVT::f32, LogOfExponent, LogOfMantissa);
3331 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3332 // For floating-point precision of 18:
3340 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3342 // error 0.0000023660568, which is better than 18 bits
3343 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3344 getF32Constant(DAG, 0xbc91e5ac));
3345 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3346 getF32Constant(DAG, 0x3e4350aa));
3347 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3348 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3349 getF32Constant(DAG, 0x3f60d3e3));
3350 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3351 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3352 getF32Constant(DAG, 0x4011cdf0));
3353 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3354 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3355 getF32Constant(DAG, 0x406cfd1c));
3356 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3357 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3358 getF32Constant(DAG, 0x408797cb));
3359 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3360 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3361 getF32Constant(DAG, 0x4006dcab));
3363 result = DAG.getNode(ISD::FADD, dl,
3364 MVT::f32, LogOfExponent, LogOfMantissa);
3367 // No special expansion.
3368 result = DAG.getNode(ISD::FLOG, dl,
3369 getValue(I.getOperand(1)).getValueType(),
3370 getValue(I.getOperand(1)));
3373 setValue(&I, result);
3376 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3377 /// limited-precision mode.
3379 SelectionDAGLowering::visitLog2(CallInst &I) {
3381 DebugLoc dl = getCurDebugLoc();
3383 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3384 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3385 SDValue Op = getValue(I.getOperand(1));
3386 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3388 // Get the exponent.
3389 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
3391 // Get the significand and build it into a floating-point number with
3393 SDValue X = GetSignificand(DAG, Op1, dl);
3395 // Different possible minimax approximations of significand in
3396 // floating-point for various degrees of accuracy over [1,2].
3397 if (LimitFloatPrecision <= 6) {
3398 // For floating-point precision of 6:
3400 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3402 // error 0.0049451742, which is more than 7 bits
3403 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3404 getF32Constant(DAG, 0xbeb08fe0));
3405 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3406 getF32Constant(DAG, 0x40019463));
3407 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3408 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3409 getF32Constant(DAG, 0x3fd6633d));
3411 result = DAG.getNode(ISD::FADD, dl,
3412 MVT::f32, LogOfExponent, Log2ofMantissa);
3413 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3414 // For floating-point precision of 12:
3420 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3422 // error 0.0000876136000, which is better than 13 bits
3423 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3424 getF32Constant(DAG, 0xbda7262e));
3425 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3426 getF32Constant(DAG, 0x3f25280b));
3427 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3428 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3429 getF32Constant(DAG, 0x4007b923));
3430 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3431 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3432 getF32Constant(DAG, 0x40823e2f));
3433 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3434 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3435 getF32Constant(DAG, 0x4020d29c));
3437 result = DAG.getNode(ISD::FADD, dl,
3438 MVT::f32, LogOfExponent, Log2ofMantissa);
3439 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3440 // For floating-point precision of 18:
3449 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3451 // error 0.0000018516, which is better than 18 bits
3452 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3453 getF32Constant(DAG, 0xbcd2769e));
3454 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3455 getF32Constant(DAG, 0x3e8ce0b9));
3456 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3457 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3458 getF32Constant(DAG, 0x3fa22ae7));
3459 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3460 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3461 getF32Constant(DAG, 0x40525723));
3462 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3463 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3464 getF32Constant(DAG, 0x40aaf200));
3465 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3466 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3467 getF32Constant(DAG, 0x40c39dad));
3468 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3469 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3470 getF32Constant(DAG, 0x4042902c));
3472 result = DAG.getNode(ISD::FADD, dl,
3473 MVT::f32, LogOfExponent, Log2ofMantissa);
3476 // No special expansion.
3477 result = DAG.getNode(ISD::FLOG2, dl,
3478 getValue(I.getOperand(1)).getValueType(),
3479 getValue(I.getOperand(1)));
3482 setValue(&I, result);
3485 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3486 /// limited-precision mode.
3488 SelectionDAGLowering::visitLog10(CallInst &I) {
3490 DebugLoc dl = getCurDebugLoc();
3492 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3493 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3494 SDValue Op = getValue(I.getOperand(1));
3495 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3497 // Scale the exponent by log10(2) [0.30102999f].
3498 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3499 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3500 getF32Constant(DAG, 0x3e9a209a));
3502 // Get the significand and build it into a floating-point number with
3504 SDValue X = GetSignificand(DAG, Op1, dl);
3506 if (LimitFloatPrecision <= 6) {
3507 // For floating-point precision of 6:
3509 // Log10ofMantissa =
3511 // (0.60948995f - 0.10380950f * x) * x;
3513 // error 0.0014886165, which is 6 bits
3514 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3515 getF32Constant(DAG, 0xbdd49a13));
3516 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3517 getF32Constant(DAG, 0x3f1c0789));
3518 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3519 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3520 getF32Constant(DAG, 0x3f011300));
3522 result = DAG.getNode(ISD::FADD, dl,
3523 MVT::f32, LogOfExponent, Log10ofMantissa);
3524 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3525 // For floating-point precision of 12:
3527 // Log10ofMantissa =
3530 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3532 // error 0.00019228036, which is better than 12 bits
3533 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3534 getF32Constant(DAG, 0x3d431f31));
3535 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3536 getF32Constant(DAG, 0x3ea21fb2));
3537 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3538 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3539 getF32Constant(DAG, 0x3f6ae232));
3540 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3541 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3542 getF32Constant(DAG, 0x3f25f7c3));
3544 result = DAG.getNode(ISD::FADD, dl,
3545 MVT::f32, LogOfExponent, Log10ofMantissa);
3546 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3547 // For floating-point precision of 18:
3549 // Log10ofMantissa =
3554 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3556 // error 0.0000037995730, which is better than 18 bits
3557 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3558 getF32Constant(DAG, 0x3c5d51ce));
3559 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3560 getF32Constant(DAG, 0x3e00685a));
3561 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3562 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3563 getF32Constant(DAG, 0x3efb6798));
3564 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3565 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3566 getF32Constant(DAG, 0x3f88d192));
3567 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3568 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3569 getF32Constant(DAG, 0x3fc4316c));
3570 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3571 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
3572 getF32Constant(DAG, 0x3f57ce70));
3574 result = DAG.getNode(ISD::FADD, dl,
3575 MVT::f32, LogOfExponent, Log10ofMantissa);
3578 // No special expansion.
3579 result = DAG.getNode(ISD::FLOG10, dl,
3580 getValue(I.getOperand(1)).getValueType(),
3581 getValue(I.getOperand(1)));
3584 setValue(&I, result);
3587 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3588 /// limited-precision mode.
3590 SelectionDAGLowering::visitExp2(CallInst &I) {
3592 DebugLoc dl = getCurDebugLoc();
3594 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3595 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3596 SDValue Op = getValue(I.getOperand(1));
3598 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
3600 // FractionalPartOfX = x - (float)IntegerPartOfX;
3601 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3602 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
3604 // IntegerPartOfX <<= 23;
3605 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3606 DAG.getConstant(23, TLI.getPointerTy()));
3608 if (LimitFloatPrecision <= 6) {
3609 // For floating-point precision of 6:
3611 // TwoToFractionalPartOfX =
3613 // (0.735607626f + 0.252464424f * x) * x;
3615 // error 0.0144103317, which is 6 bits
3616 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3617 getF32Constant(DAG, 0x3e814304));
3618 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3619 getF32Constant(DAG, 0x3f3c50c8));
3620 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3621 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3622 getF32Constant(DAG, 0x3f7f5e7e));
3623 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3624 SDValue TwoToFractionalPartOfX =
3625 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3627 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3628 MVT::f32, TwoToFractionalPartOfX);
3629 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3630 // For floating-point precision of 12:
3632 // TwoToFractionalPartOfX =
3635 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3637 // error 0.000107046256, which is 13 to 14 bits
3638 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3639 getF32Constant(DAG, 0x3da235e3));
3640 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3641 getF32Constant(DAG, 0x3e65b8f3));
3642 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3643 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3644 getF32Constant(DAG, 0x3f324b07));
3645 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3646 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3647 getF32Constant(DAG, 0x3f7ff8fd));
3648 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3649 SDValue TwoToFractionalPartOfX =
3650 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3652 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3653 MVT::f32, TwoToFractionalPartOfX);
3654 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3655 // For floating-point precision of 18:
3657 // TwoToFractionalPartOfX =
3661 // (0.554906021e-1f +
3662 // (0.961591928e-2f +
3663 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3664 // error 2.47208000*10^(-7), which is better than 18 bits
3665 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3666 getF32Constant(DAG, 0x3924b03e));
3667 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3668 getF32Constant(DAG, 0x3ab24b87));
3669 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3670 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3671 getF32Constant(DAG, 0x3c1d8c17));
3672 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3673 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3674 getF32Constant(DAG, 0x3d634a1d));
3675 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3676 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3677 getF32Constant(DAG, 0x3e75fe14));
3678 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3679 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3680 getF32Constant(DAG, 0x3f317234));
3681 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3682 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3683 getF32Constant(DAG, 0x3f800000));
3684 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3685 SDValue TwoToFractionalPartOfX =
3686 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3688 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3689 MVT::f32, TwoToFractionalPartOfX);
3692 // No special expansion.
3693 result = DAG.getNode(ISD::FEXP2, dl,
3694 getValue(I.getOperand(1)).getValueType(),
3695 getValue(I.getOperand(1)));
3698 setValue(&I, result);
3701 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3702 /// limited-precision mode with x == 10.0f.
3704 SelectionDAGLowering::visitPow(CallInst &I) {
3706 Value *Val = I.getOperand(1);
3707 DebugLoc dl = getCurDebugLoc();
3708 bool IsExp10 = false;
3710 if (getValue(Val).getValueType() == MVT::f32 &&
3711 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
3712 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3713 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3714 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3716 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3721 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3722 SDValue Op = getValue(I.getOperand(2));
3724 // Put the exponent in the right bit position for later addition to the
3727 // #define LOG2OF10 3.3219281f
3728 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3729 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3730 getF32Constant(DAG, 0x40549a78));
3731 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3733 // FractionalPartOfX = x - (float)IntegerPartOfX;
3734 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3735 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3737 // IntegerPartOfX <<= 23;
3738 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3739 DAG.getConstant(23, TLI.getPointerTy()));
3741 if (LimitFloatPrecision <= 6) {
3742 // For floating-point precision of 6:
3744 // twoToFractionalPartOfX =
3746 // (0.735607626f + 0.252464424f * x) * x;
3748 // error 0.0144103317, which is 6 bits
3749 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3750 getF32Constant(DAG, 0x3e814304));
3751 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3752 getF32Constant(DAG, 0x3f3c50c8));
3753 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3754 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3755 getF32Constant(DAG, 0x3f7f5e7e));
3756 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3757 SDValue TwoToFractionalPartOfX =
3758 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3760 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3761 MVT::f32, TwoToFractionalPartOfX);
3762 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3763 // For floating-point precision of 12:
3765 // TwoToFractionalPartOfX =
3768 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3770 // error 0.000107046256, which is 13 to 14 bits
3771 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3772 getF32Constant(DAG, 0x3da235e3));
3773 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3774 getF32Constant(DAG, 0x3e65b8f3));
3775 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3776 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3777 getF32Constant(DAG, 0x3f324b07));
3778 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3779 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3780 getF32Constant(DAG, 0x3f7ff8fd));
3781 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3782 SDValue TwoToFractionalPartOfX =
3783 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3785 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3786 MVT::f32, TwoToFractionalPartOfX);
3787 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3788 // For floating-point precision of 18:
3790 // TwoToFractionalPartOfX =
3794 // (0.554906021e-1f +
3795 // (0.961591928e-2f +
3796 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3797 // error 2.47208000*10^(-7), which is better than 18 bits
3798 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3799 getF32Constant(DAG, 0x3924b03e));
3800 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3801 getF32Constant(DAG, 0x3ab24b87));
3802 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3803 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3804 getF32Constant(DAG, 0x3c1d8c17));
3805 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3806 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3807 getF32Constant(DAG, 0x3d634a1d));
3808 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3809 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3810 getF32Constant(DAG, 0x3e75fe14));
3811 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3812 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3813 getF32Constant(DAG, 0x3f317234));
3814 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3815 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3816 getF32Constant(DAG, 0x3f800000));
3817 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3818 SDValue TwoToFractionalPartOfX =
3819 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3821 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3822 MVT::f32, TwoToFractionalPartOfX);
3825 // No special expansion.
3826 result = DAG.getNode(ISD::FPOW, dl,
3827 getValue(I.getOperand(1)).getValueType(),
3828 getValue(I.getOperand(1)),
3829 getValue(I.getOperand(2)));
3832 setValue(&I, result);
3835 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3836 /// we want to emit this as a call to a named external function, return the name
3837 /// otherwise lower it and return null.
3839 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3840 DebugLoc dl = getCurDebugLoc();
3841 switch (Intrinsic) {
3843 // By default, turn this into a target intrinsic node.
3844 visitTargetIntrinsic(I, Intrinsic);
3846 case Intrinsic::vastart: visitVAStart(I); return 0;
3847 case Intrinsic::vaend: visitVAEnd(I); return 0;
3848 case Intrinsic::vacopy: visitVACopy(I); return 0;
3849 case Intrinsic::returnaddress:
3850 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
3851 getValue(I.getOperand(1))));
3853 case Intrinsic::frameaddress:
3854 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
3855 getValue(I.getOperand(1))));
3857 case Intrinsic::setjmp:
3858 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3860 case Intrinsic::longjmp:
3861 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3863 case Intrinsic::memcpy: {
3864 SDValue Op1 = getValue(I.getOperand(1));
3865 SDValue Op2 = getValue(I.getOperand(2));
3866 SDValue Op3 = getValue(I.getOperand(3));
3867 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3868 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
3869 I.getOperand(1), 0, I.getOperand(2), 0));
3872 case Intrinsic::memset: {
3873 SDValue Op1 = getValue(I.getOperand(1));
3874 SDValue Op2 = getValue(I.getOperand(2));
3875 SDValue Op3 = getValue(I.getOperand(3));
3876 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3877 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
3878 I.getOperand(1), 0));
3881 case Intrinsic::memmove: {
3882 SDValue Op1 = getValue(I.getOperand(1));
3883 SDValue Op2 = getValue(I.getOperand(2));
3884 SDValue Op3 = getValue(I.getOperand(3));
3885 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3887 // If the source and destination are known to not be aliases, we can
3888 // lower memmove as memcpy.
3889 uint64_t Size = -1ULL;
3890 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3891 Size = C->getZExtValue();
3892 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3893 AliasAnalysis::NoAlias) {
3894 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
3895 I.getOperand(1), 0, I.getOperand(2), 0));
3899 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
3900 I.getOperand(1), 0, I.getOperand(2), 0));
3903 case Intrinsic::dbg_stoppoint: {
3904 DwarfWriter *DW = DAG.getDwarfWriter();
3905 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3906 if (DW && DW->ValidDebugInfo(SPI.getContext())) {
3907 MachineFunction &MF = DAG.getMachineFunction();
3909 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3913 DICompileUnit CU(cast<GlobalVariable>(SPI.getContext()));
3914 std::string Dir, FN;
3915 unsigned SrcFile = DW->getOrCreateSourceID(CU.getDirectory(Dir),
3916 CU.getFilename(FN));
3917 unsigned idx = MF.getOrCreateDebugLocID(SrcFile,
3918 SPI.getLine(), SPI.getColumn());
3919 setCurDebugLoc(DebugLoc::get(idx));
3923 case Intrinsic::dbg_region_start: {
3924 DwarfWriter *DW = DAG.getDwarfWriter();
3925 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3926 if (DW && DW->ValidDebugInfo(RSI.getContext())) {
3928 DW->RecordRegionStart(cast<GlobalVariable>(RSI.getContext()));
3929 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3930 getRoot(), LabelID));
3935 case Intrinsic::dbg_region_end: {
3936 DwarfWriter *DW = DAG.getDwarfWriter();
3937 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3938 if (DW && DW->ValidDebugInfo(REI.getContext())) {
3940 DW->RecordRegionEnd(cast<GlobalVariable>(REI.getContext()));
3941 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3942 getRoot(), LabelID));
3947 case Intrinsic::dbg_func_start: {
3948 DwarfWriter *DW = DAG.getDwarfWriter();
3950 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3951 Value *SP = FSI.getSubprogram();
3952 if (SP && DW->ValidDebugInfo(SP)) {
3953 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3954 // what (most?) gdb expects.
3955 MachineFunction &MF = DAG.getMachineFunction();
3956 DISubprogram Subprogram(cast<GlobalVariable>(SP));
3957 DICompileUnit CompileUnit = Subprogram.getCompileUnit();
3958 std::string Dir, FN;
3959 unsigned SrcFile = DW->getOrCreateSourceID(CompileUnit.getDirectory(Dir),
3960 CompileUnit.getFilename(FN));
3962 // Record the source line but does not create a label for the normal
3963 // function start. It will be emitted at asm emission time. However,
3964 // create a label if this is a beginning of inlined function.
3965 unsigned Line = Subprogram.getLineNumber();
3968 unsigned LabelID = DW->RecordSourceLine(Line, 0, SrcFile);
3969 if (DW->getRecordSourceLineCount() != 1)
3970 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getCurDebugLoc(),
3971 getRoot(), LabelID));
3974 setCurDebugLoc(DebugLoc::get(MF.getOrCreateDebugLocID(SrcFile, Line, 0)));
3979 case Intrinsic::dbg_declare: {
3981 DwarfWriter *DW = DAG.getDwarfWriter();
3982 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3983 Value *Variable = DI.getVariable();
3984 if (DW && DW->ValidDebugInfo(Variable))
3985 DAG.setRoot(DAG.getNode(ISD::DECLARE, dl, MVT::Other, getRoot(),
3986 getValue(DI.getAddress()), getValue(Variable)));
3988 // FIXME: Do something sensible here when we support debug declare.
3992 case Intrinsic::eh_exception: {
3993 if (!CurMBB->isLandingPad()) {
3994 // FIXME: Mark exception register as live in. Hack for PR1508.
3995 unsigned Reg = TLI.getExceptionAddressRegister();
3996 if (Reg) CurMBB->addLiveIn(Reg);
3998 // Insert the EXCEPTIONADDR instruction.
3999 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4001 Ops[0] = DAG.getRoot();
4002 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
4004 DAG.setRoot(Op.getValue(1));
4008 case Intrinsic::eh_selector_i32:
4009 case Intrinsic::eh_selector_i64: {
4010 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4011 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
4012 MVT::i32 : MVT::i64);
4015 if (CurMBB->isLandingPad())
4016 AddCatchInfo(I, MMI, CurMBB);
4019 FuncInfo.CatchInfoLost.insert(&I);
4021 // FIXME: Mark exception selector register as live in. Hack for PR1508.
4022 unsigned Reg = TLI.getExceptionSelectorRegister();
4023 if (Reg) CurMBB->addLiveIn(Reg);
4026 // Insert the EHSELECTION instruction.
4027 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
4029 Ops[0] = getValue(I.getOperand(1));
4031 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
4033 DAG.setRoot(Op.getValue(1));
4035 setValue(&I, DAG.getConstant(0, VT));
4041 case Intrinsic::eh_typeid_for_i32:
4042 case Intrinsic::eh_typeid_for_i64: {
4043 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4044 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
4045 MVT::i32 : MVT::i64);
4048 // Find the type id for the given typeinfo.
4049 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
4051 unsigned TypeID = MMI->getTypeIDFor(GV);
4052 setValue(&I, DAG.getConstant(TypeID, VT));
4054 // Return something different to eh_selector.
4055 setValue(&I, DAG.getConstant(1, VT));
4061 case Intrinsic::eh_return_i32:
4062 case Intrinsic::eh_return_i64:
4063 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4064 MMI->setCallsEHReturn(true);
4065 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
4068 getValue(I.getOperand(1)),
4069 getValue(I.getOperand(2))));
4071 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
4075 case Intrinsic::eh_unwind_init:
4076 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
4077 MMI->setCallsUnwindInit(true);
4082 case Intrinsic::eh_dwarf_cfa: {
4083 MVT VT = getValue(I.getOperand(1)).getValueType();
4085 if (VT.bitsGT(TLI.getPointerTy()))
4086 CfaArg = DAG.getNode(ISD::TRUNCATE, dl,
4087 TLI.getPointerTy(), getValue(I.getOperand(1)));
4089 CfaArg = DAG.getNode(ISD::SIGN_EXTEND, dl,
4090 TLI.getPointerTy(), getValue(I.getOperand(1)));
4092 SDValue Offset = DAG.getNode(ISD::ADD, dl,
4094 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
4095 TLI.getPointerTy()),
4097 setValue(&I, DAG.getNode(ISD::ADD, dl,
4099 DAG.getNode(ISD::FRAMEADDR, dl,
4102 TLI.getPointerTy())),
4107 case Intrinsic::convertff:
4108 case Intrinsic::convertfsi:
4109 case Intrinsic::convertfui:
4110 case Intrinsic::convertsif:
4111 case Intrinsic::convertuif:
4112 case Intrinsic::convertss:
4113 case Intrinsic::convertsu:
4114 case Intrinsic::convertus:
4115 case Intrinsic::convertuu: {
4116 ISD::CvtCode Code = ISD::CVT_INVALID;
4117 switch (Intrinsic) {
4118 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4119 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4120 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4121 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4122 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4123 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4124 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4125 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4126 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4128 MVT DestVT = TLI.getValueType(I.getType());
4129 Value* Op1 = I.getOperand(1);
4130 setValue(&I, DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
4131 DAG.getValueType(DestVT),
4132 DAG.getValueType(getValue(Op1).getValueType()),
4133 getValue(I.getOperand(2)),
4134 getValue(I.getOperand(3)),
4139 case Intrinsic::sqrt:
4140 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
4141 getValue(I.getOperand(1)).getValueType(),
4142 getValue(I.getOperand(1))));
4144 case Intrinsic::powi:
4145 setValue(&I, DAG.getNode(ISD::FPOWI, dl,
4146 getValue(I.getOperand(1)).getValueType(),
4147 getValue(I.getOperand(1)),
4148 getValue(I.getOperand(2))));
4150 case Intrinsic::sin:
4151 setValue(&I, DAG.getNode(ISD::FSIN, dl,
4152 getValue(I.getOperand(1)).getValueType(),
4153 getValue(I.getOperand(1))));
4155 case Intrinsic::cos:
4156 setValue(&I, DAG.getNode(ISD::FCOS, dl,
4157 getValue(I.getOperand(1)).getValueType(),
4158 getValue(I.getOperand(1))));
4160 case Intrinsic::log:
4163 case Intrinsic::log2:
4166 case Intrinsic::log10:
4169 case Intrinsic::exp:
4172 case Intrinsic::exp2:
4175 case Intrinsic::pow:
4178 case Intrinsic::pcmarker: {
4179 SDValue Tmp = getValue(I.getOperand(1));
4180 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
4183 case Intrinsic::readcyclecounter: {
4184 SDValue Op = getRoot();
4185 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4186 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
4189 DAG.setRoot(Tmp.getValue(1));
4192 case Intrinsic::part_select: {
4193 // Currently not implemented: just abort
4194 assert(0 && "part_select intrinsic not implemented");
4197 case Intrinsic::part_set: {
4198 // Currently not implemented: just abort
4199 assert(0 && "part_set intrinsic not implemented");
4202 case Intrinsic::bswap:
4203 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
4204 getValue(I.getOperand(1)).getValueType(),
4205 getValue(I.getOperand(1))));
4207 case Intrinsic::cttz: {
4208 SDValue Arg = getValue(I.getOperand(1));
4209 MVT Ty = Arg.getValueType();
4210 SDValue result = DAG.getNode(ISD::CTTZ, dl, Ty, Arg);
4211 setValue(&I, result);
4214 case Intrinsic::ctlz: {
4215 SDValue Arg = getValue(I.getOperand(1));
4216 MVT Ty = Arg.getValueType();
4217 SDValue result = DAG.getNode(ISD::CTLZ, dl, Ty, Arg);
4218 setValue(&I, result);
4221 case Intrinsic::ctpop: {
4222 SDValue Arg = getValue(I.getOperand(1));
4223 MVT Ty = Arg.getValueType();
4224 SDValue result = DAG.getNode(ISD::CTPOP, dl, Ty, Arg);
4225 setValue(&I, result);
4228 case Intrinsic::stacksave: {
4229 SDValue Op = getRoot();
4230 SDValue Tmp = DAG.getNode(ISD::STACKSAVE, dl,
4231 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
4233 DAG.setRoot(Tmp.getValue(1));
4236 case Intrinsic::stackrestore: {
4237 SDValue Tmp = getValue(I.getOperand(1));
4238 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Tmp));
4241 case Intrinsic::stackprotector: {
4242 // Emit code into the DAG to store the stack guard onto the stack.
4243 MachineFunction &MF = DAG.getMachineFunction();
4244 MachineFrameInfo *MFI = MF.getFrameInfo();
4245 MVT PtrTy = TLI.getPointerTy();
4247 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4248 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
4250 int FI = FuncInfo.StaticAllocaMap[Slot];
4251 MFI->setStackProtectorIndex(FI);
4253 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4255 // Store the stack protector onto the stack.
4256 SDValue Result = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4257 PseudoSourceValue::getFixedStack(FI),
4259 setValue(&I, Result);
4260 DAG.setRoot(Result);
4263 case Intrinsic::var_annotation:
4264 // Discard annotate attributes
4267 case Intrinsic::init_trampoline: {
4268 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4272 Ops[1] = getValue(I.getOperand(1));
4273 Ops[2] = getValue(I.getOperand(2));
4274 Ops[3] = getValue(I.getOperand(3));
4275 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4276 Ops[5] = DAG.getSrcValue(F);
4278 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE, dl,
4279 DAG.getNodeValueTypes(TLI.getPointerTy(),
4284 DAG.setRoot(Tmp.getValue(1));
4288 case Intrinsic::gcroot:
4290 Value *Alloca = I.getOperand(1);
4291 Constant *TypeMap = cast<Constant>(I.getOperand(2));
4293 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4294 GFI->addStackRoot(FI->getIndex(), TypeMap);
4298 case Intrinsic::gcread:
4299 case Intrinsic::gcwrite:
4300 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
4303 case Intrinsic::flt_rounds: {
4304 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
4308 case Intrinsic::trap: {
4309 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
4313 case Intrinsic::uadd_with_overflow:
4314 return implVisitAluOverflow(I, ISD::UADDO);
4315 case Intrinsic::sadd_with_overflow:
4316 return implVisitAluOverflow(I, ISD::SADDO);
4317 case Intrinsic::usub_with_overflow:
4318 return implVisitAluOverflow(I, ISD::USUBO);
4319 case Intrinsic::ssub_with_overflow:
4320 return implVisitAluOverflow(I, ISD::SSUBO);
4321 case Intrinsic::umul_with_overflow:
4322 return implVisitAluOverflow(I, ISD::UMULO);
4323 case Intrinsic::smul_with_overflow:
4324 return implVisitAluOverflow(I, ISD::SMULO);
4326 case Intrinsic::prefetch: {
4329 Ops[1] = getValue(I.getOperand(1));
4330 Ops[2] = getValue(I.getOperand(2));
4331 Ops[3] = getValue(I.getOperand(3));
4332 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
4336 case Intrinsic::memory_barrier: {
4339 for (int x = 1; x < 6; ++x)
4340 Ops[x] = getValue(I.getOperand(x));
4342 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
4345 case Intrinsic::atomic_cmp_swap: {
4346 SDValue Root = getRoot();
4348 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
4349 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4351 getValue(I.getOperand(1)),
4352 getValue(I.getOperand(2)),
4353 getValue(I.getOperand(3)),
4356 DAG.setRoot(L.getValue(1));
4359 case Intrinsic::atomic_load_add:
4360 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4361 case Intrinsic::atomic_load_sub:
4362 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4363 case Intrinsic::atomic_load_or:
4364 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4365 case Intrinsic::atomic_load_xor:
4366 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4367 case Intrinsic::atomic_load_and:
4368 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4369 case Intrinsic::atomic_load_nand:
4370 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4371 case Intrinsic::atomic_load_max:
4372 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4373 case Intrinsic::atomic_load_min:
4374 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4375 case Intrinsic::atomic_load_umin:
4376 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4377 case Intrinsic::atomic_load_umax:
4378 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4379 case Intrinsic::atomic_swap:
4380 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4385 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4387 MachineBasicBlock *LandingPad) {
4388 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4389 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4390 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4391 unsigned BeginLabel = 0, EndLabel = 0;
4393 TargetLowering::ArgListTy Args;
4394 TargetLowering::ArgListEntry Entry;
4395 Args.reserve(CS.arg_size());
4396 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4398 SDValue ArgNode = getValue(*i);
4399 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4401 unsigned attrInd = i - CS.arg_begin() + 1;
4402 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4403 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4404 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4405 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4406 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4407 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4408 Entry.Alignment = CS.getParamAlignment(attrInd);
4409 Args.push_back(Entry);
4412 if (LandingPad && MMI) {
4413 // Insert a label before the invoke call to mark the try range. This can be
4414 // used to detect deletion of the invoke via the MachineModuleInfo.
4415 BeginLabel = MMI->NextLabelID();
4416 // Both PendingLoads and PendingExports must be flushed here;
4417 // this call might not return.
4419 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4420 getControlRoot(), BeginLabel));
4423 std::pair<SDValue,SDValue> Result =
4424 TLI.LowerCallTo(getRoot(), CS.getType(),
4425 CS.paramHasAttr(0, Attribute::SExt),
4426 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4427 CS.paramHasAttr(0, Attribute::InReg),
4428 CS.getCallingConv(),
4429 IsTailCall && PerformTailCallOpt,
4430 Callee, Args, DAG, getCurDebugLoc());
4431 if (CS.getType() != Type::VoidTy)
4432 setValue(CS.getInstruction(), Result.first);
4433 DAG.setRoot(Result.second);
4435 if (LandingPad && MMI) {
4436 // Insert a label at the end of the invoke call to mark the try range. This
4437 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4438 EndLabel = MMI->NextLabelID();
4439 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4440 getRoot(), EndLabel));
4442 // Inform MachineModuleInfo of range.
4443 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4448 void SelectionDAGLowering::visitCall(CallInst &I) {
4449 const char *RenameFn = 0;
4450 if (Function *F = I.getCalledFunction()) {
4451 if (F->isDeclaration()) {
4452 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4454 if (unsigned IID = II->getIntrinsicID(F)) {
4455 RenameFn = visitIntrinsicCall(I, IID);
4460 if (unsigned IID = F->getIntrinsicID()) {
4461 RenameFn = visitIntrinsicCall(I, IID);
4467 // Check for well-known libc/libm calls. If the function is internal, it
4468 // can't be a library call.
4469 unsigned NameLen = F->getNameLen();
4470 if (!F->hasLocalLinkage() && NameLen) {
4471 const char *NameStr = F->getNameStart();
4472 if (NameStr[0] == 'c' &&
4473 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4474 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4475 if (I.getNumOperands() == 3 && // Basic sanity checks.
4476 I.getOperand(1)->getType()->isFloatingPoint() &&
4477 I.getType() == I.getOperand(1)->getType() &&
4478 I.getType() == I.getOperand(2)->getType()) {
4479 SDValue LHS = getValue(I.getOperand(1));
4480 SDValue RHS = getValue(I.getOperand(2));
4481 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
4482 LHS.getValueType(), LHS, RHS));
4485 } else if (NameStr[0] == 'f' &&
4486 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4487 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4488 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4489 if (I.getNumOperands() == 2 && // Basic sanity checks.
4490 I.getOperand(1)->getType()->isFloatingPoint() &&
4491 I.getType() == I.getOperand(1)->getType()) {
4492 SDValue Tmp = getValue(I.getOperand(1));
4493 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
4494 Tmp.getValueType(), Tmp));
4497 } else if (NameStr[0] == 's' &&
4498 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4499 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4500 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4501 if (I.getNumOperands() == 2 && // Basic sanity checks.
4502 I.getOperand(1)->getType()->isFloatingPoint() &&
4503 I.getType() == I.getOperand(1)->getType()) {
4504 SDValue Tmp = getValue(I.getOperand(1));
4505 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
4506 Tmp.getValueType(), Tmp));
4509 } else if (NameStr[0] == 'c' &&
4510 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4511 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4512 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4513 if (I.getNumOperands() == 2 && // Basic sanity checks.
4514 I.getOperand(1)->getType()->isFloatingPoint() &&
4515 I.getType() == I.getOperand(1)->getType()) {
4516 SDValue Tmp = getValue(I.getOperand(1));
4517 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
4518 Tmp.getValueType(), Tmp));
4523 } else if (isa<InlineAsm>(I.getOperand(0))) {
4530 Callee = getValue(I.getOperand(0));
4532 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
4534 LowerCallTo(&I, Callee, I.isTailCall());
4538 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4539 /// this value and returns the result as a ValueVT value. This uses
4540 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4541 /// If the Flag pointer is NULL, no flag is used.
4542 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
4544 SDValue *Flag) const {
4545 // Assemble the legal parts into the final values.
4546 SmallVector<SDValue, 4> Values(ValueVTs.size());
4547 SmallVector<SDValue, 8> Parts;
4548 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4549 // Copy the legal parts from the registers.
4550 MVT ValueVT = ValueVTs[Value];
4551 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4552 MVT RegisterVT = RegVTs[Value];
4554 Parts.resize(NumRegs);
4555 for (unsigned i = 0; i != NumRegs; ++i) {
4558 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
4560 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
4561 *Flag = P.getValue(2);
4563 Chain = P.getValue(1);
4565 // If the source register was virtual and if we know something about it,
4566 // add an assert node.
4567 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4568 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4569 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4570 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4571 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4572 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4574 unsigned RegSize = RegisterVT.getSizeInBits();
4575 unsigned NumSignBits = LOI.NumSignBits;
4576 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4578 // FIXME: We capture more information than the dag can represent. For
4579 // now, just use the tightest assertzext/assertsext possible.
4581 MVT FromVT(MVT::Other);
4582 if (NumSignBits == RegSize)
4583 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4584 else if (NumZeroBits >= RegSize-1)
4585 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4586 else if (NumSignBits > RegSize-8)
4587 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4588 else if (NumZeroBits >= RegSize-8)
4589 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4590 else if (NumSignBits > RegSize-16)
4591 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
4592 else if (NumZeroBits >= RegSize-16)
4593 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
4594 else if (NumSignBits > RegSize-32)
4595 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
4596 else if (NumZeroBits >= RegSize-32)
4597 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
4599 if (FromVT != MVT::Other) {
4600 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
4601 RegisterVT, P, DAG.getValueType(FromVT));
4610 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
4611 NumRegs, RegisterVT, ValueVT);
4616 return DAG.getNode(ISD::MERGE_VALUES, dl,
4617 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4618 &Values[0], ValueVTs.size());
4621 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4622 /// specified value into the registers specified by this object. This uses
4623 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4624 /// If the Flag pointer is NULL, no flag is used.
4625 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
4626 SDValue &Chain, SDValue *Flag) const {
4627 // Get the list of the values's legal parts.
4628 unsigned NumRegs = Regs.size();
4629 SmallVector<SDValue, 8> Parts(NumRegs);
4630 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4631 MVT ValueVT = ValueVTs[Value];
4632 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4633 MVT RegisterVT = RegVTs[Value];
4635 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
4636 &Parts[Part], NumParts, RegisterVT);
4640 // Copy the parts into the registers.
4641 SmallVector<SDValue, 8> Chains(NumRegs);
4642 for (unsigned i = 0; i != NumRegs; ++i) {
4645 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
4647 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
4648 *Flag = Part.getValue(1);
4650 Chains[i] = Part.getValue(0);
4653 if (NumRegs == 1 || Flag)
4654 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4655 // flagged to it. That is the CopyToReg nodes and the user are considered
4656 // a single scheduling unit. If we create a TokenFactor and return it as
4657 // chain, then the TokenFactor is both a predecessor (operand) of the
4658 // user as well as a successor (the TF operands are flagged to the user).
4659 // c1, f1 = CopyToReg
4660 // c2, f2 = CopyToReg
4661 // c3 = TokenFactor c1, c2
4664 Chain = Chains[NumRegs-1];
4666 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
4669 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
4670 /// operand list. This adds the code marker and includes the number of
4671 /// values added into it.
4672 void RegsForValue::AddInlineAsmOperands(unsigned Code,
4673 bool HasMatching,unsigned MatchingIdx,
4675 std::vector<SDValue> &Ops) const {
4676 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4677 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
4678 unsigned Flag = Code | (Regs.size() << 3);
4680 Flag |= 0x80000000 | (MatchingIdx << 16);
4681 Ops.push_back(DAG.getTargetConstant(Flag, IntPtrTy));
4682 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4683 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4684 MVT RegisterVT = RegVTs[Value];
4685 for (unsigned i = 0; i != NumRegs; ++i) {
4686 assert(Reg < Regs.size() && "Mismatch in # registers expected");
4687 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
4692 /// isAllocatableRegister - If the specified register is safe to allocate,
4693 /// i.e. it isn't a stack pointer or some other special register, return the
4694 /// register class for the register. Otherwise, return null.
4695 static const TargetRegisterClass *
4696 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4697 const TargetLowering &TLI,
4698 const TargetRegisterInfo *TRI) {
4699 MVT FoundVT = MVT::Other;
4700 const TargetRegisterClass *FoundRC = 0;
4701 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4702 E = TRI->regclass_end(); RCI != E; ++RCI) {
4703 MVT ThisVT = MVT::Other;
4705 const TargetRegisterClass *RC = *RCI;
4706 // If none of the the value types for this register class are valid, we
4707 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4708 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4710 if (TLI.isTypeLegal(*I)) {
4711 // If we have already found this register in a different register class,
4712 // choose the one with the largest VT specified. For example, on
4713 // PowerPC, we favor f64 register classes over f32.
4714 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4721 if (ThisVT == MVT::Other) continue;
4723 // NOTE: This isn't ideal. In particular, this might allocate the
4724 // frame pointer in functions that need it (due to them not being taken
4725 // out of allocation, because a variable sized allocation hasn't been seen
4726 // yet). This is a slight code pessimization, but should still work.
4727 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4728 E = RC->allocation_order_end(MF); I != E; ++I)
4730 // We found a matching register class. Keep looking at others in case
4731 // we find one with larger registers that this physreg is also in.
4742 /// AsmOperandInfo - This contains information for each constraint that we are
4744 class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4745 public TargetLowering::AsmOperandInfo {
4747 /// CallOperand - If this is the result output operand or a clobber
4748 /// this is null, otherwise it is the incoming operand to the CallInst.
4749 /// This gets modified as the asm is processed.
4750 SDValue CallOperand;
4752 /// AssignedRegs - If this is a register or register class operand, this
4753 /// contains the set of register corresponding to the operand.
4754 RegsForValue AssignedRegs;
4756 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4757 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4760 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4761 /// busy in OutputRegs/InputRegs.
4762 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4763 std::set<unsigned> &OutputRegs,
4764 std::set<unsigned> &InputRegs,
4765 const TargetRegisterInfo &TRI) const {
4767 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4768 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4771 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4772 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4776 /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4777 /// corresponds to. If there is no Value* for this operand, it returns
4779 MVT getCallOperandValMVT(const TargetLowering &TLI,
4780 const TargetData *TD) const {
4781 if (CallOperandVal == 0) return MVT::Other;
4783 if (isa<BasicBlock>(CallOperandVal))
4784 return TLI.getPointerTy();
4786 const llvm::Type *OpTy = CallOperandVal->getType();
4788 // If this is an indirect operand, the operand is a pointer to the
4791 OpTy = cast<PointerType>(OpTy)->getElementType();
4793 // If OpTy is not a single value, it may be a struct/union that we
4794 // can tile with integers.
4795 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4796 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4805 OpTy = IntegerType::get(BitSize);
4810 return TLI.getValueType(OpTy, true);
4814 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4816 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4817 const TargetRegisterInfo &TRI) {
4818 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4820 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4821 for (; *Aliases; ++Aliases)
4822 Regs.insert(*Aliases);
4825 } // end llvm namespace.
4828 /// GetRegistersForValue - Assign registers (virtual or physical) for the
4829 /// specified operand. We prefer to assign virtual registers, to allow the
4830 /// register allocator handle the assignment process. However, if the asm uses
4831 /// features that we can't model on machineinstrs, we have SDISel do the
4832 /// allocation. This produces generally horrible, but correct, code.
4834 /// OpInfo describes the operand.
4835 /// Input and OutputRegs are the set of already allocated physical registers.
4837 void SelectionDAGLowering::
4838 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
4839 std::set<unsigned> &OutputRegs,
4840 std::set<unsigned> &InputRegs) {
4841 // Compute whether this value requires an input register, an output register,
4843 bool isOutReg = false;
4844 bool isInReg = false;
4845 switch (OpInfo.Type) {
4846 case InlineAsm::isOutput:
4849 // If there is an input constraint that matches this, we need to reserve
4850 // the input register so no other inputs allocate to it.
4851 isInReg = OpInfo.hasMatchingInput();
4853 case InlineAsm::isInput:
4857 case InlineAsm::isClobber:
4864 MachineFunction &MF = DAG.getMachineFunction();
4865 SmallVector<unsigned, 4> Regs;
4867 // If this is a constraint for a single physreg, or a constraint for a
4868 // register class, find it.
4869 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4870 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4871 OpInfo.ConstraintVT);
4873 unsigned NumRegs = 1;
4874 if (OpInfo.ConstraintVT != MVT::Other) {
4875 // If this is a FP input in an integer register (or visa versa) insert a bit
4876 // cast of the input value. More generally, handle any case where the input
4877 // value disagrees with the register class we plan to stick this in.
4878 if (OpInfo.Type == InlineAsm::isInput &&
4879 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4880 // Try to convert to the first MVT that the reg class contains. If the
4881 // types are identical size, use a bitcast to convert (e.g. two differing
4883 MVT RegVT = *PhysReg.second->vt_begin();
4884 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
4885 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
4886 RegVT, OpInfo.CallOperand);
4887 OpInfo.ConstraintVT = RegVT;
4888 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4889 // If the input is a FP value and we want it in FP registers, do a
4890 // bitcast to the corresponding integer type. This turns an f64 value
4891 // into i64, which can be passed with two i32 values on a 32-bit
4893 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
4894 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
4895 RegVT, OpInfo.CallOperand);
4896 OpInfo.ConstraintVT = RegVT;
4900 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
4904 MVT ValueVT = OpInfo.ConstraintVT;
4906 // If this is a constraint for a specific physical register, like {r17},
4908 if (unsigned AssignedReg = PhysReg.first) {
4909 const TargetRegisterClass *RC = PhysReg.second;
4910 if (OpInfo.ConstraintVT == MVT::Other)
4911 ValueVT = *RC->vt_begin();
4913 // Get the actual register value type. This is important, because the user
4914 // may have asked for (e.g.) the AX register in i32 type. We need to
4915 // remember that AX is actually i16 to get the right extension.
4916 RegVT = *RC->vt_begin();
4918 // This is a explicit reference to a physical register.
4919 Regs.push_back(AssignedReg);
4921 // If this is an expanded reference, add the rest of the regs to Regs.
4923 TargetRegisterClass::iterator I = RC->begin();
4924 for (; *I != AssignedReg; ++I)
4925 assert(I != RC->end() && "Didn't find reg!");
4927 // Already added the first reg.
4929 for (; NumRegs; --NumRegs, ++I) {
4930 assert(I != RC->end() && "Ran out of registers to allocate!");
4934 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4935 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4936 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4940 // Otherwise, if this was a reference to an LLVM register class, create vregs
4941 // for this reference.
4942 if (const TargetRegisterClass *RC = PhysReg.second) {
4943 RegVT = *RC->vt_begin();
4944 if (OpInfo.ConstraintVT == MVT::Other)
4947 // Create the appropriate number of virtual registers.
4948 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4949 for (; NumRegs; --NumRegs)
4950 Regs.push_back(RegInfo.createVirtualRegister(RC));
4952 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4956 // This is a reference to a register class that doesn't directly correspond
4957 // to an LLVM register class. Allocate NumRegs consecutive, available,
4958 // registers from the class.
4959 std::vector<unsigned> RegClassRegs
4960 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4961 OpInfo.ConstraintVT);
4963 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4964 unsigned NumAllocated = 0;
4965 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4966 unsigned Reg = RegClassRegs[i];
4967 // See if this register is available.
4968 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4969 (isInReg && InputRegs.count(Reg))) { // Already used.
4970 // Make sure we find consecutive registers.
4975 // Check to see if this register is allocatable (i.e. don't give out the
4977 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4978 if (!RC) { // Couldn't allocate this register.
4979 // Reset NumAllocated to make sure we return consecutive registers.
4984 // Okay, this register is good, we can use it.
4987 // If we allocated enough consecutive registers, succeed.
4988 if (NumAllocated == NumRegs) {
4989 unsigned RegStart = (i-NumAllocated)+1;
4990 unsigned RegEnd = i+1;
4991 // Mark all of the allocated registers used.
4992 for (unsigned i = RegStart; i != RegEnd; ++i)
4993 Regs.push_back(RegClassRegs[i]);
4995 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
4996 OpInfo.ConstraintVT);
4997 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5002 // Otherwise, we couldn't allocate enough registers for this.
5005 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
5006 /// processed uses a memory 'm' constraint.
5008 hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
5009 const TargetLowering &TLI) {
5010 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
5011 InlineAsm::ConstraintInfo &CI = CInfos[i];
5012 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
5013 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
5014 if (CType == TargetLowering::C_Memory)
5022 /// visitInlineAsm - Handle a call to an InlineAsm object.
5024 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
5025 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5027 /// ConstraintOperands - Information about all of the constraints.
5028 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
5030 SDValue Chain = getRoot();
5033 std::set<unsigned> OutputRegs, InputRegs;
5035 // Do a prepass over the constraints, canonicalizing them, and building up the
5036 // ConstraintOperands list.
5037 std::vector<InlineAsm::ConstraintInfo>
5038 ConstraintInfos = IA->ParseConstraints();
5040 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
5042 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5043 unsigned ResNo = 0; // ResNo - The result number of the next output.
5044 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5045 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5046 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5048 MVT OpVT = MVT::Other;
5050 // Compute the value type for each operand.
5051 switch (OpInfo.Type) {
5052 case InlineAsm::isOutput:
5053 // Indirect outputs just consume an argument.
5054 if (OpInfo.isIndirect) {
5055 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5059 // The return value of the call is this value. As such, there is no
5060 // corresponding argument.
5061 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5062 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5063 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5065 assert(ResNo == 0 && "Asm only has one result!");
5066 OpVT = TLI.getValueType(CS.getType());
5070 case InlineAsm::isInput:
5071 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5073 case InlineAsm::isClobber:
5078 // If this is an input or an indirect output, process the call argument.
5079 // BasicBlocks are labels, currently appearing only in asm's.
5080 if (OpInfo.CallOperandVal) {
5081 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5082 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5084 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5087 OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
5090 OpInfo.ConstraintVT = OpVT;
5093 // Second pass over the constraints: compute which constraint option to use
5094 // and assign registers to constraints that want a specific physreg.
5095 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5096 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5098 // If this is an output operand with a matching input operand, look up the
5099 // matching input. If their types mismatch, e.g. one is an integer, the
5100 // other is floating point, or their sizes are different, flag it as an
5102 if (OpInfo.hasMatchingInput()) {
5103 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5104 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5105 if ((OpInfo.ConstraintVT.isInteger() !=
5106 Input.ConstraintVT.isInteger()) ||
5107 (OpInfo.ConstraintVT.getSizeInBits() !=
5108 Input.ConstraintVT.getSizeInBits())) {
5109 cerr << "Unsupported asm: input constraint with a matching output "
5110 << "constraint of incompatible type!\n";
5113 Input.ConstraintVT = OpInfo.ConstraintVT;
5117 // Compute the constraint code and ConstraintType to use.
5118 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
5120 // If this is a memory input, and if the operand is not indirect, do what we
5121 // need to to provide an address for the memory input.
5122 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5123 !OpInfo.isIndirect) {
5124 assert(OpInfo.Type == InlineAsm::isInput &&
5125 "Can only indirectify direct input operands!");
5127 // Memory operands really want the address of the value. If we don't have
5128 // an indirect input, put it in the constpool if we can, otherwise spill
5129 // it to a stack slot.
5131 // If the operand is a float, integer, or vector constant, spill to a
5132 // constant pool entry to get its address.
5133 Value *OpVal = OpInfo.CallOperandVal;
5134 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5135 isa<ConstantVector>(OpVal)) {
5136 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5137 TLI.getPointerTy());
5139 // Otherwise, create a stack slot and emit a store to it before the
5141 const Type *Ty = OpVal->getType();
5142 uint64_t TySize = TLI.getTargetData()->getTypePaddedSize(Ty);
5143 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5144 MachineFunction &MF = DAG.getMachineFunction();
5145 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
5146 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5147 Chain = DAG.getStore(Chain, getCurDebugLoc(),
5148 OpInfo.CallOperand, StackSlot, NULL, 0);
5149 OpInfo.CallOperand = StackSlot;
5152 // There is no longer a Value* corresponding to this operand.
5153 OpInfo.CallOperandVal = 0;
5154 // It is now an indirect operand.
5155 OpInfo.isIndirect = true;
5158 // If this constraint is for a specific register, allocate it before
5160 if (OpInfo.ConstraintType == TargetLowering::C_Register)
5161 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5163 ConstraintInfos.clear();
5166 // Second pass - Loop over all of the operands, assigning virtual or physregs
5167 // to register class operands.
5168 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5169 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5171 // C_Register operands have already been allocated, Other/Memory don't need
5173 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
5174 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5177 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5178 std::vector<SDValue> AsmNodeOperands;
5179 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5180 AsmNodeOperands.push_back(
5181 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
5184 // Loop over all of the inputs, copying the operand values into the
5185 // appropriate registers and processing the output regs.
5186 RegsForValue RetValRegs;
5188 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5189 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
5191 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5192 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5194 switch (OpInfo.Type) {
5195 case InlineAsm::isOutput: {
5196 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5197 OpInfo.ConstraintType != TargetLowering::C_Register) {
5198 // Memory output, or 'other' output (e.g. 'X' constraint).
5199 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5201 // Add information to the INLINEASM node to know about this output.
5202 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5203 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5204 TLI.getPointerTy()));
5205 AsmNodeOperands.push_back(OpInfo.CallOperand);
5209 // Otherwise, this is a register or register class output.
5211 // Copy the output from the appropriate register. Find a register that
5213 if (OpInfo.AssignedRegs.Regs.empty()) {
5214 cerr << "Couldn't allocate output reg for constraint '"
5215 << OpInfo.ConstraintCode << "'!\n";
5219 // If this is an indirect operand, store through the pointer after the
5221 if (OpInfo.isIndirect) {
5222 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5223 OpInfo.CallOperandVal));
5225 // This is the result value of the call.
5226 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5227 // Concatenate this output onto the outputs list.
5228 RetValRegs.append(OpInfo.AssignedRegs);
5231 // Add information to the INLINEASM node to know that this register is
5233 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5234 6 /* EARLYCLOBBER REGDEF */ :
5238 DAG, AsmNodeOperands);
5241 case InlineAsm::isInput: {
5242 SDValue InOperandVal = OpInfo.CallOperand;
5244 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
5245 // If this is required to match an output register we have already set,
5246 // just use its register.
5247 unsigned OperandNo = OpInfo.getMatchedOperand();
5249 // Scan until we find the definition we already emitted of this operand.
5250 // When we find it, create a RegsForValue operand.
5251 unsigned CurOp = 2; // The first operand.
5252 for (; OperandNo; --OperandNo) {
5253 // Advance to the next operand.
5255 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5256 assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5257 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5258 (OpFlag & 7) == 4 /*MEM*/) &&
5259 "Skipped past definitions?");
5260 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
5264 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5265 if ((OpFlag & 7) == 2 /*REGDEF*/
5266 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5267 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
5268 RegsForValue MatchedRegs;
5269 MatchedRegs.TLI = &TLI;
5270 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5271 MVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5272 MatchedRegs.RegVTs.push_back(RegVT);
5273 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
5274 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
5277 push_back(RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
5279 // Use the produced MatchedRegs object to
5280 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5282 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5283 true, OpInfo.getMatchedOperand(),
5284 DAG, AsmNodeOperands);
5287 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5288 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5289 "Unexpected number of operands");
5290 // Add information to the INLINEASM node to know about this input.
5291 // See InlineAsm.h isUseOperandTiedToDef.
5292 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
5293 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
5294 TLI.getPointerTy()));
5295 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5300 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5301 assert(!OpInfo.isIndirect &&
5302 "Don't know how to handle indirect other inputs yet!");
5304 std::vector<SDValue> Ops;
5305 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
5306 hasMemory, Ops, DAG);
5308 cerr << "Invalid operand for inline asm constraint '"
5309 << OpInfo.ConstraintCode << "'!\n";
5313 // Add information to the INLINEASM node to know about this input.
5314 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
5315 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5316 TLI.getPointerTy()));
5317 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5319 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5320 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5321 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5322 "Memory operands expect pointer values");
5324 // Add information to the INLINEASM node to know about this input.
5325 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5326 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5327 TLI.getPointerTy()));
5328 AsmNodeOperands.push_back(InOperandVal);
5332 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5333 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5334 "Unknown constraint type!");
5335 assert(!OpInfo.isIndirect &&
5336 "Don't know how to handle indirect register inputs yet!");
5338 // Copy the input into the appropriate registers.
5339 if (OpInfo.AssignedRegs.Regs.empty()) {
5340 cerr << "Couldn't allocate output reg for constraint '"
5341 << OpInfo.ConstraintCode << "'!\n";
5345 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5348 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
5349 DAG, AsmNodeOperands);
5352 case InlineAsm::isClobber: {
5353 // Add the clobbered value to the operand list, so that the register
5354 // allocator is aware that the physreg got clobbered.
5355 if (!OpInfo.AssignedRegs.Regs.empty())
5356 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
5357 false, 0, DAG,AsmNodeOperands);
5363 // Finish up input operands.
5364 AsmNodeOperands[0] = Chain;
5365 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5367 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
5368 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
5369 &AsmNodeOperands[0], AsmNodeOperands.size());
5370 Flag = Chain.getValue(1);
5372 // If this asm returns a register value, copy the result from that register
5373 // and set it as the value of the call.
5374 if (!RetValRegs.Regs.empty()) {
5375 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5378 // FIXME: Why don't we do this for inline asms with MRVs?
5379 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5380 MVT ResultType = TLI.getValueType(CS.getType());
5382 // If any of the results of the inline asm is a vector, it may have the
5383 // wrong width/num elts. This can happen for register classes that can
5384 // contain multiple different value types. The preg or vreg allocated may
5385 // not have the same VT as was expected. Convert it to the right type
5386 // with bit_convert.
5387 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5388 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5391 } else if (ResultType != Val.getValueType() &&
5392 ResultType.isInteger() && Val.getValueType().isInteger()) {
5393 // If a result value was tied to an input value, the computed result may
5394 // have a wider width than the expected result. Extract the relevant
5396 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
5399 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
5402 setValue(CS.getInstruction(), Val);
5405 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5407 // Process indirect outputs, first output all of the flagged copies out of
5409 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5410 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5411 Value *Ptr = IndirectStoresToEmit[i].second;
5412 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5414 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5417 // Emit the non-flagged stores from the physregs.
5418 SmallVector<SDValue, 8> OutChains;
5419 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5420 OutChains.push_back(DAG.getStore(Chain, getCurDebugLoc(),
5421 StoresToEmit[i].first,
5422 getValue(StoresToEmit[i].second),
5423 StoresToEmit[i].second, 0));
5424 if (!OutChains.empty())
5425 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
5426 &OutChains[0], OutChains.size());
5431 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5432 SDValue Src = getValue(I.getOperand(0));
5434 // Scale up by the type size in the original i32 type width. Various
5435 // mid-level optimizers may make assumptions about demanded bits etc from the
5436 // i32-ness of the optimizer: we do not want to promote to i64 and then
5437 // multiply on 64-bit targets.
5438 // FIXME: Malloc inst should go away: PR715.
5439 uint64_t ElementSize = TD->getTypePaddedSize(I.getType()->getElementType());
5440 if (ElementSize != 1)
5441 Src = DAG.getNode(ISD::MUL, getCurDebugLoc(), Src.getValueType(),
5442 Src, DAG.getConstant(ElementSize, Src.getValueType()));
5444 MVT IntPtr = TLI.getPointerTy();
5446 if (IntPtr.bitsLT(Src.getValueType()))
5447 Src = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), IntPtr, Src);
5448 else if (IntPtr.bitsGT(Src.getValueType()))
5449 Src = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), IntPtr, Src);
5451 TargetLowering::ArgListTy Args;
5452 TargetLowering::ArgListEntry Entry;
5454 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5455 Args.push_back(Entry);
5457 std::pair<SDValue,SDValue> Result =
5458 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
5459 CallingConv::C, PerformTailCallOpt,
5460 DAG.getExternalSymbol("malloc", IntPtr),
5461 Args, DAG, getCurDebugLoc());
5462 setValue(&I, Result.first); // Pointers always fit in registers
5463 DAG.setRoot(Result.second);
5466 void SelectionDAGLowering::visitFree(FreeInst &I) {
5467 TargetLowering::ArgListTy Args;
5468 TargetLowering::ArgListEntry Entry;
5469 Entry.Node = getValue(I.getOperand(0));
5470 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5471 Args.push_back(Entry);
5472 MVT IntPtr = TLI.getPointerTy();
5473 std::pair<SDValue,SDValue> Result =
5474 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
5475 CallingConv::C, PerformTailCallOpt,
5476 DAG.getExternalSymbol("free", IntPtr), Args, DAG,
5478 DAG.setRoot(Result.second);
5481 void SelectionDAGLowering::visitVAStart(CallInst &I) {
5482 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
5483 MVT::Other, getRoot(),
5484 getValue(I.getOperand(1)),
5485 DAG.getSrcValue(I.getOperand(1))));
5488 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
5489 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5490 getRoot(), getValue(I.getOperand(0)),
5491 DAG.getSrcValue(I.getOperand(0)));
5493 DAG.setRoot(V.getValue(1));
5496 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
5497 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
5498 MVT::Other, getRoot(),
5499 getValue(I.getOperand(1)),
5500 DAG.getSrcValue(I.getOperand(1))));
5503 void SelectionDAGLowering::visitVACopy(CallInst &I) {
5504 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
5505 MVT::Other, getRoot(),
5506 getValue(I.getOperand(1)),
5507 getValue(I.getOperand(2)),
5508 DAG.getSrcValue(I.getOperand(1)),
5509 DAG.getSrcValue(I.getOperand(2))));
5512 /// TargetLowering::LowerArguments - This is the default LowerArguments
5513 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
5514 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
5515 /// integrated into SDISel.
5516 void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
5517 SmallVectorImpl<SDValue> &ArgValues,
5519 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5520 SmallVector<SDValue, 3+16> Ops;
5521 Ops.push_back(DAG.getRoot());
5522 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5523 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5525 // Add one result value for each formal argument.
5526 SmallVector<MVT, 16> RetVals;
5528 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5530 SmallVector<MVT, 4> ValueVTs;
5531 ComputeValueVTs(*this, I->getType(), ValueVTs);
5532 for (unsigned Value = 0, NumValues = ValueVTs.size();
5533 Value != NumValues; ++Value) {
5534 MVT VT = ValueVTs[Value];
5535 const Type *ArgTy = VT.getTypeForMVT();
5536 ISD::ArgFlagsTy Flags;
5537 unsigned OriginalAlignment =
5538 getTargetData()->getABITypeAlignment(ArgTy);
5540 if (F.paramHasAttr(j, Attribute::ZExt))
5542 if (F.paramHasAttr(j, Attribute::SExt))
5544 if (F.paramHasAttr(j, Attribute::InReg))
5546 if (F.paramHasAttr(j, Attribute::StructRet))
5548 if (F.paramHasAttr(j, Attribute::ByVal)) {
5550 const PointerType *Ty = cast<PointerType>(I->getType());
5551 const Type *ElementTy = Ty->getElementType();
5552 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5553 unsigned FrameSize = getTargetData()->getTypePaddedSize(ElementTy);
5554 // For ByVal, alignment should be passed from FE. BE will guess if
5555 // this info is not there but there are cases it cannot get right.
5556 if (F.getParamAlignment(j))
5557 FrameAlign = F.getParamAlignment(j);
5558 Flags.setByValAlign(FrameAlign);
5559 Flags.setByValSize(FrameSize);
5561 if (F.paramHasAttr(j, Attribute::Nest))
5563 Flags.setOrigAlign(OriginalAlignment);
5565 MVT RegisterVT = getRegisterType(VT);
5566 unsigned NumRegs = getNumRegisters(VT);
5567 for (unsigned i = 0; i != NumRegs; ++i) {
5568 RetVals.push_back(RegisterVT);
5569 ISD::ArgFlagsTy MyFlags = Flags;
5570 if (NumRegs > 1 && i == 0)
5572 // if it isn't first piece, alignment must be 1
5574 MyFlags.setOrigAlign(1);
5575 Ops.push_back(DAG.getArgFlags(MyFlags));
5580 RetVals.push_back(MVT::Other);
5583 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS, dl,
5584 DAG.getVTList(&RetVals[0], RetVals.size()),
5585 &Ops[0], Ops.size()).getNode();
5587 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5588 // allows exposing the loads that may be part of the argument access to the
5589 // first DAGCombiner pass.
5590 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
5592 // The number of results should match up, except that the lowered one may have
5593 // an extra flag result.
5594 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5595 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5596 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5597 && "Lowering produced unexpected number of results!");
5599 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5600 if (Result != TmpRes.getNode() && Result->use_empty()) {
5601 HandleSDNode Dummy(DAG.getRoot());
5602 DAG.RemoveDeadNode(Result);
5605 Result = TmpRes.getNode();
5607 unsigned NumArgRegs = Result->getNumValues() - 1;
5608 DAG.setRoot(SDValue(Result, NumArgRegs));
5610 // Set up the return result vector.
5613 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5615 SmallVector<MVT, 4> ValueVTs;
5616 ComputeValueVTs(*this, I->getType(), ValueVTs);
5617 for (unsigned Value = 0, NumValues = ValueVTs.size();
5618 Value != NumValues; ++Value) {
5619 MVT VT = ValueVTs[Value];
5620 MVT PartVT = getRegisterType(VT);
5622 unsigned NumParts = getNumRegisters(VT);
5623 SmallVector<SDValue, 4> Parts(NumParts);
5624 for (unsigned j = 0; j != NumParts; ++j)
5625 Parts[j] = SDValue(Result, i++);
5627 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5628 if (F.paramHasAttr(Idx, Attribute::SExt))
5629 AssertOp = ISD::AssertSext;
5630 else if (F.paramHasAttr(Idx, Attribute::ZExt))
5631 AssertOp = ISD::AssertZext;
5633 ArgValues.push_back(getCopyFromParts(DAG, dl, &Parts[0], NumParts,
5634 PartVT, VT, AssertOp));
5637 assert(i == NumArgRegs && "Argument register count mismatch!");
5641 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
5642 /// implementation, which just inserts an ISD::CALL node, which is later custom
5643 /// lowered by the target to something concrete. FIXME: When all targets are
5644 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5645 std::pair<SDValue, SDValue>
5646 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5647 bool RetSExt, bool RetZExt, bool isVarArg,
5649 unsigned CallingConv, bool isTailCall,
5651 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
5652 assert((!isTailCall || PerformTailCallOpt) &&
5653 "isTailCall set when tail-call optimizations are disabled!");
5655 SmallVector<SDValue, 32> Ops;
5656 Ops.push_back(Chain); // Op#0 - Chain
5657 Ops.push_back(Callee);
5659 // Handle all of the outgoing arguments.
5660 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5661 SmallVector<MVT, 4> ValueVTs;
5662 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5663 for (unsigned Value = 0, NumValues = ValueVTs.size();
5664 Value != NumValues; ++Value) {
5665 MVT VT = ValueVTs[Value];
5666 const Type *ArgTy = VT.getTypeForMVT();
5667 SDValue Op = SDValue(Args[i].Node.getNode(),
5668 Args[i].Node.getResNo() + Value);
5669 ISD::ArgFlagsTy Flags;
5670 unsigned OriginalAlignment =
5671 getTargetData()->getABITypeAlignment(ArgTy);
5677 if (Args[i].isInReg)
5681 if (Args[i].isByVal) {
5683 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5684 const Type *ElementTy = Ty->getElementType();
5685 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5686 unsigned FrameSize = getTargetData()->getTypePaddedSize(ElementTy);
5687 // For ByVal, alignment should come from FE. BE will guess if this
5688 // info is not there but there are cases it cannot get right.
5689 if (Args[i].Alignment)
5690 FrameAlign = Args[i].Alignment;
5691 Flags.setByValAlign(FrameAlign);
5692 Flags.setByValSize(FrameSize);
5696 Flags.setOrigAlign(OriginalAlignment);
5698 MVT PartVT = getRegisterType(VT);
5699 unsigned NumParts = getNumRegisters(VT);
5700 SmallVector<SDValue, 4> Parts(NumParts);
5701 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5704 ExtendKind = ISD::SIGN_EXTEND;
5705 else if (Args[i].isZExt)
5706 ExtendKind = ISD::ZERO_EXTEND;
5708 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5710 for (unsigned i = 0; i != NumParts; ++i) {
5711 // if it isn't first piece, alignment must be 1
5712 ISD::ArgFlagsTy MyFlags = Flags;
5713 if (NumParts > 1 && i == 0)
5716 MyFlags.setOrigAlign(1);
5718 Ops.push_back(Parts[i]);
5719 Ops.push_back(DAG.getArgFlags(MyFlags));
5724 // Figure out the result value types. We start by making a list of
5725 // the potentially illegal return value types.
5726 SmallVector<MVT, 4> LoweredRetTys;
5727 SmallVector<MVT, 4> RetTys;
5728 ComputeValueVTs(*this, RetTy, RetTys);
5730 // Then we translate that to a list of legal types.
5731 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5733 MVT RegisterVT = getRegisterType(VT);
5734 unsigned NumRegs = getNumRegisters(VT);
5735 for (unsigned i = 0; i != NumRegs; ++i)
5736 LoweredRetTys.push_back(RegisterVT);
5739 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
5741 // Create the CALL node.
5742 SDValue Res = DAG.getCall(CallingConv, dl,
5743 isVarArg, isTailCall, isInreg,
5744 DAG.getVTList(&LoweredRetTys[0],
5745 LoweredRetTys.size()),
5748 Chain = Res.getValue(LoweredRetTys.size() - 1);
5750 // Gather up the call result into a single value.
5751 if (RetTy != Type::VoidTy && !RetTys.empty()) {
5752 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5755 AssertOp = ISD::AssertSext;
5757 AssertOp = ISD::AssertZext;
5759 SmallVector<SDValue, 4> ReturnValues;
5761 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5763 MVT RegisterVT = getRegisterType(VT);
5764 unsigned NumRegs = getNumRegisters(VT);
5765 unsigned RegNoEnd = NumRegs + RegNo;
5766 SmallVector<SDValue, 4> Results;
5767 for (; RegNo != RegNoEnd; ++RegNo)
5768 Results.push_back(Res.getValue(RegNo));
5769 SDValue ReturnValue =
5770 getCopyFromParts(DAG, dl, &Results[0], NumRegs, RegisterVT, VT,
5772 ReturnValues.push_back(ReturnValue);
5774 Res = DAG.getNode(ISD::MERGE_VALUES, dl,
5775 DAG.getVTList(&RetTys[0], RetTys.size()),
5776 &ReturnValues[0], ReturnValues.size());
5779 return std::make_pair(Res, Chain);
5782 void TargetLowering::LowerOperationWrapper(SDNode *N,
5783 SmallVectorImpl<SDValue> &Results,
5784 SelectionDAG &DAG) {
5785 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
5787 Results.push_back(Res);
5790 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5791 assert(0 && "LowerOperation not implemented for this target!");
5797 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5798 SDValue Op = getValue(V);
5799 assert((Op.getOpcode() != ISD::CopyFromReg ||
5800 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5801 "Copy from a reg to the same reg!");
5802 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5804 RegsForValue RFV(TLI, Reg, V->getType());
5805 SDValue Chain = DAG.getEntryNode();
5806 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
5807 PendingExports.push_back(Chain);
5810 #include "llvm/CodeGen/SelectionDAGISel.h"
5812 void SelectionDAGISel::
5813 LowerArguments(BasicBlock *LLVMBB) {
5814 // If this is the entry block, emit arguments.
5815 Function &F = *LLVMBB->getParent();
5816 SDValue OldRoot = SDL->DAG.getRoot();
5817 SmallVector<SDValue, 16> Args;
5818 TLI.LowerArguments(F, SDL->DAG, Args, SDL->getCurDebugLoc());
5821 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5823 SmallVector<MVT, 4> ValueVTs;
5824 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5825 unsigned NumValues = ValueVTs.size();
5826 if (!AI->use_empty()) {
5827 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues,
5828 SDL->getCurDebugLoc()));
5829 // If this argument is live outside of the entry block, insert a copy from
5830 // whereever we got it to the vreg that other BB's will reference it as.
5831 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5832 if (VMI != FuncInfo->ValueMap.end()) {
5833 SDL->CopyValueToVirtualRegister(AI, VMI->second);
5839 // Finally, if the target has anything special to do, allow it to do so.
5840 // FIXME: this should insert code into the DAG!
5841 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5844 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5845 /// ensure constants are generated when needed. Remember the virtual registers
5846 /// that need to be added to the Machine PHI nodes as input. We cannot just
5847 /// directly add them, because expansion might result in multiple MBB's for one
5848 /// BB. As such, the start of the BB might correspond to a different MBB than
5852 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5853 TerminatorInst *TI = LLVMBB->getTerminator();
5855 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5857 // Check successor nodes' PHI nodes that expect a constant to be available
5859 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5860 BasicBlock *SuccBB = TI->getSuccessor(succ);
5861 if (!isa<PHINode>(SuccBB->begin())) continue;
5862 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5864 // If this terminator has multiple identical successors (common for
5865 // switches), only handle each succ once.
5866 if (!SuccsHandled.insert(SuccMBB)) continue;
5868 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5871 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5872 // nodes and Machine PHI nodes, but the incoming operands have not been
5874 for (BasicBlock::iterator I = SuccBB->begin();
5875 (PN = dyn_cast<PHINode>(I)); ++I) {
5876 // Ignore dead phi's.
5877 if (PN->use_empty()) continue;
5880 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5882 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5883 unsigned &RegOut = SDL->ConstantsOut[C];
5885 RegOut = FuncInfo->CreateRegForValue(C);
5886 SDL->CopyValueToVirtualRegister(C, RegOut);
5890 Reg = FuncInfo->ValueMap[PHIOp];
5892 assert(isa<AllocaInst>(PHIOp) &&
5893 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5894 "Didn't codegen value into a register!??");
5895 Reg = FuncInfo->CreateRegForValue(PHIOp);
5896 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5900 // Remember that this register needs to added to the machine PHI node as
5901 // the input for this MBB.
5902 SmallVector<MVT, 4> ValueVTs;
5903 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5904 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5905 MVT VT = ValueVTs[vti];
5906 unsigned NumRegisters = TLI.getNumRegisters(VT);
5907 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5908 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5909 Reg += NumRegisters;
5913 SDL->ConstantsOut.clear();
5916 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5917 /// supports legal types, and it emits MachineInstrs directly instead of
5918 /// creating SelectionDAG nodes.
5921 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5923 TerminatorInst *TI = LLVMBB->getTerminator();
5925 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5926 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5928 // Check successor nodes' PHI nodes that expect a constant to be available
5930 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5931 BasicBlock *SuccBB = TI->getSuccessor(succ);
5932 if (!isa<PHINode>(SuccBB->begin())) continue;
5933 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5935 // If this terminator has multiple identical successors (common for
5936 // switches), only handle each succ once.
5937 if (!SuccsHandled.insert(SuccMBB)) continue;
5939 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5942 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5943 // nodes and Machine PHI nodes, but the incoming operands have not been
5945 for (BasicBlock::iterator I = SuccBB->begin();
5946 (PN = dyn_cast<PHINode>(I)); ++I) {
5947 // Ignore dead phi's.
5948 if (PN->use_empty()) continue;
5950 // Only handle legal types. Two interesting things to note here. First,
5951 // by bailing out early, we may leave behind some dead instructions,
5952 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5953 // own moves. Second, this check is necessary becuase FastISel doesn't
5954 // use CreateRegForValue to create registers, so it always creates
5955 // exactly one register for each non-void instruction.
5956 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5957 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
5960 VT = TLI.getTypeToTransformTo(VT);
5962 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5967 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5969 unsigned Reg = F->getRegForValue(PHIOp);
5971 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5974 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));