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/Target/TargetRegisterInfo.h"
41 #include "llvm/Target/TargetData.h"
42 #include "llvm/Target/TargetFrameInfo.h"
43 #include "llvm/Target/TargetInstrInfo.h"
44 #include "llvm/Target/TargetLowering.h"
45 #include "llvm/Target/TargetMachine.h"
46 #include "llvm/Target/TargetOptions.h"
47 #include "llvm/Support/Compiler.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/MathExtras.h"
53 /// LimitFloatPrecision - Generate low-precision inline sequences for
54 /// some float libcalls (6, 8 or 12 bits).
55 static unsigned LimitFloatPrecision;
57 static cl::opt<unsigned, true>
58 LimitFPPrecision("limit-float-precision",
59 cl::desc("Generate low-precision inline sequences "
60 "for some float libcalls"),
61 cl::location(LimitFloatPrecision),
64 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
65 /// insertvalue or extractvalue indices that identify a member, return
66 /// the linearized index of the start of the member.
68 static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
69 const unsigned *Indices,
70 const unsigned *IndicesEnd,
71 unsigned CurIndex = 0) {
72 // Base case: We're done.
73 if (Indices && Indices == IndicesEnd)
76 // Given a struct type, recursively traverse the elements.
77 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
78 for (StructType::element_iterator EB = STy->element_begin(),
80 EE = STy->element_end();
82 if (Indices && *Indices == unsigned(EI - EB))
83 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
84 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
87 // Given an array type, recursively traverse the elements.
88 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
89 const Type *EltTy = ATy->getElementType();
90 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
91 if (Indices && *Indices == i)
92 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
93 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
96 // We haven't found the type we're looking for, so keep searching.
100 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
101 /// MVTs that represent all the individual underlying
102 /// non-aggregate types that comprise it.
104 /// If Offsets is non-null, it points to a vector to be filled in
105 /// with the in-memory offsets of each of the individual values.
107 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
108 SmallVectorImpl<MVT> &ValueVTs,
109 SmallVectorImpl<uint64_t> *Offsets = 0,
110 uint64_t StartingOffset = 0) {
111 // Given a struct type, recursively traverse the elements.
112 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
113 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
114 for (StructType::element_iterator EB = STy->element_begin(),
116 EE = STy->element_end();
118 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
119 StartingOffset + SL->getElementOffset(EI - EB));
122 // Given an array type, recursively traverse the elements.
123 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
124 const Type *EltTy = ATy->getElementType();
125 uint64_t EltSize = TLI.getTargetData()->getABITypeSize(EltTy);
126 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
127 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
128 StartingOffset + i * EltSize);
131 // Base case: we can get an MVT for this LLVM IR type.
132 ValueVTs.push_back(TLI.getValueType(Ty));
134 Offsets->push_back(StartingOffset);
138 /// RegsForValue - This struct represents the registers (physical or virtual)
139 /// that a particular set of values is assigned, and the type information about
140 /// the value. The most common situation is to represent one value at a time,
141 /// but struct or array values are handled element-wise as multiple values.
142 /// The splitting of aggregates is performed recursively, so that we never
143 /// have aggregate-typed registers. The values at this point do not necessarily
144 /// have legal types, so each value may require one or more registers of some
147 struct VISIBILITY_HIDDEN RegsForValue {
148 /// TLI - The TargetLowering object.
150 const TargetLowering *TLI;
152 /// ValueVTs - The value types of the values, which may not be legal, and
153 /// may need be promoted or synthesized from one or more registers.
155 SmallVector<MVT, 4> ValueVTs;
157 /// RegVTs - The value types of the registers. This is the same size as
158 /// ValueVTs and it records, for each value, what the type of the assigned
159 /// register or registers are. (Individual values are never synthesized
160 /// from more than one type of register.)
162 /// With virtual registers, the contents of RegVTs is redundant with TLI's
163 /// getRegisterType member function, however when with physical registers
164 /// it is necessary to have a separate record of the types.
166 SmallVector<MVT, 4> RegVTs;
168 /// Regs - This list holds the registers assigned to the values.
169 /// Each legal or promoted value requires one register, and each
170 /// expanded value requires multiple registers.
172 SmallVector<unsigned, 4> Regs;
174 RegsForValue() : TLI(0) {}
176 RegsForValue(const TargetLowering &tli,
177 const SmallVector<unsigned, 4> ®s,
178 MVT regvt, MVT valuevt)
179 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
180 RegsForValue(const TargetLowering &tli,
181 const SmallVector<unsigned, 4> ®s,
182 const SmallVector<MVT, 4> ®vts,
183 const SmallVector<MVT, 4> &valuevts)
184 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
185 RegsForValue(const TargetLowering &tli,
186 unsigned Reg, const Type *Ty) : TLI(&tli) {
187 ComputeValueVTs(tli, Ty, ValueVTs);
189 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
190 MVT ValueVT = ValueVTs[Value];
191 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
192 MVT RegisterVT = TLI->getRegisterType(ValueVT);
193 for (unsigned i = 0; i != NumRegs; ++i)
194 Regs.push_back(Reg + i);
195 RegVTs.push_back(RegisterVT);
200 /// append - Add the specified values to this one.
201 void append(const RegsForValue &RHS) {
203 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
204 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
205 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
209 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
210 /// this value and returns the result as a ValueVTs value. This uses
211 /// Chain/Flag as the input and updates them for the output Chain/Flag.
212 /// If the Flag pointer is NULL, no flag is used.
213 SDValue getCopyFromRegs(SelectionDAG &DAG,
214 SDValue &Chain, SDValue *Flag) const;
216 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
217 /// specified value into the registers specified by this object. This uses
218 /// Chain/Flag as the input and updates them for the output Chain/Flag.
219 /// If the Flag pointer is NULL, no flag is used.
220 void getCopyToRegs(SDValue Val, SelectionDAG &DAG,
221 SDValue &Chain, SDValue *Flag) const;
223 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
224 /// operand list. This adds the code marker and includes the number of
225 /// values added into it.
226 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
227 std::vector<SDValue> &Ops) const;
231 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
232 /// PHI nodes or outside of the basic block that defines it, or used by a
233 /// switch or atomic instruction, which may expand to multiple basic blocks.
234 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
235 if (isa<PHINode>(I)) return true;
236 BasicBlock *BB = I->getParent();
237 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
238 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
239 // FIXME: Remove switchinst special case.
240 isa<SwitchInst>(*UI))
245 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
246 /// entry block, return true. This includes arguments used by switches, since
247 /// the switch may expand into multiple basic blocks.
248 static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
249 // With FastISel active, we may be splitting blocks, so force creation
250 // of virtual registers for all non-dead arguments.
251 // Don't force virtual registers for byval arguments though, because
252 // fast-isel can't handle those in all cases.
253 if (EnableFastISel && !A->hasByValAttr())
254 return A->use_empty();
256 BasicBlock *Entry = A->getParent()->begin();
257 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
258 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
259 return false; // Use not in entry block.
263 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
267 void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
268 bool EnableFastISel) {
271 RegInfo = &MF->getRegInfo();
273 // Create a vreg for each argument register that is not dead and is used
274 // outside of the entry block for the function.
275 for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
277 if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
278 InitializeRegForValue(AI);
280 // Initialize the mapping of values to registers. This is only set up for
281 // instruction values that are used outside of the block that defines
283 Function::iterator BB = Fn->begin(), EB = Fn->end();
284 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
285 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
286 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
287 const Type *Ty = AI->getAllocatedType();
288 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
290 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
293 TySize *= CUI->getZExtValue(); // Get total allocated size.
294 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
295 StaticAllocaMap[AI] =
296 MF->getFrameInfo()->CreateStackObject(TySize, Align);
299 for (; BB != EB; ++BB)
300 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
301 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
302 if (!isa<AllocaInst>(I) ||
303 !StaticAllocaMap.count(cast<AllocaInst>(I)))
304 InitializeRegForValue(I);
306 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
307 // also creates the initial PHI MachineInstrs, though none of the input
308 // operands are populated.
309 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
310 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
314 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
317 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
318 if (PN->use_empty()) continue;
320 unsigned PHIReg = ValueMap[PN];
321 assert(PHIReg && "PHI node does not have an assigned virtual register!");
323 SmallVector<MVT, 4> ValueVTs;
324 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
325 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
326 MVT VT = ValueVTs[vti];
327 unsigned NumRegisters = TLI.getNumRegisters(VT);
328 const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
329 for (unsigned i = 0; i != NumRegisters; ++i)
330 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
331 PHIReg += NumRegisters;
337 unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
338 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
341 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
342 /// the correctly promoted or expanded types. Assign these registers
343 /// consecutive vreg numbers and return the first assigned number.
345 /// In the case that the given value has struct or array type, this function
346 /// will assign registers for each member or element.
348 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
349 SmallVector<MVT, 4> ValueVTs;
350 ComputeValueVTs(TLI, V->getType(), ValueVTs);
352 unsigned FirstReg = 0;
353 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
354 MVT ValueVT = ValueVTs[Value];
355 MVT RegisterVT = TLI.getRegisterType(ValueVT);
357 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
358 for (unsigned i = 0; i != NumRegs; ++i) {
359 unsigned R = MakeReg(RegisterVT);
360 if (!FirstReg) FirstReg = R;
366 /// getCopyFromParts - Create a value that contains the specified legal parts
367 /// combined into the value they represent. If the parts combine to a type
368 /// larger then ValueVT then AssertOp can be used to specify whether the extra
369 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
370 /// (ISD::AssertSext).
371 static SDValue getCopyFromParts(SelectionDAG &DAG,
372 const SDValue *Parts,
376 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
377 assert(NumParts > 0 && "No parts to assemble!");
378 TargetLowering &TLI = DAG.getTargetLoweringInfo();
379 SDValue Val = Parts[0];
382 // Assemble the value from multiple parts.
383 if (!ValueVT.isVector()) {
384 unsigned PartBits = PartVT.getSizeInBits();
385 unsigned ValueBits = ValueVT.getSizeInBits();
387 // Assemble the power of 2 part.
388 unsigned RoundParts = NumParts & (NumParts - 1) ?
389 1 << Log2_32(NumParts) : NumParts;
390 unsigned RoundBits = PartBits * RoundParts;
391 MVT RoundVT = RoundBits == ValueBits ?
392 ValueVT : MVT::getIntegerVT(RoundBits);
395 MVT HalfVT = ValueVT.isInteger() ?
396 MVT::getIntegerVT(RoundBits/2) :
397 MVT::getFloatingPointVT(RoundBits/2);
399 if (RoundParts > 2) {
400 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
401 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
404 Lo = DAG.getNode(ISD::BIT_CONVERT, HalfVT, Parts[0]);
405 Hi = DAG.getNode(ISD::BIT_CONVERT, HalfVT, Parts[1]);
407 if (TLI.isBigEndian())
409 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
411 if (RoundParts < NumParts) {
412 // Assemble the trailing non-power-of-2 part.
413 unsigned OddParts = NumParts - RoundParts;
414 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
415 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
417 // Combine the round and odd parts.
419 if (TLI.isBigEndian())
421 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
422 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
423 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
424 DAG.getConstant(Lo.getValueType().getSizeInBits(),
425 TLI.getShiftAmountTy()));
426 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
427 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
430 // Handle a multi-element vector.
431 MVT IntermediateVT, RegisterVT;
432 unsigned NumIntermediates;
434 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
436 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
437 NumParts = NumRegs; // Silence a compiler warning.
438 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
439 assert(RegisterVT == Parts[0].getValueType() &&
440 "Part type doesn't match part!");
442 // Assemble the parts into intermediate operands.
443 SmallVector<SDValue, 8> Ops(NumIntermediates);
444 if (NumIntermediates == NumParts) {
445 // If the register was not expanded, truncate or copy the value,
447 for (unsigned i = 0; i != NumParts; ++i)
448 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
449 PartVT, IntermediateVT);
450 } else if (NumParts > 0) {
451 // If the intermediate type was expanded, build the intermediate operands
453 assert(NumParts % NumIntermediates == 0 &&
454 "Must expand into a divisible number of parts!");
455 unsigned Factor = NumParts / NumIntermediates;
456 for (unsigned i = 0; i != NumIntermediates; ++i)
457 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
458 PartVT, IntermediateVT);
461 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
463 Val = DAG.getNode(IntermediateVT.isVector() ?
464 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
465 ValueVT, &Ops[0], NumIntermediates);
469 // There is now one part, held in Val. Correct it to match ValueVT.
470 PartVT = Val.getValueType();
472 if (PartVT == ValueVT)
475 if (PartVT.isVector()) {
476 assert(ValueVT.isVector() && "Unknown vector conversion!");
477 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
480 if (ValueVT.isVector()) {
481 assert(ValueVT.getVectorElementType() == PartVT &&
482 ValueVT.getVectorNumElements() == 1 &&
483 "Only trivial scalar-to-vector conversions should get here!");
484 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
487 if (PartVT.isInteger() &&
488 ValueVT.isInteger()) {
489 if (ValueVT.bitsLT(PartVT)) {
490 // For a truncate, see if we have any information to
491 // indicate whether the truncated bits will always be
492 // zero or sign-extension.
493 if (AssertOp != ISD::DELETED_NODE)
494 Val = DAG.getNode(AssertOp, PartVT, Val,
495 DAG.getValueType(ValueVT));
496 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
498 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
502 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
503 if (ValueVT.bitsLT(Val.getValueType()))
504 // FP_ROUND's are always exact here.
505 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
506 DAG.getIntPtrConstant(1));
507 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
510 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
511 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
513 assert(0 && "Unknown mismatch!");
517 /// getCopyToParts - Create a series of nodes that contain the specified value
518 /// split into legal parts. If the parts contain more bits than Val, then, for
519 /// integers, ExtendKind can be used to specify how to generate the extra bits.
520 static void getCopyToParts(SelectionDAG &DAG, SDValue Val,
521 SDValue *Parts, unsigned NumParts, MVT PartVT,
522 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
523 TargetLowering &TLI = DAG.getTargetLoweringInfo();
524 MVT PtrVT = TLI.getPointerTy();
525 MVT ValueVT = Val.getValueType();
526 unsigned PartBits = PartVT.getSizeInBits();
527 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
532 if (!ValueVT.isVector()) {
533 if (PartVT == ValueVT) {
534 assert(NumParts == 1 && "No-op copy with multiple parts!");
539 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
540 // If the parts cover more bits than the value has, promote the value.
541 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
542 assert(NumParts == 1 && "Do not know what to promote to!");
543 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
544 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
545 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
546 Val = DAG.getNode(ExtendKind, ValueVT, Val);
548 assert(0 && "Unknown mismatch!");
550 } else if (PartBits == ValueVT.getSizeInBits()) {
551 // Different types of the same size.
552 assert(NumParts == 1 && PartVT != ValueVT);
553 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
554 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
555 // If the parts cover less bits than value has, truncate the value.
556 if (PartVT.isInteger() && ValueVT.isInteger()) {
557 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
558 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
560 assert(0 && "Unknown mismatch!");
564 // The value may have changed - recompute ValueVT.
565 ValueVT = Val.getValueType();
566 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
567 "Failed to tile the value with PartVT!");
570 assert(PartVT == ValueVT && "Type conversion failed!");
575 // Expand the value into multiple parts.
576 if (NumParts & (NumParts - 1)) {
577 // The number of parts is not a power of 2. Split off and copy the tail.
578 assert(PartVT.isInteger() && ValueVT.isInteger() &&
579 "Do not know what to expand to!");
580 unsigned RoundParts = 1 << Log2_32(NumParts);
581 unsigned RoundBits = RoundParts * PartBits;
582 unsigned OddParts = NumParts - RoundParts;
583 SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
584 DAG.getConstant(RoundBits,
585 TLI.getShiftAmountTy()));
586 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
587 if (TLI.isBigEndian())
588 // The odd parts were reversed by getCopyToParts - unreverse them.
589 std::reverse(Parts + RoundParts, Parts + NumParts);
590 NumParts = RoundParts;
591 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
592 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
595 // The number of parts is a power of 2. Repeatedly bisect the value using
597 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
598 MVT::getIntegerVT(ValueVT.getSizeInBits()),
600 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
601 for (unsigned i = 0; i < NumParts; i += StepSize) {
602 unsigned ThisBits = StepSize * PartBits / 2;
603 MVT ThisVT = MVT::getIntegerVT (ThisBits);
604 SDValue &Part0 = Parts[i];
605 SDValue &Part1 = Parts[i+StepSize/2];
607 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
608 DAG.getConstant(1, PtrVT));
609 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
610 DAG.getConstant(0, PtrVT));
612 if (ThisBits == PartBits && ThisVT != PartVT) {
613 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
614 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
619 if (TLI.isBigEndian())
620 std::reverse(Parts, Parts + NumParts);
627 if (PartVT != ValueVT) {
628 if (PartVT.isVector()) {
629 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
631 assert(ValueVT.getVectorElementType() == PartVT &&
632 ValueVT.getVectorNumElements() == 1 &&
633 "Only trivial vector-to-scalar conversions should get here!");
634 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
635 DAG.getConstant(0, PtrVT));
643 // Handle a multi-element vector.
644 MVT IntermediateVT, RegisterVT;
645 unsigned NumIntermediates;
647 DAG.getTargetLoweringInfo()
648 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
650 unsigned NumElements = ValueVT.getVectorNumElements();
652 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
653 NumParts = NumRegs; // Silence a compiler warning.
654 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
656 // Split the vector into intermediate operands.
657 SmallVector<SDValue, 8> Ops(NumIntermediates);
658 for (unsigned i = 0; i != NumIntermediates; ++i)
659 if (IntermediateVT.isVector())
660 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
662 DAG.getConstant(i * (NumElements / NumIntermediates),
665 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
667 DAG.getConstant(i, PtrVT));
669 // Split the intermediate operands into legal parts.
670 if (NumParts == NumIntermediates) {
671 // If the register was not expanded, promote or copy the value,
673 for (unsigned i = 0; i != NumParts; ++i)
674 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
675 } else if (NumParts > 0) {
676 // If the intermediate type was expanded, split each the value into
678 assert(NumParts % NumIntermediates == 0 &&
679 "Must expand into a divisible number of parts!");
680 unsigned Factor = NumParts / NumIntermediates;
681 for (unsigned i = 0; i != NumIntermediates; ++i)
682 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
687 void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
690 TD = DAG.getTarget().getTargetData();
693 /// clear - Clear out the curret SelectionDAG and the associated
694 /// state and prepare this SelectionDAGLowering object to be used
695 /// for a new block. This doesn't clear out information about
696 /// additional blocks that are needed to complete switch lowering
697 /// or PHI node updating; that information is cleared out as it is
699 void SelectionDAGLowering::clear() {
701 PendingLoads.clear();
702 PendingExports.clear();
706 /// getRoot - Return the current virtual root of the Selection DAG,
707 /// flushing any PendingLoad items. This must be done before emitting
708 /// a store or any other node that may need to be ordered after any
709 /// prior load instructions.
711 SDValue SelectionDAGLowering::getRoot() {
712 if (PendingLoads.empty())
713 return DAG.getRoot();
715 if (PendingLoads.size() == 1) {
716 SDValue Root = PendingLoads[0];
718 PendingLoads.clear();
722 // Otherwise, we have to make a token factor node.
723 SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
724 &PendingLoads[0], PendingLoads.size());
725 PendingLoads.clear();
730 /// getControlRoot - Similar to getRoot, but instead of flushing all the
731 /// PendingLoad items, flush all the PendingExports items. It is necessary
732 /// to do this before emitting a terminator instruction.
734 SDValue SelectionDAGLowering::getControlRoot() {
735 SDValue Root = DAG.getRoot();
737 if (PendingExports.empty())
740 // Turn all of the CopyToReg chains into one factored node.
741 if (Root.getOpcode() != ISD::EntryToken) {
742 unsigned i = 0, e = PendingExports.size();
743 for (; i != e; ++i) {
744 assert(PendingExports[i].getNode()->getNumOperands() > 1);
745 if (PendingExports[i].getNode()->getOperand(0) == Root)
746 break; // Don't add the root if we already indirectly depend on it.
750 PendingExports.push_back(Root);
753 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
755 PendingExports.size());
756 PendingExports.clear();
761 void SelectionDAGLowering::visit(Instruction &I) {
762 visit(I.getOpcode(), I);
765 void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
766 // Note: this doesn't use InstVisitor, because it has to work with
767 // ConstantExpr's in addition to instructions.
769 default: assert(0 && "Unknown instruction type encountered!");
771 // Build the switch statement using the Instruction.def file.
772 #define HANDLE_INST(NUM, OPCODE, CLASS) \
773 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
774 #include "llvm/Instruction.def"
778 void SelectionDAGLowering::visitAdd(User &I) {
779 if (I.getType()->isFPOrFPVector())
780 visitBinary(I, ISD::FADD);
782 visitBinary(I, ISD::ADD);
785 void SelectionDAGLowering::visitMul(User &I) {
786 if (I.getType()->isFPOrFPVector())
787 visitBinary(I, ISD::FMUL);
789 visitBinary(I, ISD::MUL);
792 SDValue SelectionDAGLowering::getValue(const Value *V) {
793 SDValue &N = NodeMap[V];
794 if (N.getNode()) return N;
796 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
797 MVT VT = TLI.getValueType(V->getType(), true);
799 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
800 return N = DAG.getConstant(*CI, VT);
802 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
803 return N = DAG.getGlobalAddress(GV, VT);
805 if (isa<ConstantPointerNull>(C))
806 return N = DAG.getConstant(0, TLI.getPointerTy());
808 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
809 return N = DAG.getConstantFP(*CFP, VT);
811 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
812 !V->getType()->isAggregateType())
813 return N = DAG.getNode(ISD::UNDEF, VT);
815 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
816 visit(CE->getOpcode(), *CE);
817 SDValue N1 = NodeMap[V];
818 assert(N1.getNode() && "visit didn't populate the ValueMap!");
822 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
823 SmallVector<SDValue, 4> Constants;
824 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
826 SDNode *Val = getValue(*OI).getNode();
827 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
828 Constants.push_back(SDValue(Val, i));
830 return DAG.getMergeValues(&Constants[0], Constants.size());
833 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
834 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
835 "Unknown struct or array constant!");
837 SmallVector<MVT, 4> ValueVTs;
838 ComputeValueVTs(TLI, C->getType(), ValueVTs);
839 unsigned NumElts = ValueVTs.size();
841 return SDValue(); // empty struct
842 SmallVector<SDValue, 4> Constants(NumElts);
843 for (unsigned i = 0; i != NumElts; ++i) {
844 MVT EltVT = ValueVTs[i];
845 if (isa<UndefValue>(C))
846 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
847 else if (EltVT.isFloatingPoint())
848 Constants[i] = DAG.getConstantFP(0, EltVT);
850 Constants[i] = DAG.getConstant(0, EltVT);
852 return DAG.getMergeValues(&Constants[0], NumElts);
855 const VectorType *VecTy = cast<VectorType>(V->getType());
856 unsigned NumElements = VecTy->getNumElements();
858 // Now that we know the number and type of the elements, get that number of
859 // elements into the Ops array based on what kind of constant it is.
860 SmallVector<SDValue, 16> Ops;
861 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
862 for (unsigned i = 0; i != NumElements; ++i)
863 Ops.push_back(getValue(CP->getOperand(i)));
865 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
866 "Unknown vector constant!");
867 MVT EltVT = TLI.getValueType(VecTy->getElementType());
870 if (isa<UndefValue>(C))
871 Op = DAG.getNode(ISD::UNDEF, EltVT);
872 else if (EltVT.isFloatingPoint())
873 Op = DAG.getConstantFP(0, EltVT);
875 Op = DAG.getConstant(0, EltVT);
876 Ops.assign(NumElements, Op);
879 // Create a BUILD_VECTOR node.
880 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
883 // If this is a static alloca, generate it as the frameindex instead of
885 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
886 DenseMap<const AllocaInst*, int>::iterator SI =
887 FuncInfo.StaticAllocaMap.find(AI);
888 if (SI != FuncInfo.StaticAllocaMap.end())
889 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
892 unsigned InReg = FuncInfo.ValueMap[V];
893 assert(InReg && "Value not in map!");
895 RegsForValue RFV(TLI, InReg, V->getType());
896 SDValue Chain = DAG.getEntryNode();
897 return RFV.getCopyFromRegs(DAG, Chain, NULL);
901 void SelectionDAGLowering::visitRet(ReturnInst &I) {
902 if (I.getNumOperands() == 0) {
903 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
907 SmallVector<SDValue, 8> NewValues;
908 NewValues.push_back(getControlRoot());
909 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
910 SmallVector<MVT, 4> ValueVTs;
911 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
912 unsigned NumValues = ValueVTs.size();
913 if (NumValues == 0) continue;
915 SDValue RetOp = getValue(I.getOperand(i));
916 for (unsigned j = 0, f = NumValues; j != f; ++j) {
917 MVT VT = ValueVTs[j];
919 // FIXME: C calling convention requires the return type to be promoted to
920 // at least 32-bit. But this is not necessary for non-C calling
922 if (VT.isInteger()) {
923 MVT MinVT = TLI.getRegisterType(MVT::i32);
924 if (VT.bitsLT(MinVT))
928 unsigned NumParts = TLI.getNumRegisters(VT);
929 MVT PartVT = TLI.getRegisterType(VT);
930 SmallVector<SDValue, 4> Parts(NumParts);
931 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
933 const Function *F = I.getParent()->getParent();
934 if (F->paramHasAttr(0, Attribute::SExt))
935 ExtendKind = ISD::SIGN_EXTEND;
936 else if (F->paramHasAttr(0, Attribute::ZExt))
937 ExtendKind = ISD::ZERO_EXTEND;
939 getCopyToParts(DAG, SDValue(RetOp.getNode(), RetOp.getResNo() + j),
940 &Parts[0], NumParts, PartVT, ExtendKind);
942 // 'inreg' on function refers to return value
943 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
944 if (F->paramHasAttr(0, Attribute::InReg))
946 for (unsigned i = 0; i < NumParts; ++i) {
947 NewValues.push_back(Parts[i]);
948 NewValues.push_back(DAG.getArgFlags(Flags));
952 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
953 &NewValues[0], NewValues.size()));
956 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
957 /// the current basic block, add it to ValueMap now so that we'll get a
959 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
960 // No need to export constants.
961 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
964 if (FuncInfo.isExportedInst(V)) return;
966 unsigned Reg = FuncInfo.InitializeRegForValue(V);
967 CopyValueToVirtualRegister(V, Reg);
970 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
971 const BasicBlock *FromBB) {
972 // The operands of the setcc have to be in this block. We don't know
973 // how to export them from some other block.
974 if (Instruction *VI = dyn_cast<Instruction>(V)) {
975 // Can export from current BB.
976 if (VI->getParent() == FromBB)
979 // Is already exported, noop.
980 return FuncInfo.isExportedInst(V);
983 // If this is an argument, we can export it if the BB is the entry block or
984 // if it is already exported.
985 if (isa<Argument>(V)) {
986 if (FromBB == &FromBB->getParent()->getEntryBlock())
989 // Otherwise, can only export this if it is already exported.
990 return FuncInfo.isExportedInst(V);
993 // Otherwise, constants can always be exported.
997 static bool InBlock(const Value *V, const BasicBlock *BB) {
998 if (const Instruction *I = dyn_cast<Instruction>(V))
999 return I->getParent() == BB;
1003 /// getFCmpCondCode - Return the ISD condition code corresponding to
1004 /// the given LLVM IR floating-point condition code. This includes
1005 /// consideration of global floating-point math flags.
1007 static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
1008 ISD::CondCode FPC, FOC;
1010 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1011 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1012 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1013 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1014 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1015 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1016 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1017 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1018 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1019 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1020 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1021 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1022 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1023 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1024 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1025 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1027 assert(0 && "Invalid FCmp predicate opcode!");
1028 FOC = FPC = ISD::SETFALSE;
1031 if (FiniteOnlyFPMath())
1037 /// getICmpCondCode - Return the ISD condition code corresponding to
1038 /// the given LLVM IR integer condition code.
1040 static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
1042 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
1043 case ICmpInst::ICMP_NE: return ISD::SETNE;
1044 case ICmpInst::ICMP_SLE: return ISD::SETLE;
1045 case ICmpInst::ICMP_ULE: return ISD::SETULE;
1046 case ICmpInst::ICMP_SGE: return ISD::SETGE;
1047 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
1048 case ICmpInst::ICMP_SLT: return ISD::SETLT;
1049 case ICmpInst::ICMP_ULT: return ISD::SETULT;
1050 case ICmpInst::ICMP_SGT: return ISD::SETGT;
1051 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
1053 assert(0 && "Invalid ICmp predicate opcode!");
1058 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1059 /// This function emits a branch and is used at the leaves of an OR or an
1060 /// AND operator tree.
1063 SelectionDAGLowering::EmitBranchForMergedCondition(Value *Cond,
1064 MachineBasicBlock *TBB,
1065 MachineBasicBlock *FBB,
1066 MachineBasicBlock *CurBB) {
1067 const BasicBlock *BB = CurBB->getBasicBlock();
1069 // If the leaf of the tree is a comparison, merge the condition into
1071 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1072 // The operands of the cmp have to be in this block. We don't know
1073 // how to export them from some other block. If this is the first block
1074 // of the sequence, no exporting is needed.
1075 if (CurBB == CurMBB ||
1076 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1077 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1078 ISD::CondCode Condition;
1079 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1080 Condition = getICmpCondCode(IC->getPredicate());
1081 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1082 Condition = getFCmpCondCode(FC->getPredicate());
1084 Condition = ISD::SETEQ; // silence warning.
1085 assert(0 && "Unknown compare instruction");
1088 CaseBlock CB(Condition, BOp->getOperand(0),
1089 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1090 SwitchCases.push_back(CB);
1095 // Create a CaseBlock record representing this branch.
1096 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1097 NULL, TBB, FBB, CurBB);
1098 SwitchCases.push_back(CB);
1101 /// FindMergedConditions - If Cond is an expression like
1102 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
1103 MachineBasicBlock *TBB,
1104 MachineBasicBlock *FBB,
1105 MachineBasicBlock *CurBB,
1107 // If this node is not part of the or/and tree, emit it as a branch.
1108 Instruction *BOp = dyn_cast<Instruction>(Cond);
1109 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1110 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1111 BOp->getParent() != CurBB->getBasicBlock() ||
1112 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1113 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1114 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
1118 // Create TmpBB after CurBB.
1119 MachineFunction::iterator BBI = CurBB;
1120 MachineFunction &MF = DAG.getMachineFunction();
1121 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1122 CurBB->getParent()->insert(++BBI, TmpBB);
1124 if (Opc == Instruction::Or) {
1125 // Codegen X | Y as:
1133 // Emit the LHS condition.
1134 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1136 // Emit the RHS condition into TmpBB.
1137 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1139 assert(Opc == Instruction::And && "Unknown merge op!");
1140 // Codegen X & Y as:
1147 // This requires creation of TmpBB after CurBB.
1149 // Emit the LHS condition.
1150 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1152 // Emit the RHS condition into TmpBB.
1153 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1157 /// If the set of cases should be emitted as a series of branches, return true.
1158 /// If we should emit this as a bunch of and/or'd together conditions, return
1161 SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1162 if (Cases.size() != 2) return true;
1164 // If this is two comparisons of the same values or'd or and'd together, they
1165 // will get folded into a single comparison, so don't emit two blocks.
1166 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1167 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1168 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1169 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1176 void SelectionDAGLowering::visitBr(BranchInst &I) {
1177 // Update machine-CFG edges.
1178 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1180 // Figure out which block is immediately after the current one.
1181 MachineBasicBlock *NextBlock = 0;
1182 MachineFunction::iterator BBI = CurMBB;
1183 if (++BBI != CurMBB->getParent()->end())
1186 if (I.isUnconditional()) {
1187 // Update machine-CFG edges.
1188 CurMBB->addSuccessor(Succ0MBB);
1190 // If this is not a fall-through branch, emit the branch.
1191 if (Succ0MBB != NextBlock)
1192 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1193 DAG.getBasicBlock(Succ0MBB)));
1197 // If this condition is one of the special cases we handle, do special stuff
1199 Value *CondVal = I.getCondition();
1200 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1202 // If this is a series of conditions that are or'd or and'd together, emit
1203 // this as a sequence of branches instead of setcc's with and/or operations.
1204 // For example, instead of something like:
1217 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1218 if (BOp->hasOneUse() &&
1219 (BOp->getOpcode() == Instruction::And ||
1220 BOp->getOpcode() == Instruction::Or)) {
1221 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1222 // If the compares in later blocks need to use values not currently
1223 // exported from this block, export them now. This block should always
1224 // be the first entry.
1225 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1227 // Allow some cases to be rejected.
1228 if (ShouldEmitAsBranches(SwitchCases)) {
1229 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1230 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1231 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1234 // Emit the branch for this block.
1235 visitSwitchCase(SwitchCases[0]);
1236 SwitchCases.erase(SwitchCases.begin());
1240 // Okay, we decided not to do this, remove any inserted MBB's and clear
1242 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1243 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
1245 SwitchCases.clear();
1249 // Create a CaseBlock record representing this branch.
1250 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1251 NULL, Succ0MBB, Succ1MBB, CurMBB);
1252 // Use visitSwitchCase to actually insert the fast branch sequence for this
1254 visitSwitchCase(CB);
1257 /// visitSwitchCase - Emits the necessary code to represent a single node in
1258 /// the binary search tree resulting from lowering a switch instruction.
1259 void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1261 SDValue CondLHS = getValue(CB.CmpLHS);
1263 // Build the setcc now.
1264 if (CB.CmpMHS == NULL) {
1265 // Fold "(X == true)" to X and "(X == false)" to !X to
1266 // handle common cases produced by branch lowering.
1267 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1269 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1270 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1271 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1273 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1275 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1277 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1278 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1280 SDValue CmpOp = getValue(CB.CmpMHS);
1281 MVT VT = CmpOp.getValueType();
1283 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1284 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1286 SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1287 Cond = DAG.getSetCC(MVT::i1, SUB,
1288 DAG.getConstant(High-Low, VT), ISD::SETULE);
1292 // Update successor info
1293 CurMBB->addSuccessor(CB.TrueBB);
1294 CurMBB->addSuccessor(CB.FalseBB);
1296 // Set NextBlock to be the MBB immediately after the current one, if any.
1297 // This is used to avoid emitting unnecessary branches to the next block.
1298 MachineBasicBlock *NextBlock = 0;
1299 MachineFunction::iterator BBI = CurMBB;
1300 if (++BBI != CurMBB->getParent()->end())
1303 // If the lhs block is the next block, invert the condition so that we can
1304 // fall through to the lhs instead of the rhs block.
1305 if (CB.TrueBB == NextBlock) {
1306 std::swap(CB.TrueBB, CB.FalseBB);
1307 SDValue True = DAG.getConstant(1, Cond.getValueType());
1308 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1310 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1311 DAG.getBasicBlock(CB.TrueBB));
1313 // If the branch was constant folded, fix up the CFG.
1314 if (BrCond.getOpcode() == ISD::BR) {
1315 CurMBB->removeSuccessor(CB.FalseBB);
1316 DAG.setRoot(BrCond);
1318 // Otherwise, go ahead and insert the false branch.
1319 if (BrCond == getControlRoot())
1320 CurMBB->removeSuccessor(CB.TrueBB);
1322 if (CB.FalseBB == NextBlock)
1323 DAG.setRoot(BrCond);
1325 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1326 DAG.getBasicBlock(CB.FalseBB)));
1330 /// visitJumpTable - Emit JumpTable node in the current MBB
1331 void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1332 // Emit the code for the jump table
1333 assert(JT.Reg != -1U && "Should lower JT Header first!");
1334 MVT PTy = TLI.getPointerTy();
1335 SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1336 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1337 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1342 /// visitJumpTableHeader - This function emits necessary code to produce index
1343 /// in the JumpTable from switch case.
1344 void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1345 JumpTableHeader &JTH) {
1346 // Subtract the lowest switch case value from the value being switched on and
1347 // conditional branch to default mbb if the result is greater than the
1348 // difference between smallest and largest cases.
1349 SDValue SwitchOp = getValue(JTH.SValue);
1350 MVT VT = SwitchOp.getValueType();
1351 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1352 DAG.getConstant(JTH.First, VT));
1354 // The SDNode we just created, which holds the value being switched on minus
1355 // the the smallest case value, needs to be copied to a virtual register so it
1356 // can be used as an index into the jump table in a subsequent basic block.
1357 // This value may be smaller or larger than the target's pointer type, and
1358 // therefore require extension or truncating.
1359 if (VT.bitsGT(TLI.getPointerTy()))
1360 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1362 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1364 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1365 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1366 JT.Reg = JumpTableReg;
1368 // Emit the range check for the jump table, and branch to the default block
1369 // for the switch statement if the value being switched on exceeds the largest
1370 // case in the switch.
1371 SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1372 DAG.getConstant(JTH.Last-JTH.First,VT),
1375 // Set NextBlock to be the MBB immediately after the current one, if any.
1376 // This is used to avoid emitting unnecessary branches to the next block.
1377 MachineBasicBlock *NextBlock = 0;
1378 MachineFunction::iterator BBI = CurMBB;
1379 if (++BBI != CurMBB->getParent()->end())
1382 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1383 DAG.getBasicBlock(JT.Default));
1385 if (JT.MBB == NextBlock)
1386 DAG.setRoot(BrCond);
1388 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1389 DAG.getBasicBlock(JT.MBB)));
1394 /// visitBitTestHeader - This function emits necessary code to produce value
1395 /// suitable for "bit tests"
1396 void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1397 // Subtract the minimum value
1398 SDValue SwitchOp = getValue(B.SValue);
1399 MVT VT = SwitchOp.getValueType();
1400 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1401 DAG.getConstant(B.First, VT));
1404 SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1405 DAG.getConstant(B.Range, VT),
1409 if (VT.bitsGT(TLI.getShiftAmountTy()))
1410 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1412 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1414 // Make desired shift
1415 SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1416 DAG.getConstant(1, TLI.getPointerTy()),
1419 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1420 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1423 // Set NextBlock to be the MBB immediately after the current one, if any.
1424 // This is used to avoid emitting unnecessary branches to the next block.
1425 MachineBasicBlock *NextBlock = 0;
1426 MachineFunction::iterator BBI = CurMBB;
1427 if (++BBI != CurMBB->getParent()->end())
1430 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1432 CurMBB->addSuccessor(B.Default);
1433 CurMBB->addSuccessor(MBB);
1435 SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1436 DAG.getBasicBlock(B.Default));
1438 if (MBB == NextBlock)
1439 DAG.setRoot(BrRange);
1441 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1442 DAG.getBasicBlock(MBB)));
1447 /// visitBitTestCase - this function produces one "bit test"
1448 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1451 // Emit bit tests and jumps
1452 SDValue SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg,
1453 TLI.getPointerTy());
1455 SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
1456 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1457 SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1458 DAG.getConstant(0, TLI.getPointerTy()),
1461 CurMBB->addSuccessor(B.TargetBB);
1462 CurMBB->addSuccessor(NextMBB);
1464 SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1465 AndCmp, DAG.getBasicBlock(B.TargetBB));
1467 // Set NextBlock to be the MBB immediately after the current one, if any.
1468 // This is used to avoid emitting unnecessary branches to the next block.
1469 MachineBasicBlock *NextBlock = 0;
1470 MachineFunction::iterator BBI = CurMBB;
1471 if (++BBI != CurMBB->getParent()->end())
1474 if (NextMBB == NextBlock)
1477 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1478 DAG.getBasicBlock(NextMBB)));
1483 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1484 // Retrieve successors.
1485 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1486 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1488 if (isa<InlineAsm>(I.getCalledValue()))
1491 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1493 // If the value of the invoke is used outside of its defining block, make it
1494 // available as a virtual register.
1495 if (!I.use_empty()) {
1496 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1497 if (VMI != FuncInfo.ValueMap.end())
1498 CopyValueToVirtualRegister(&I, VMI->second);
1501 // Update successor info
1502 CurMBB->addSuccessor(Return);
1503 CurMBB->addSuccessor(LandingPad);
1505 // Drop into normal successor.
1506 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1507 DAG.getBasicBlock(Return)));
1510 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1513 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1514 /// small case ranges).
1515 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1516 CaseRecVector& WorkList,
1518 MachineBasicBlock* Default) {
1519 Case& BackCase = *(CR.Range.second-1);
1521 // Size is the number of Cases represented by this range.
1522 size_t Size = CR.Range.second - CR.Range.first;
1526 // Get the MachineFunction which holds the current MBB. This is used when
1527 // inserting any additional MBBs necessary to represent the switch.
1528 MachineFunction *CurMF = CurMBB->getParent();
1530 // Figure out which block is immediately after the current one.
1531 MachineBasicBlock *NextBlock = 0;
1532 MachineFunction::iterator BBI = CR.CaseBB;
1534 if (++BBI != CurMBB->getParent()->end())
1537 // TODO: If any two of the cases has the same destination, and if one value
1538 // is the same as the other, but has one bit unset that the other has set,
1539 // use bit manipulation to do two compares at once. For example:
1540 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1542 // Rearrange the case blocks so that the last one falls through if possible.
1543 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1544 // The last case block won't fall through into 'NextBlock' if we emit the
1545 // branches in this order. See if rearranging a case value would help.
1546 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1547 if (I->BB == NextBlock) {
1548 std::swap(*I, BackCase);
1554 // Create a CaseBlock record representing a conditional branch to
1555 // the Case's target mbb if the value being switched on SV is equal
1557 MachineBasicBlock *CurBlock = CR.CaseBB;
1558 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1559 MachineBasicBlock *FallThrough;
1561 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1562 CurMF->insert(BBI, FallThrough);
1564 // If the last case doesn't match, go to the default block.
1565 FallThrough = Default;
1568 Value *RHS, *LHS, *MHS;
1570 if (I->High == I->Low) {
1571 // This is just small small case range :) containing exactly 1 case
1573 LHS = SV; RHS = I->High; MHS = NULL;
1576 LHS = I->Low; MHS = SV; RHS = I->High;
1578 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1580 // If emitting the first comparison, just call visitSwitchCase to emit the
1581 // code into the current block. Otherwise, push the CaseBlock onto the
1582 // vector to be later processed by SDISel, and insert the node's MBB
1583 // before the next MBB.
1584 if (CurBlock == CurMBB)
1585 visitSwitchCase(CB);
1587 SwitchCases.push_back(CB);
1589 CurBlock = FallThrough;
1595 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1596 return !DisableJumpTables &&
1597 (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1598 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1601 /// handleJTSwitchCase - Emit jumptable for current switch case range
1602 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1603 CaseRecVector& WorkList,
1605 MachineBasicBlock* Default) {
1606 Case& FrontCase = *CR.Range.first;
1607 Case& BackCase = *(CR.Range.second-1);
1609 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1610 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
1613 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1617 if (!areJTsAllowed(TLI) || TSize <= 3)
1620 APInt Range = Last - First + 1ULL;
1621 double Density = (double)TSize / Range.roundToDouble();
1625 /*DOUT << "Lowering jump table\n"
1626 << "First entry: " << First << ". Last entry: " << Last << "\n"
1627 << "Size: " << TSize << ". Density: " << Density << "\n\n";*/
1629 // Get the MachineFunction which holds the current MBB. This is used when
1630 // inserting any additional MBBs necessary to represent the switch.
1631 MachineFunction *CurMF = CurMBB->getParent();
1633 // Figure out which block is immediately after the current one.
1634 MachineBasicBlock *NextBlock = 0;
1635 MachineFunction::iterator BBI = CR.CaseBB;
1637 if (++BBI != CurMBB->getParent()->end())
1640 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1642 // Create a new basic block to hold the code for loading the address
1643 // of the jump table, and jumping to it. Update successor information;
1644 // we will either branch to the default case for the switch, or the jump
1646 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1647 CurMF->insert(BBI, JumpTableBB);
1648 CR.CaseBB->addSuccessor(Default);
1649 CR.CaseBB->addSuccessor(JumpTableBB);
1651 // Build a vector of destination BBs, corresponding to each target
1652 // of the jump table. If the value of the jump table slot corresponds to
1653 // a case statement, push the case's BB onto the vector, otherwise, push
1655 std::vector<MachineBasicBlock*> DestBBs;
1657 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1658 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1659 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1661 if (Low.sle(TEI) && TEI.sle(High)) {
1662 DestBBs.push_back(I->BB);
1666 DestBBs.push_back(Default);
1670 // Update successor info. Add one edge to each unique successor.
1671 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1672 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1673 E = DestBBs.end(); I != E; ++I) {
1674 if (!SuccsHandled[(*I)->getNumber()]) {
1675 SuccsHandled[(*I)->getNumber()] = true;
1676 JumpTableBB->addSuccessor(*I);
1680 // Create a jump table index for this jump table, or return an existing
1682 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1684 // Set the jump table information so that we can codegen it as a second
1685 // MachineBasicBlock
1686 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1687 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1688 if (CR.CaseBB == CurMBB)
1689 visitJumpTableHeader(JT, JTH);
1691 JTCases.push_back(JumpTableBlock(JTH, JT));
1696 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1698 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1699 CaseRecVector& WorkList,
1701 MachineBasicBlock* Default) {
1702 // Get the MachineFunction which holds the current MBB. This is used when
1703 // inserting any additional MBBs necessary to represent the switch.
1704 MachineFunction *CurMF = CurMBB->getParent();
1706 // Figure out which block is immediately after the current one.
1707 MachineBasicBlock *NextBlock = 0;
1708 MachineFunction::iterator BBI = CR.CaseBB;
1710 if (++BBI != CurMBB->getParent()->end())
1713 Case& FrontCase = *CR.Range.first;
1714 Case& BackCase = *(CR.Range.second-1);
1715 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1717 // Size is the number of Cases represented by this range.
1718 unsigned Size = CR.Range.second - CR.Range.first;
1720 const APInt& First = cast<ConstantInt>(FrontCase.Low)->getValue();
1721 const APInt& Last = cast<ConstantInt>(BackCase.High)->getValue();
1723 CaseItr Pivot = CR.Range.first + Size/2;
1725 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1726 // (heuristically) allow us to emit JumpTable's later.
1728 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1732 size_t LSize = FrontCase.size();
1733 size_t RSize = TSize-LSize;
1734 /*DOUT << "Selecting best pivot: \n"
1735 << "First: " << First << ", Last: " << Last <<"\n"
1736 << "LSize: " << LSize << ", RSize: " << RSize << "\n";*/
1737 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1739 const APInt& LEnd = cast<ConstantInt>(I->High)->getValue();
1740 const APInt& RBegin = cast<ConstantInt>(J->Low)->getValue();
1741 assert((RBegin - LEnd - 1).isNonNegative() && "Invalid case distance");
1742 double LDensity = (double)LSize / (LEnd - First + 1ULL).roundToDouble();
1743 double RDensity = (double)RSize / (Last - RBegin + 1ULL).roundToDouble();
1744 double Metric = (RBegin-LEnd).logBase2()*(LDensity+RDensity);
1745 // Should always split in some non-trivial place
1747 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1748 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1749 << "Metric: " << Metric << "\n";*/
1750 if (FMetric < Metric) {
1753 DOUT << "Current metric set to: " << FMetric << "\n";
1759 if (areJTsAllowed(TLI)) {
1760 // If our case is dense we *really* should handle it earlier!
1761 assert((FMetric > 0) && "Should handle dense range earlier!");
1763 Pivot = CR.Range.first + Size/2;
1766 CaseRange LHSR(CR.Range.first, Pivot);
1767 CaseRange RHSR(Pivot, CR.Range.second);
1768 Constant *C = Pivot->Low;
1769 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1771 // We know that we branch to the LHS if the Value being switched on is
1772 // less than the Pivot value, C. We use this to optimize our binary
1773 // tree a bit, by recognizing that if SV is greater than or equal to the
1774 // LHS's Case Value, and that Case Value is exactly one less than the
1775 // Pivot's Value, then we can branch directly to the LHS's Target,
1776 // rather than creating a leaf node for it.
1777 if ((LHSR.second - LHSR.first) == 1 &&
1778 LHSR.first->High == CR.GE &&
1779 cast<ConstantInt>(C)->getValue() ==
1780 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
1781 TrueBB = LHSR.first->BB;
1783 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1784 CurMF->insert(BBI, TrueBB);
1785 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1788 // Similar to the optimization above, if the Value being switched on is
1789 // known to be less than the Constant CR.LT, and the current Case Value
1790 // is CR.LT - 1, then we can branch directly to the target block for
1791 // the current Case Value, rather than emitting a RHS leaf node for it.
1792 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1793 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1794 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
1795 FalseBB = RHSR.first->BB;
1797 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1798 CurMF->insert(BBI, FalseBB);
1799 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1802 // Create a CaseBlock record representing a conditional branch to
1803 // the LHS node if the value being switched on SV is less than C.
1804 // Otherwise, branch to LHS.
1805 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1807 if (CR.CaseBB == CurMBB)
1808 visitSwitchCase(CB);
1810 SwitchCases.push_back(CB);
1815 /// handleBitTestsSwitchCase - if current case range has few destination and
1816 /// range span less, than machine word bitwidth, encode case range into series
1817 /// of masks and emit bit tests with these masks.
1818 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1819 CaseRecVector& WorkList,
1821 MachineBasicBlock* Default){
1822 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1824 Case& FrontCase = *CR.Range.first;
1825 Case& BackCase = *(CR.Range.second-1);
1827 // Get the MachineFunction which holds the current MBB. This is used when
1828 // inserting any additional MBBs necessary to represent the switch.
1829 MachineFunction *CurMF = CurMBB->getParent();
1832 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1834 // Single case counts one, case range - two.
1835 numCmps += (I->Low == I->High ? 1 : 2);
1838 // Count unique destinations
1839 SmallSet<MachineBasicBlock*, 4> Dests;
1840 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1841 Dests.insert(I->BB);
1842 if (Dests.size() > 3)
1843 // Don't bother the code below, if there are too much unique destinations
1846 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1847 << "Total number of comparisons: " << numCmps << "\n";
1849 // Compute span of values.
1850 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1851 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
1852 APInt cmpRange = maxValue - minValue;
1853 /*DOUT << "Compare range: " << Range << "\n"
1854 << "Low bound: " << cast<ConstantInt>(minValue)->getValue() << "\n"
1855 << "High bound: " << cast<ConstantInt>(maxValue)->getValue() << "\n";*/
1857 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
1858 (!(Dests.size() == 1 && numCmps >= 3) &&
1859 !(Dests.size() == 2 && numCmps >= 5) &&
1860 !(Dests.size() >= 3 && numCmps >= 6)))
1863 DOUT << "Emitting bit tests\n";
1864 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1866 // Optimize the case where all the case values fit in a
1867 // word without having to subtract minValue. In this case,
1868 // we can optimize away the subtraction.
1869 if (minValue.isNonNegative() &&
1870 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1871 cmpRange = maxValue;
1873 lowBound = minValue;
1876 CaseBitsVector CasesBits;
1877 unsigned i, count = 0;
1879 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1880 MachineBasicBlock* Dest = I->BB;
1881 for (i = 0; i < count; ++i)
1882 if (Dest == CasesBits[i].BB)
1886 assert((count < 3) && "Too much destinations to test!");
1887 CasesBits.push_back(CaseBits(0, Dest, 0));
1891 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1892 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1894 uint64_t lo = (lowValue - lowBound).getZExtValue();
1895 uint64_t hi = (highValue - lowBound).getZExtValue();
1897 for (uint64_t j = lo; j <= hi; j++) {
1898 CasesBits[i].Mask |= 1ULL << j;
1899 CasesBits[i].Bits++;
1903 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1907 // Figure out which block is immediately after the current one.
1908 MachineFunction::iterator BBI = CR.CaseBB;
1911 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1914 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1915 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1916 << ", BB: " << CasesBits[i].BB << "\n";
1918 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1919 CurMF->insert(BBI, CaseBB);
1920 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1925 BitTestBlock BTB(lowBound, cmpRange, SV,
1926 -1U, (CR.CaseBB == CurMBB),
1927 CR.CaseBB, Default, BTC);
1929 if (CR.CaseBB == CurMBB)
1930 visitBitTestHeader(BTB);
1932 BitTestCases.push_back(BTB);
1938 /// Clusterify - Transform simple list of Cases into list of CaseRange's
1939 size_t SelectionDAGLowering::Clusterify(CaseVector& Cases,
1940 const SwitchInst& SI) {
1943 // Start with "simple" cases
1944 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
1945 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1946 Cases.push_back(Case(SI.getSuccessorValue(i),
1947 SI.getSuccessorValue(i),
1950 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1952 // Merge case into clusters
1953 if (Cases.size() >= 2)
1954 // Must recompute end() each iteration because it may be
1955 // invalidated by erase if we hold on to it
1956 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
1957 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
1958 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
1959 MachineBasicBlock* nextBB = J->BB;
1960 MachineBasicBlock* currentBB = I->BB;
1962 // If the two neighboring cases go to the same destination, merge them
1963 // into a single case.
1964 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
1972 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1973 if (I->Low != I->High)
1974 // A range counts double, since it requires two compares.
1981 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
1982 // Figure out which block is immediately after the current one.
1983 MachineBasicBlock *NextBlock = 0;
1984 MachineFunction::iterator BBI = CurMBB;
1986 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1988 // If there is only the default destination, branch to it if it is not the
1989 // next basic block. Otherwise, just fall through.
1990 if (SI.getNumOperands() == 2) {
1991 // Update machine-CFG edges.
1993 // If this is not a fall-through branch, emit the branch.
1994 CurMBB->addSuccessor(Default);
1995 if (Default != NextBlock)
1996 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1997 DAG.getBasicBlock(Default)));
2001 // If there are any non-default case statements, create a vector of Cases
2002 // representing each one, and sort the vector so that we can efficiently
2003 // create a binary search tree from them.
2005 size_t numCmps = Clusterify(Cases, SI);
2006 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
2007 << ". Total compares: " << numCmps << "\n";
2009 // Get the Value to be switched on and default basic blocks, which will be
2010 // inserted into CaseBlock records, representing basic blocks in the binary
2012 Value *SV = SI.getOperand(0);
2014 // Push the initial CaseRec onto the worklist
2015 CaseRecVector WorkList;
2016 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2018 while (!WorkList.empty()) {
2019 // Grab a record representing a case range to process off the worklist
2020 CaseRec CR = WorkList.back();
2021 WorkList.pop_back();
2023 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2026 // If the range has few cases (two or less) emit a series of specific
2028 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2031 // If the switch has more than 5 blocks, and at least 40% dense, and the
2032 // target supports indirect branches, then emit a jump table rather than
2033 // lowering the switch to a binary tree of conditional branches.
2034 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2037 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2038 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2039 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2044 void SelectionDAGLowering::visitSub(User &I) {
2045 // -0.0 - X --> fneg
2046 const Type *Ty = I.getType();
2047 if (isa<VectorType>(Ty)) {
2048 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2049 const VectorType *DestTy = cast<VectorType>(I.getType());
2050 const Type *ElTy = DestTy->getElementType();
2051 if (ElTy->isFloatingPoint()) {
2052 unsigned VL = DestTy->getNumElements();
2053 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2054 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2056 SDValue Op2 = getValue(I.getOperand(1));
2057 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2063 if (Ty->isFloatingPoint()) {
2064 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2065 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2066 SDValue Op2 = getValue(I.getOperand(1));
2067 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2072 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2075 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2076 SDValue Op1 = getValue(I.getOperand(0));
2077 SDValue Op2 = getValue(I.getOperand(1));
2079 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2082 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2083 SDValue Op1 = getValue(I.getOperand(0));
2084 SDValue Op2 = getValue(I.getOperand(1));
2085 if (!isa<VectorType>(I.getType())) {
2086 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2087 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2088 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2089 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2092 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2095 void SelectionDAGLowering::visitICmp(User &I) {
2096 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2097 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2098 predicate = IC->getPredicate();
2099 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2100 predicate = ICmpInst::Predicate(IC->getPredicate());
2101 SDValue Op1 = getValue(I.getOperand(0));
2102 SDValue Op2 = getValue(I.getOperand(1));
2103 ISD::CondCode Opcode = getICmpCondCode(predicate);
2104 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2107 void SelectionDAGLowering::visitFCmp(User &I) {
2108 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2109 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2110 predicate = FC->getPredicate();
2111 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2112 predicate = FCmpInst::Predicate(FC->getPredicate());
2113 SDValue Op1 = getValue(I.getOperand(0));
2114 SDValue Op2 = getValue(I.getOperand(1));
2115 ISD::CondCode Condition = getFCmpCondCode(predicate);
2116 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2119 void SelectionDAGLowering::visitVICmp(User &I) {
2120 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2121 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2122 predicate = IC->getPredicate();
2123 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2124 predicate = ICmpInst::Predicate(IC->getPredicate());
2125 SDValue Op1 = getValue(I.getOperand(0));
2126 SDValue Op2 = getValue(I.getOperand(1));
2127 ISD::CondCode Opcode = getICmpCondCode(predicate);
2128 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2131 void SelectionDAGLowering::visitVFCmp(User &I) {
2132 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2133 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2134 predicate = FC->getPredicate();
2135 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2136 predicate = FCmpInst::Predicate(FC->getPredicate());
2137 SDValue Op1 = getValue(I.getOperand(0));
2138 SDValue Op2 = getValue(I.getOperand(1));
2139 ISD::CondCode Condition = getFCmpCondCode(predicate);
2140 MVT DestVT = TLI.getValueType(I.getType());
2142 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2145 void SelectionDAGLowering::visitSelect(User &I) {
2146 SmallVector<MVT, 4> ValueVTs;
2147 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2148 unsigned NumValues = ValueVTs.size();
2149 if (NumValues != 0) {
2150 SmallVector<SDValue, 4> Values(NumValues);
2151 SDValue Cond = getValue(I.getOperand(0));
2152 SDValue TrueVal = getValue(I.getOperand(1));
2153 SDValue FalseVal = getValue(I.getOperand(2));
2155 for (unsigned i = 0; i != NumValues; ++i)
2156 Values[i] = DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2157 SDValue(TrueVal.getNode(), TrueVal.getResNo() + i),
2158 SDValue(FalseVal.getNode(), FalseVal.getResNo() + i));
2160 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2161 DAG.getVTList(&ValueVTs[0], NumValues),
2162 &Values[0], NumValues));
2167 void SelectionDAGLowering::visitTrunc(User &I) {
2168 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2169 SDValue N = getValue(I.getOperand(0));
2170 MVT DestVT = TLI.getValueType(I.getType());
2171 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2174 void SelectionDAGLowering::visitZExt(User &I) {
2175 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2176 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2177 SDValue N = getValue(I.getOperand(0));
2178 MVT DestVT = TLI.getValueType(I.getType());
2179 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2182 void SelectionDAGLowering::visitSExt(User &I) {
2183 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2184 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2185 SDValue N = getValue(I.getOperand(0));
2186 MVT DestVT = TLI.getValueType(I.getType());
2187 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2190 void SelectionDAGLowering::visitFPTrunc(User &I) {
2191 // FPTrunc is never a no-op cast, no need to check
2192 SDValue N = getValue(I.getOperand(0));
2193 MVT DestVT = TLI.getValueType(I.getType());
2194 setValue(&I, DAG.getNode(ISD::FP_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2197 void SelectionDAGLowering::visitFPExt(User &I){
2198 // FPTrunc is never a no-op cast, no need to check
2199 SDValue N = getValue(I.getOperand(0));
2200 MVT DestVT = TLI.getValueType(I.getType());
2201 setValue(&I, DAG.getNode(ISD::FP_EXTEND, DestVT, N));
2204 void SelectionDAGLowering::visitFPToUI(User &I) {
2205 // FPToUI is never a no-op cast, no need to check
2206 SDValue N = getValue(I.getOperand(0));
2207 MVT DestVT = TLI.getValueType(I.getType());
2208 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, DestVT, N));
2211 void SelectionDAGLowering::visitFPToSI(User &I) {
2212 // FPToSI is never a no-op cast, no need to check
2213 SDValue N = getValue(I.getOperand(0));
2214 MVT DestVT = TLI.getValueType(I.getType());
2215 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2218 void SelectionDAGLowering::visitUIToFP(User &I) {
2219 // UIToFP is never a no-op cast, no need to check
2220 SDValue N = getValue(I.getOperand(0));
2221 MVT DestVT = TLI.getValueType(I.getType());
2222 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2225 void SelectionDAGLowering::visitSIToFP(User &I){
2226 // SIToFP is never a no-op cast, no need to check
2227 SDValue N = getValue(I.getOperand(0));
2228 MVT DestVT = TLI.getValueType(I.getType());
2229 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2232 void SelectionDAGLowering::visitPtrToInt(User &I) {
2233 // What to do depends on the size of the integer and the size of the pointer.
2234 // We can either truncate, zero extend, or no-op, accordingly.
2235 SDValue N = getValue(I.getOperand(0));
2236 MVT SrcVT = N.getValueType();
2237 MVT DestVT = TLI.getValueType(I.getType());
2239 if (DestVT.bitsLT(SrcVT))
2240 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2242 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2243 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2244 setValue(&I, Result);
2247 void SelectionDAGLowering::visitIntToPtr(User &I) {
2248 // What to do depends on the size of the integer and the size of the pointer.
2249 // We can either truncate, zero extend, or no-op, accordingly.
2250 SDValue N = getValue(I.getOperand(0));
2251 MVT SrcVT = N.getValueType();
2252 MVT DestVT = TLI.getValueType(I.getType());
2253 if (DestVT.bitsLT(SrcVT))
2254 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2256 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2257 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2260 void SelectionDAGLowering::visitBitCast(User &I) {
2261 SDValue N = getValue(I.getOperand(0));
2262 MVT DestVT = TLI.getValueType(I.getType());
2264 // BitCast assures us that source and destination are the same size so this
2265 // is either a BIT_CONVERT or a no-op.
2266 if (DestVT != N.getValueType())
2267 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2269 setValue(&I, N); // noop cast.
2272 void SelectionDAGLowering::visitInsertElement(User &I) {
2273 SDValue InVec = getValue(I.getOperand(0));
2274 SDValue InVal = getValue(I.getOperand(1));
2275 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2276 getValue(I.getOperand(2)));
2278 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2279 TLI.getValueType(I.getType()),
2280 InVec, InVal, InIdx));
2283 void SelectionDAGLowering::visitExtractElement(User &I) {
2284 SDValue InVec = getValue(I.getOperand(0));
2285 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2286 getValue(I.getOperand(1)));
2287 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2288 TLI.getValueType(I.getType()), InVec, InIdx));
2292 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2293 // from SIndx and increasing to the element length (undefs are allowed).
2294 static bool SequentialMask(SDValue Mask, unsigned SIndx) {
2295 unsigned MaskNumElts = Mask.getNumOperands();
2296 for (unsigned i = 0; i != MaskNumElts; ++i) {
2297 if (Mask.getOperand(i).getOpcode() != ISD::UNDEF) {
2298 unsigned Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2299 if (Idx != i + SIndx)
2306 void SelectionDAGLowering::visitShuffleVector(User &I) {
2307 SDValue Src1 = getValue(I.getOperand(0));
2308 SDValue Src2 = getValue(I.getOperand(1));
2309 SDValue Mask = getValue(I.getOperand(2));
2311 MVT VT = TLI.getValueType(I.getType());
2312 MVT SrcVT = Src1.getValueType();
2313 int MaskNumElts = Mask.getNumOperands();
2314 int SrcNumElts = SrcVT.getVectorNumElements();
2316 if (SrcNumElts == MaskNumElts) {
2317 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
2321 // Normalize the shuffle vector since mask and vector length don't match.
2322 MVT MaskEltVT = Mask.getValueType().getVectorElementType();
2324 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2325 // Mask is longer than the source vectors and is a multiple of the source
2326 // vectors. We can use concatenate vector to make the mask and vectors
2328 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2329 // The shuffle is concatenating two vectors together.
2330 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, VT, Src1, Src2));
2334 // Pad both vectors with undefs to make them the same length as the mask.
2335 unsigned NumConcat = MaskNumElts / SrcNumElts;
2336 SDValue UndefVal = DAG.getNode(ISD::UNDEF, SrcVT);
2338 SDValue* MOps1 = new SDValue[NumConcat];
2339 SDValue* MOps2 = new SDValue[NumConcat];
2342 for (unsigned i = 1; i != NumConcat; ++i) {
2343 MOps1[i] = UndefVal;
2344 MOps2[i] = UndefVal;
2346 Src1 = DAG.getNode(ISD::CONCAT_VECTORS, VT, MOps1, NumConcat);
2347 Src2 = DAG.getNode(ISD::CONCAT_VECTORS, VT, MOps2, NumConcat);
2352 // Readjust mask for new input vector length.
2353 SmallVector<SDValue, 8> MappedOps;
2354 for (int i = 0; i != MaskNumElts; ++i) {
2355 if (Mask.getOperand(i).getOpcode() == ISD::UNDEF) {
2356 MappedOps.push_back(Mask.getOperand(i));
2358 int Idx = cast<ConstantSDNode>(Mask.getOperand(i))->getZExtValue();
2359 if (Idx < SrcNumElts)
2360 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2362 MappedOps.push_back(DAG.getConstant(Idx + MaskNumElts - SrcNumElts,
2366 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2367 &MappedOps[0], MappedOps.size());
2369 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
2373 if (SrcNumElts > MaskNumElts) {
2374 // Resulting vector is shorter than the incoming vector.
2375 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,0)) {
2376 // Shuffle extracts 1st vector.
2381 if (SrcNumElts == MaskNumElts && SequentialMask(Mask,MaskNumElts)) {
2382 // Shuffle extracts 2nd vector.
2387 // Analyze the access pattern of the vector to see if we can extract
2388 // two subvectors and do the shuffle. The analysis is done by calculating
2389 // the range of elements the mask access on both vectors.
2390 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2391 int MaxRange[2] = {-1, -1};
2393 for (int i = 0; i != MaskNumElts; ++i) {
2394 SDValue Arg = Mask.getOperand(i);
2395 if (Arg.getOpcode() != ISD::UNDEF) {
2396 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2397 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2399 if (Idx >= SrcNumElts) {
2403 if (Idx > MaxRange[Input])
2404 MaxRange[Input] = Idx;
2405 if (Idx < MinRange[Input])
2406 MinRange[Input] = Idx;
2410 // Check if the access is smaller than the vector size and can we find
2411 // a reasonable extract index.
2412 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
2413 int StartIdx[2]; // StartIdx to extract from
2414 for (int Input=0; Input < 2; ++Input) {
2415 if (MinRange[Input] == SrcNumElts+1 && MaxRange[Input] == -1) {
2416 RangeUse[Input] = 0; // Unused
2417 StartIdx[Input] = 0;
2418 } else if (MaxRange[Input] - MinRange[Input] < MaskNumElts) {
2419 // Fits within range but we should see if we can find a good
2420 // start index that is a multiple of the mask length.
2421 if (MaxRange[Input] < MaskNumElts) {
2422 RangeUse[Input] = 1; // Extract from beginning of the vector
2423 StartIdx[Input] = 0;
2425 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2426 if (MaxRange[Input] - StartIdx[Input] < MaskNumElts &&
2427 StartIdx[Input] + MaskNumElts < SrcNumElts)
2428 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2433 if (RangeUse[0] == 0 && RangeUse[0] == 0) {
2434 setValue(&I, DAG.getNode(ISD::UNDEF, VT)); // Vectors are not used.
2437 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2438 // Extract appropriate subvector and generate a vector shuffle
2439 for (int Input=0; Input < 2; ++Input) {
2440 SDValue& Src = Input == 0 ? Src1 : Src2;
2441 if (RangeUse[Input] == 0) {
2442 Src = DAG.getNode(ISD::UNDEF, VT);
2444 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, VT, Src,
2445 DAG.getIntPtrConstant(StartIdx[Input]));
2448 // Calculate new mask.
2449 SmallVector<SDValue, 8> MappedOps;
2450 for (int i = 0; i != MaskNumElts; ++i) {
2451 SDValue Arg = Mask.getOperand(i);
2452 if (Arg.getOpcode() == ISD::UNDEF) {
2453 MappedOps.push_back(Arg);
2455 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2456 if (Idx < SrcNumElts)
2457 MappedOps.push_back(DAG.getConstant(Idx - StartIdx[0], MaskEltVT));
2459 Idx = Idx - SrcNumElts - StartIdx[1] + MaskNumElts;
2460 MappedOps.push_back(DAG.getConstant(Idx, MaskEltVT));
2464 Mask = DAG.getNode(ISD::BUILD_VECTOR, Mask.getValueType(),
2465 &MappedOps[0], MappedOps.size());
2466 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Src1, Src2, Mask));
2471 // We can't use either concat vectors or extract subvectors so fall back to
2472 // replacing the shuffle with extract and build vector.
2473 // to insert and build vector.
2474 MVT EltVT = VT.getVectorElementType();
2475 MVT PtrVT = TLI.getPointerTy();
2476 SmallVector<SDValue,8> Ops;
2477 for (int i = 0; i != MaskNumElts; ++i) {
2478 SDValue Arg = Mask.getOperand(i);
2479 if (Arg.getOpcode() == ISD::UNDEF) {
2480 Ops.push_back(DAG.getNode(ISD::UNDEF, EltVT));
2482 assert(isa<ConstantSDNode>(Arg) && "Invalid VECTOR_SHUFFLE mask!");
2483 int Idx = cast<ConstantSDNode>(Arg)->getZExtValue();
2484 if (Idx < SrcNumElts)
2485 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Src1,
2486 DAG.getConstant(Idx, PtrVT)));
2488 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, EltVT, Src2,
2489 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
2492 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size()));
2495 void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2496 const Value *Op0 = I.getOperand(0);
2497 const Value *Op1 = I.getOperand(1);
2498 const Type *AggTy = I.getType();
2499 const Type *ValTy = Op1->getType();
2500 bool IntoUndef = isa<UndefValue>(Op0);
2501 bool FromUndef = isa<UndefValue>(Op1);
2503 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2504 I.idx_begin(), I.idx_end());
2506 SmallVector<MVT, 4> AggValueVTs;
2507 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2508 SmallVector<MVT, 4> ValValueVTs;
2509 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2511 unsigned NumAggValues = AggValueVTs.size();
2512 unsigned NumValValues = ValValueVTs.size();
2513 SmallVector<SDValue, 4> Values(NumAggValues);
2515 SDValue Agg = getValue(Op0);
2516 SDValue Val = getValue(Op1);
2518 // Copy the beginning value(s) from the original aggregate.
2519 for (; i != LinearIndex; ++i)
2520 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2521 SDValue(Agg.getNode(), Agg.getResNo() + i);
2522 // Copy values from the inserted value(s).
2523 for (; i != LinearIndex + NumValValues; ++i)
2524 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2525 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2526 // Copy remaining value(s) from the original aggregate.
2527 for (; i != NumAggValues; ++i)
2528 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2529 SDValue(Agg.getNode(), Agg.getResNo() + i);
2531 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2532 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2533 &Values[0], NumAggValues));
2536 void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2537 const Value *Op0 = I.getOperand(0);
2538 const Type *AggTy = Op0->getType();
2539 const Type *ValTy = I.getType();
2540 bool OutOfUndef = isa<UndefValue>(Op0);
2542 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2543 I.idx_begin(), I.idx_end());
2545 SmallVector<MVT, 4> ValValueVTs;
2546 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2548 unsigned NumValValues = ValValueVTs.size();
2549 SmallVector<SDValue, 4> Values(NumValValues);
2551 SDValue Agg = getValue(Op0);
2552 // Copy out the selected value(s).
2553 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2554 Values[i - LinearIndex] =
2556 DAG.getNode(ISD::UNDEF,
2557 Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2558 SDValue(Agg.getNode(), Agg.getResNo() + i);
2560 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2561 DAG.getVTList(&ValValueVTs[0], NumValValues),
2562 &Values[0], NumValValues));
2566 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2567 SDValue N = getValue(I.getOperand(0));
2568 const Type *Ty = I.getOperand(0)->getType();
2570 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2573 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2574 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2577 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2578 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2579 DAG.getIntPtrConstant(Offset));
2581 Ty = StTy->getElementType(Field);
2583 Ty = cast<SequentialType>(Ty)->getElementType();
2585 // If this is a constant subscript, handle it quickly.
2586 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2587 if (CI->getZExtValue() == 0) continue;
2589 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2590 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2591 DAG.getIntPtrConstant(Offs));
2595 // N = N + Idx * ElementSize;
2596 uint64_t ElementSize = TD->getABITypeSize(Ty);
2597 SDValue IdxN = getValue(Idx);
2599 // If the index is smaller or larger than intptr_t, truncate or extend
2601 if (IdxN.getValueType().bitsLT(N.getValueType()))
2602 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2603 else if (IdxN.getValueType().bitsGT(N.getValueType()))
2604 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2606 // If this is a multiply by a power of two, turn it into a shl
2607 // immediately. This is a very common case.
2608 if (ElementSize != 1) {
2609 if (isPowerOf2_64(ElementSize)) {
2610 unsigned Amt = Log2_64(ElementSize);
2611 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2612 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2614 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2615 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2619 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2625 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2626 // If this is a fixed sized alloca in the entry block of the function,
2627 // allocate it statically on the stack.
2628 if (FuncInfo.StaticAllocaMap.count(&I))
2629 return; // getValue will auto-populate this.
2631 const Type *Ty = I.getAllocatedType();
2632 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2634 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2637 SDValue AllocSize = getValue(I.getArraySize());
2638 MVT IntPtr = TLI.getPointerTy();
2639 if (IntPtr.bitsLT(AllocSize.getValueType()))
2640 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2641 else if (IntPtr.bitsGT(AllocSize.getValueType()))
2642 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2644 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2645 DAG.getIntPtrConstant(TySize));
2647 // Handle alignment. If the requested alignment is less than or equal to
2648 // the stack alignment, ignore it. If the size is greater than or equal to
2649 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2650 unsigned StackAlign =
2651 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2652 if (Align <= StackAlign)
2655 // Round the size of the allocation up to the stack alignment size
2656 // by add SA-1 to the size.
2657 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2658 DAG.getIntPtrConstant(StackAlign-1));
2659 // Mask out the low bits for alignment purposes.
2660 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2661 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2663 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2664 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2666 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2668 DAG.setRoot(DSA.getValue(1));
2670 // Inform the Frame Information that we have just allocated a variable-sized
2672 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2675 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2676 const Value *SV = I.getOperand(0);
2677 SDValue Ptr = getValue(SV);
2679 const Type *Ty = I.getType();
2680 bool isVolatile = I.isVolatile();
2681 unsigned Alignment = I.getAlignment();
2683 SmallVector<MVT, 4> ValueVTs;
2684 SmallVector<uint64_t, 4> Offsets;
2685 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2686 unsigned NumValues = ValueVTs.size();
2691 bool ConstantMemory = false;
2693 // Serialize volatile loads with other side effects.
2695 else if (AA->pointsToConstantMemory(SV)) {
2696 // Do not serialize (non-volatile) loads of constant memory with anything.
2697 Root = DAG.getEntryNode();
2698 ConstantMemory = true;
2700 // Do not serialize non-volatile loads against each other.
2701 Root = DAG.getRoot();
2704 SmallVector<SDValue, 4> Values(NumValues);
2705 SmallVector<SDValue, 4> Chains(NumValues);
2706 MVT PtrVT = Ptr.getValueType();
2707 for (unsigned i = 0; i != NumValues; ++i) {
2708 SDValue L = DAG.getLoad(ValueVTs[i], Root,
2709 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2710 DAG.getConstant(Offsets[i], PtrVT)),
2712 isVolatile, Alignment);
2714 Chains[i] = L.getValue(1);
2717 if (!ConstantMemory) {
2718 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2719 &Chains[0], NumValues);
2723 PendingLoads.push_back(Chain);
2726 setValue(&I, DAG.getNode(ISD::MERGE_VALUES,
2727 DAG.getVTList(&ValueVTs[0], NumValues),
2728 &Values[0], NumValues));
2732 void SelectionDAGLowering::visitStore(StoreInst &I) {
2733 Value *SrcV = I.getOperand(0);
2734 Value *PtrV = I.getOperand(1);
2736 SmallVector<MVT, 4> ValueVTs;
2737 SmallVector<uint64_t, 4> Offsets;
2738 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2739 unsigned NumValues = ValueVTs.size();
2743 // Get the lowered operands. Note that we do this after
2744 // checking if NumResults is zero, because with zero results
2745 // the operands won't have values in the map.
2746 SDValue Src = getValue(SrcV);
2747 SDValue Ptr = getValue(PtrV);
2749 SDValue Root = getRoot();
2750 SmallVector<SDValue, 4> Chains(NumValues);
2751 MVT PtrVT = Ptr.getValueType();
2752 bool isVolatile = I.isVolatile();
2753 unsigned Alignment = I.getAlignment();
2754 for (unsigned i = 0; i != NumValues; ++i)
2755 Chains[i] = DAG.getStore(Root, SDValue(Src.getNode(), Src.getResNo() + i),
2756 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2757 DAG.getConstant(Offsets[i], PtrVT)),
2759 isVolatile, Alignment);
2761 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2764 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2766 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2767 unsigned Intrinsic) {
2768 bool HasChain = !I.doesNotAccessMemory();
2769 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2771 // Build the operand list.
2772 SmallVector<SDValue, 8> Ops;
2773 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2775 // We don't need to serialize loads against other loads.
2776 Ops.push_back(DAG.getRoot());
2778 Ops.push_back(getRoot());
2782 // Info is set by getTgtMemInstrinsic
2783 TargetLowering::IntrinsicInfo Info;
2784 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2786 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
2787 if (!IsTgtIntrinsic)
2788 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2790 // Add all operands of the call to the operand list.
2791 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2792 SDValue Op = getValue(I.getOperand(i));
2793 assert(TLI.isTypeLegal(Op.getValueType()) &&
2794 "Intrinsic uses a non-legal type?");
2798 std::vector<MVT> VTs;
2799 if (I.getType() != Type::VoidTy) {
2800 MVT VT = TLI.getValueType(I.getType());
2801 if (VT.isVector()) {
2802 const VectorType *DestTy = cast<VectorType>(I.getType());
2803 MVT EltVT = TLI.getValueType(DestTy->getElementType());
2805 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2806 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2809 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2813 VTs.push_back(MVT::Other);
2815 const MVT *VTList = DAG.getNodeValueTypes(VTs);
2819 if (IsTgtIntrinsic) {
2820 // This is target intrinsic that touches memory
2821 Result = DAG.getMemIntrinsicNode(Info.opc, VTList, VTs.size(),
2822 &Ops[0], Ops.size(),
2823 Info.memVT, Info.ptrVal, Info.offset,
2824 Info.align, Info.vol,
2825 Info.readMem, Info.writeMem);
2828 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2829 &Ops[0], Ops.size());
2830 else if (I.getType() != Type::VoidTy)
2831 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2832 &Ops[0], Ops.size());
2834 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2835 &Ops[0], Ops.size());
2838 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2840 PendingLoads.push_back(Chain);
2844 if (I.getType() != Type::VoidTy) {
2845 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2846 MVT VT = TLI.getValueType(PTy);
2847 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2849 setValue(&I, Result);
2853 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2854 static GlobalVariable *ExtractTypeInfo(Value *V) {
2855 V = V->stripPointerCasts();
2856 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2857 assert ((GV || isa<ConstantPointerNull>(V)) &&
2858 "TypeInfo must be a global variable or NULL");
2864 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
2865 /// call, and add them to the specified machine basic block.
2866 void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2867 MachineBasicBlock *MBB) {
2868 // Inform the MachineModuleInfo of the personality for this landing pad.
2869 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2870 assert(CE->getOpcode() == Instruction::BitCast &&
2871 isa<Function>(CE->getOperand(0)) &&
2872 "Personality should be a function");
2873 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2875 // Gather all the type infos for this landing pad and pass them along to
2876 // MachineModuleInfo.
2877 std::vector<GlobalVariable *> TyInfo;
2878 unsigned N = I.getNumOperands();
2880 for (unsigned i = N - 1; i > 2; --i) {
2881 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2882 unsigned FilterLength = CI->getZExtValue();
2883 unsigned FirstCatch = i + FilterLength + !FilterLength;
2884 assert (FirstCatch <= N && "Invalid filter length");
2886 if (FirstCatch < N) {
2887 TyInfo.reserve(N - FirstCatch);
2888 for (unsigned j = FirstCatch; j < N; ++j)
2889 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2890 MMI->addCatchTypeInfo(MBB, TyInfo);
2894 if (!FilterLength) {
2896 MMI->addCleanup(MBB);
2899 TyInfo.reserve(FilterLength - 1);
2900 for (unsigned j = i + 1; j < FirstCatch; ++j)
2901 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2902 MMI->addFilterTypeInfo(MBB, TyInfo);
2911 TyInfo.reserve(N - 3);
2912 for (unsigned j = 3; j < N; ++j)
2913 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2914 MMI->addCatchTypeInfo(MBB, TyInfo);
2920 /// GetSignificand - Get the significand and build it into a floating-point
2921 /// number with exponent of 1:
2923 /// Op = (Op & 0x007fffff) | 0x3f800000;
2925 /// where Op is the hexidecimal representation of floating point value.
2927 GetSignificand(SelectionDAG &DAG, SDValue Op) {
2928 SDValue t1 = DAG.getNode(ISD::AND, MVT::i32, Op,
2929 DAG.getConstant(0x007fffff, MVT::i32));
2930 SDValue t2 = DAG.getNode(ISD::OR, MVT::i32, t1,
2931 DAG.getConstant(0x3f800000, MVT::i32));
2932 return DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t2);
2935 /// GetExponent - Get the exponent:
2937 /// (float)((Op1 >> 23) - 127);
2939 /// where Op is the hexidecimal representation of floating point value.
2941 GetExponent(SelectionDAG &DAG, SDValue Op) {
2942 SDValue t1 = DAG.getNode(ISD::SRL, MVT::i32, Op,
2943 DAG.getConstant(23, MVT::i32));
2944 SDValue t2 = DAG.getNode(ISD::SUB, MVT::i32, t1,
2945 DAG.getConstant(127, MVT::i32));
2946 return DAG.getNode(ISD::UINT_TO_FP, MVT::f32, t2);
2949 /// getF32Constant - Get 32-bit floating point constant.
2951 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
2952 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
2955 /// Inlined utility function to implement binary input atomic intrinsics for
2956 /// visitIntrinsicCall: I is a call instruction
2957 /// Op is the associated NodeType for I
2959 SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2960 SDValue Root = getRoot();
2962 DAG.getAtomic(Op, getValue(I.getOperand(2)).getValueType().getSimpleVT(),
2964 getValue(I.getOperand(1)),
2965 getValue(I.getOperand(2)),
2968 DAG.setRoot(L.getValue(1));
2972 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
2974 SelectionDAGLowering::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
2975 SDValue Op1 = getValue(I.getOperand(1));
2976 SDValue Op2 = getValue(I.getOperand(2));
2978 MVT ValueVTs[] = { Op1.getValueType(), MVT::i1 };
2979 SDValue Ops[] = { Op1, Op2 };
2981 SDValue Result = DAG.getNode(Op, DAG.getVTList(&ValueVTs[0], 2), &Ops[0], 2);
2983 setValue(&I, Result);
2987 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
2988 /// limited-precision mode.
2990 SelectionDAGLowering::visitExp(CallInst &I) {
2993 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2994 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
2995 SDValue Op = getValue(I.getOperand(1));
2997 // Put the exponent in the right bit position for later addition to the
3000 // #define LOG2OFe 1.4426950f
3001 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3002 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
3003 getF32Constant(DAG, 0x3fb8aa3b));
3004 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3006 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3007 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3008 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3010 // IntegerPartOfX <<= 23;
3011 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3012 DAG.getConstant(23, MVT::i32));
3014 if (LimitFloatPrecision <= 6) {
3015 // For floating-point precision of 6:
3017 // TwoToFractionalPartOfX =
3019 // (0.735607626f + 0.252464424f * x) * x;
3021 // error 0.0144103317, which is 6 bits
3022 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3023 getF32Constant(DAG, 0x3e814304));
3024 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3025 getF32Constant(DAG, 0x3f3c50c8));
3026 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3027 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3028 getF32Constant(DAG, 0x3f7f5e7e));
3029 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3031 // Add the exponent into the result in integer domain.
3032 SDValue t6 = DAG.getNode(ISD::ADD, MVT::i32,
3033 TwoToFracPartOfX, IntegerPartOfX);
3035 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t6);
3036 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3037 // For floating-point precision of 12:
3039 // TwoToFractionalPartOfX =
3042 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3044 // 0.000107046256 error, which is 13 to 14 bits
3045 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3046 getF32Constant(DAG, 0x3da235e3));
3047 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3048 getF32Constant(DAG, 0x3e65b8f3));
3049 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3050 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3051 getF32Constant(DAG, 0x3f324b07));
3052 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3053 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3054 getF32Constant(DAG, 0x3f7ff8fd));
3055 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3057 // Add the exponent into the result in integer domain.
3058 SDValue t8 = DAG.getNode(ISD::ADD, MVT::i32,
3059 TwoToFracPartOfX, IntegerPartOfX);
3061 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t8);
3062 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3063 // For floating-point precision of 18:
3065 // TwoToFractionalPartOfX =
3069 // (0.554906021e-1f +
3070 // (0.961591928e-2f +
3071 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3073 // error 2.47208000*10^(-7), which is better than 18 bits
3074 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3075 getF32Constant(DAG, 0x3924b03e));
3076 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3077 getF32Constant(DAG, 0x3ab24b87));
3078 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3079 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3080 getF32Constant(DAG, 0x3c1d8c17));
3081 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3082 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3083 getF32Constant(DAG, 0x3d634a1d));
3084 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3085 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3086 getF32Constant(DAG, 0x3e75fe14));
3087 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3088 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
3089 getF32Constant(DAG, 0x3f317234));
3090 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3091 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
3092 getF32Constant(DAG, 0x3f800000));
3093 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3095 // Add the exponent into the result in integer domain.
3096 SDValue t14 = DAG.getNode(ISD::ADD, MVT::i32,
3097 TwoToFracPartOfX, IntegerPartOfX);
3099 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, t14);
3102 // No special expansion.
3103 result = DAG.getNode(ISD::FEXP,
3104 getValue(I.getOperand(1)).getValueType(),
3105 getValue(I.getOperand(1)));
3108 setValue(&I, result);
3111 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3112 /// limited-precision mode.
3114 SelectionDAGLowering::visitLog(CallInst &I) {
3117 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3118 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3119 SDValue Op = getValue(I.getOperand(1));
3120 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3122 // Scale the exponent by log(2) [0.69314718f].
3123 SDValue Exp = GetExponent(DAG, Op1);
3124 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
3125 getF32Constant(DAG, 0x3f317218));
3127 // Get the significand and build it into a floating-point number with
3129 SDValue X = GetSignificand(DAG, Op1);
3131 if (LimitFloatPrecision <= 6) {
3132 // For floating-point precision of 6:
3136 // (1.4034025f - 0.23903021f * x) * x;
3138 // error 0.0034276066, which is better than 8 bits
3139 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3140 getF32Constant(DAG, 0xbe74c456));
3141 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3142 getF32Constant(DAG, 0x3fb3a2b1));
3143 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3144 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3145 getF32Constant(DAG, 0x3f949a29));
3147 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3148 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3149 // For floating-point precision of 12:
3155 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3157 // error 0.000061011436, which is 14 bits
3158 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3159 getF32Constant(DAG, 0xbd67b6d6));
3160 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3161 getF32Constant(DAG, 0x3ee4f4b8));
3162 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3163 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3164 getF32Constant(DAG, 0x3fbc278b));
3165 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3166 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3167 getF32Constant(DAG, 0x40348e95));
3168 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3169 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
3170 getF32Constant(DAG, 0x3fdef31a));
3172 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3173 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3174 // For floating-point precision of 18:
3182 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3184 // error 0.0000023660568, which is better than 18 bits
3185 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3186 getF32Constant(DAG, 0xbc91e5ac));
3187 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3188 getF32Constant(DAG, 0x3e4350aa));
3189 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3190 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3191 getF32Constant(DAG, 0x3f60d3e3));
3192 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3193 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3194 getF32Constant(DAG, 0x4011cdf0));
3195 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3196 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
3197 getF32Constant(DAG, 0x406cfd1c));
3198 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3199 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3200 getF32Constant(DAG, 0x408797cb));
3201 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3202 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
3203 getF32Constant(DAG, 0x4006dcab));
3205 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, LogOfMantissa);
3208 // No special expansion.
3209 result = DAG.getNode(ISD::FLOG,
3210 getValue(I.getOperand(1)).getValueType(),
3211 getValue(I.getOperand(1)));
3214 setValue(&I, result);
3217 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3218 /// limited-precision mode.
3220 SelectionDAGLowering::visitLog2(CallInst &I) {
3223 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3224 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3225 SDValue Op = getValue(I.getOperand(1));
3226 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3228 // Get the exponent.
3229 SDValue LogOfExponent = GetExponent(DAG, Op1);
3231 // Get the significand and build it into a floating-point number with
3233 SDValue X = GetSignificand(DAG, Op1);
3235 // Different possible minimax approximations of significand in
3236 // floating-point for various degrees of accuracy over [1,2].
3237 if (LimitFloatPrecision <= 6) {
3238 // For floating-point precision of 6:
3240 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3242 // error 0.0049451742, which is more than 7 bits
3243 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3244 getF32Constant(DAG, 0xbeb08fe0));
3245 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3246 getF32Constant(DAG, 0x40019463));
3247 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3248 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3249 getF32Constant(DAG, 0x3fd6633d));
3251 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3252 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3253 // For floating-point precision of 12:
3259 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3261 // error 0.0000876136000, which is better than 13 bits
3262 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3263 getF32Constant(DAG, 0xbda7262e));
3264 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3265 getF32Constant(DAG, 0x3f25280b));
3266 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3267 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3268 getF32Constant(DAG, 0x4007b923));
3269 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3270 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3271 getF32Constant(DAG, 0x40823e2f));
3272 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3273 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t6,
3274 getF32Constant(DAG, 0x4020d29c));
3276 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3277 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3278 // For floating-point precision of 18:
3287 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3289 // error 0.0000018516, which is better than 18 bits
3290 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3291 getF32Constant(DAG, 0xbcd2769e));
3292 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3293 getF32Constant(DAG, 0x3e8ce0b9));
3294 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3295 SDValue t3 = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3296 getF32Constant(DAG, 0x3fa22ae7));
3297 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3298 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3299 getF32Constant(DAG, 0x40525723));
3300 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3301 SDValue t7 = DAG.getNode(ISD::FSUB, MVT::f32, t6,
3302 getF32Constant(DAG, 0x40aaf200));
3303 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3304 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3305 getF32Constant(DAG, 0x40c39dad));
3306 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3307 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t10,
3308 getF32Constant(DAG, 0x4042902c));
3310 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log2ofMantissa);
3313 // No special expansion.
3314 result = DAG.getNode(ISD::FLOG2,
3315 getValue(I.getOperand(1)).getValueType(),
3316 getValue(I.getOperand(1)));
3319 setValue(&I, result);
3322 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3323 /// limited-precision mode.
3325 SelectionDAGLowering::visitLog10(CallInst &I) {
3328 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3329 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3330 SDValue Op = getValue(I.getOperand(1));
3331 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, Op);
3333 // Scale the exponent by log10(2) [0.30102999f].
3334 SDValue Exp = GetExponent(DAG, Op1);
3335 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, MVT::f32, Exp,
3336 getF32Constant(DAG, 0x3e9a209a));
3338 // Get the significand and build it into a floating-point number with
3340 SDValue X = GetSignificand(DAG, Op1);
3342 if (LimitFloatPrecision <= 6) {
3343 // For floating-point precision of 6:
3345 // Log10ofMantissa =
3347 // (0.60948995f - 0.10380950f * x) * x;
3349 // error 0.0014886165, which is 6 bits
3350 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3351 getF32Constant(DAG, 0xbdd49a13));
3352 SDValue t1 = DAG.getNode(ISD::FADD, MVT::f32, t0,
3353 getF32Constant(DAG, 0x3f1c0789));
3354 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3355 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t2,
3356 getF32Constant(DAG, 0x3f011300));
3358 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3359 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3360 // For floating-point precision of 12:
3362 // Log10ofMantissa =
3365 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3367 // error 0.00019228036, which is better than 12 bits
3368 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3369 getF32Constant(DAG, 0x3d431f31));
3370 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
3371 getF32Constant(DAG, 0x3ea21fb2));
3372 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3373 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3374 getF32Constant(DAG, 0x3f6ae232));
3375 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3376 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t4,
3377 getF32Constant(DAG, 0x3f25f7c3));
3379 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3380 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3381 // For floating-point precision of 18:
3383 // Log10ofMantissa =
3388 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3390 // error 0.0000037995730, which is better than 18 bits
3391 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3392 getF32Constant(DAG, 0x3c5d51ce));
3393 SDValue t1 = DAG.getNode(ISD::FSUB, MVT::f32, t0,
3394 getF32Constant(DAG, 0x3e00685a));
3395 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, t1, X);
3396 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3397 getF32Constant(DAG, 0x3efb6798));
3398 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3399 SDValue t5 = DAG.getNode(ISD::FSUB, MVT::f32, t4,
3400 getF32Constant(DAG, 0x3f88d192));
3401 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3402 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3403 getF32Constant(DAG, 0x3fc4316c));
3404 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3405 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, MVT::f32, t8,
3406 getF32Constant(DAG, 0x3f57ce70));
3408 result = DAG.getNode(ISD::FADD, MVT::f32, LogOfExponent, Log10ofMantissa);
3411 // No special expansion.
3412 result = DAG.getNode(ISD::FLOG10,
3413 getValue(I.getOperand(1)).getValueType(),
3414 getValue(I.getOperand(1)));
3417 setValue(&I, result);
3420 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3421 /// limited-precision mode.
3423 SelectionDAGLowering::visitExp2(CallInst &I) {
3426 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3427 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3428 SDValue Op = getValue(I.getOperand(1));
3430 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, Op);
3432 // FractionalPartOfX = x - (float)IntegerPartOfX;
3433 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3434 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, Op, t1);
3436 // IntegerPartOfX <<= 23;
3437 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3438 DAG.getConstant(23, MVT::i32));
3440 if (LimitFloatPrecision <= 6) {
3441 // For floating-point precision of 6:
3443 // TwoToFractionalPartOfX =
3445 // (0.735607626f + 0.252464424f * x) * x;
3447 // error 0.0144103317, which is 6 bits
3448 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3449 getF32Constant(DAG, 0x3e814304));
3450 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3451 getF32Constant(DAG, 0x3f3c50c8));
3452 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3453 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3454 getF32Constant(DAG, 0x3f7f5e7e));
3455 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3456 SDValue TwoToFractionalPartOfX =
3457 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3459 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3460 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3461 // For floating-point precision of 12:
3463 // TwoToFractionalPartOfX =
3466 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3468 // error 0.000107046256, which is 13 to 14 bits
3469 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3470 getF32Constant(DAG, 0x3da235e3));
3471 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3472 getF32Constant(DAG, 0x3e65b8f3));
3473 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3474 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3475 getF32Constant(DAG, 0x3f324b07));
3476 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3477 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3478 getF32Constant(DAG, 0x3f7ff8fd));
3479 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3480 SDValue TwoToFractionalPartOfX =
3481 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3483 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3484 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3485 // For floating-point precision of 18:
3487 // TwoToFractionalPartOfX =
3491 // (0.554906021e-1f +
3492 // (0.961591928e-2f +
3493 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3494 // error 2.47208000*10^(-7), which is better than 18 bits
3495 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3496 getF32Constant(DAG, 0x3924b03e));
3497 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3498 getF32Constant(DAG, 0x3ab24b87));
3499 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3500 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3501 getF32Constant(DAG, 0x3c1d8c17));
3502 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3503 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3504 getF32Constant(DAG, 0x3d634a1d));
3505 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3506 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3507 getF32Constant(DAG, 0x3e75fe14));
3508 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3509 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
3510 getF32Constant(DAG, 0x3f317234));
3511 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3512 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
3513 getF32Constant(DAG, 0x3f800000));
3514 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3515 SDValue TwoToFractionalPartOfX =
3516 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3518 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3521 // No special expansion.
3522 result = DAG.getNode(ISD::FEXP2,
3523 getValue(I.getOperand(1)).getValueType(),
3524 getValue(I.getOperand(1)));
3527 setValue(&I, result);
3530 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3531 /// limited-precision mode with x == 10.0f.
3533 SelectionDAGLowering::visitPow(CallInst &I) {
3535 Value *Val = I.getOperand(1);
3536 bool IsExp10 = false;
3538 if (getValue(Val).getValueType() == MVT::f32 &&
3539 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
3540 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3541 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3542 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3544 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3549 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3550 SDValue Op = getValue(I.getOperand(2));
3552 // Put the exponent in the right bit position for later addition to the
3555 // #define LOG2OF10 3.3219281f
3556 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3557 SDValue t0 = DAG.getNode(ISD::FMUL, MVT::f32, Op,
3558 getF32Constant(DAG, 0x40549a78));
3559 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, MVT::i32, t0);
3561 // FractionalPartOfX = x - (float)IntegerPartOfX;
3562 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, MVT::f32, IntegerPartOfX);
3563 SDValue X = DAG.getNode(ISD::FSUB, MVT::f32, t0, t1);
3565 // IntegerPartOfX <<= 23;
3566 IntegerPartOfX = DAG.getNode(ISD::SHL, MVT::i32, IntegerPartOfX,
3567 DAG.getConstant(23, MVT::i32));
3569 if (LimitFloatPrecision <= 6) {
3570 // For floating-point precision of 6:
3572 // twoToFractionalPartOfX =
3574 // (0.735607626f + 0.252464424f * x) * x;
3576 // error 0.0144103317, which is 6 bits
3577 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3578 getF32Constant(DAG, 0x3e814304));
3579 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3580 getF32Constant(DAG, 0x3f3c50c8));
3581 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3582 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3583 getF32Constant(DAG, 0x3f7f5e7e));
3584 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t5);
3585 SDValue TwoToFractionalPartOfX =
3586 DAG.getNode(ISD::ADD, MVT::i32, t6, IntegerPartOfX);
3588 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3589 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3590 // For floating-point precision of 12:
3592 // TwoToFractionalPartOfX =
3595 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3597 // error 0.000107046256, which is 13 to 14 bits
3598 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3599 getF32Constant(DAG, 0x3da235e3));
3600 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3601 getF32Constant(DAG, 0x3e65b8f3));
3602 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3603 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3604 getF32Constant(DAG, 0x3f324b07));
3605 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3606 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3607 getF32Constant(DAG, 0x3f7ff8fd));
3608 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t7);
3609 SDValue TwoToFractionalPartOfX =
3610 DAG.getNode(ISD::ADD, MVT::i32, t8, IntegerPartOfX);
3612 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3613 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3614 // For floating-point precision of 18:
3616 // TwoToFractionalPartOfX =
3620 // (0.554906021e-1f +
3621 // (0.961591928e-2f +
3622 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3623 // error 2.47208000*10^(-7), which is better than 18 bits
3624 SDValue t2 = DAG.getNode(ISD::FMUL, MVT::f32, X,
3625 getF32Constant(DAG, 0x3924b03e));
3626 SDValue t3 = DAG.getNode(ISD::FADD, MVT::f32, t2,
3627 getF32Constant(DAG, 0x3ab24b87));
3628 SDValue t4 = DAG.getNode(ISD::FMUL, MVT::f32, t3, X);
3629 SDValue t5 = DAG.getNode(ISD::FADD, MVT::f32, t4,
3630 getF32Constant(DAG, 0x3c1d8c17));
3631 SDValue t6 = DAG.getNode(ISD::FMUL, MVT::f32, t5, X);
3632 SDValue t7 = DAG.getNode(ISD::FADD, MVT::f32, t6,
3633 getF32Constant(DAG, 0x3d634a1d));
3634 SDValue t8 = DAG.getNode(ISD::FMUL, MVT::f32, t7, X);
3635 SDValue t9 = DAG.getNode(ISD::FADD, MVT::f32, t8,
3636 getF32Constant(DAG, 0x3e75fe14));
3637 SDValue t10 = DAG.getNode(ISD::FMUL, MVT::f32, t9, X);
3638 SDValue t11 = DAG.getNode(ISD::FADD, MVT::f32, t10,
3639 getF32Constant(DAG, 0x3f317234));
3640 SDValue t12 = DAG.getNode(ISD::FMUL, MVT::f32, t11, X);
3641 SDValue t13 = DAG.getNode(ISD::FADD, MVT::f32, t12,
3642 getF32Constant(DAG, 0x3f800000));
3643 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, MVT::i32, t13);
3644 SDValue TwoToFractionalPartOfX =
3645 DAG.getNode(ISD::ADD, MVT::i32, t14, IntegerPartOfX);
3647 result = DAG.getNode(ISD::BIT_CONVERT, MVT::f32, TwoToFractionalPartOfX);
3650 // No special expansion.
3651 result = DAG.getNode(ISD::FPOW,
3652 getValue(I.getOperand(1)).getValueType(),
3653 getValue(I.getOperand(1)),
3654 getValue(I.getOperand(2)));
3657 setValue(&I, result);
3660 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3661 /// we want to emit this as a call to a named external function, return the name
3662 /// otherwise lower it and return null.
3664 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3665 switch (Intrinsic) {
3667 // By default, turn this into a target intrinsic node.
3668 visitTargetIntrinsic(I, Intrinsic);
3670 case Intrinsic::vastart: visitVAStart(I); return 0;
3671 case Intrinsic::vaend: visitVAEnd(I); return 0;
3672 case Intrinsic::vacopy: visitVACopy(I); return 0;
3673 case Intrinsic::returnaddress:
3674 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
3675 getValue(I.getOperand(1))));
3677 case Intrinsic::frameaddress:
3678 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
3679 getValue(I.getOperand(1))));
3681 case Intrinsic::setjmp:
3682 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3684 case Intrinsic::longjmp:
3685 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3687 case Intrinsic::memcpy: {
3688 SDValue Op1 = getValue(I.getOperand(1));
3689 SDValue Op2 = getValue(I.getOperand(2));
3690 SDValue Op3 = getValue(I.getOperand(3));
3691 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3692 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3693 I.getOperand(1), 0, I.getOperand(2), 0));
3696 case Intrinsic::memset: {
3697 SDValue Op1 = getValue(I.getOperand(1));
3698 SDValue Op2 = getValue(I.getOperand(2));
3699 SDValue Op3 = getValue(I.getOperand(3));
3700 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3701 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
3702 I.getOperand(1), 0));
3705 case Intrinsic::memmove: {
3706 SDValue Op1 = getValue(I.getOperand(1));
3707 SDValue Op2 = getValue(I.getOperand(2));
3708 SDValue Op3 = getValue(I.getOperand(3));
3709 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3711 // If the source and destination are known to not be aliases, we can
3712 // lower memmove as memcpy.
3713 uint64_t Size = -1ULL;
3714 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3715 Size = C->getZExtValue();
3716 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3717 AliasAnalysis::NoAlias) {
3718 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
3719 I.getOperand(1), 0, I.getOperand(2), 0));
3723 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
3724 I.getOperand(1), 0, I.getOperand(2), 0));
3727 case Intrinsic::dbg_stoppoint: {
3728 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3729 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
3730 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
3731 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
3732 assert(DD && "Not a debug information descriptor");
3733 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
3736 cast<CompileUnitDesc>(DD)));
3741 case Intrinsic::dbg_region_start: {
3742 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3743 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
3744 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
3745 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
3746 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3751 case Intrinsic::dbg_region_end: {
3752 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3753 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
3754 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
3755 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
3756 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3761 case Intrinsic::dbg_func_start: {
3762 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3764 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
3765 Value *SP = FSI.getSubprogram();
3766 if (SP && MMI->Verify(SP)) {
3767 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
3768 // what (most?) gdb expects.
3769 DebugInfoDesc *DD = MMI->getDescFor(SP);
3770 assert(DD && "Not a debug information descriptor");
3771 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
3772 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
3773 unsigned SrcFile = MMI->RecordSource(CompileUnit);
3774 // Record the source line but does not create a label for the normal
3775 // function start. It will be emitted at asm emission time. However,
3776 // create a label if this is a beginning of inlined function.
3777 unsigned LabelID = MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
3778 if (MMI->getSourceLines().size() != 1)
3779 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
3784 case Intrinsic::dbg_declare: {
3785 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3786 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3787 Value *Variable = DI.getVariable();
3788 if (MMI && Variable && MMI->Verify(Variable))
3789 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
3790 getValue(DI.getAddress()), getValue(Variable)));
3794 case Intrinsic::eh_exception: {
3795 if (!CurMBB->isLandingPad()) {
3796 // FIXME: Mark exception register as live in. Hack for PR1508.
3797 unsigned Reg = TLI.getExceptionAddressRegister();
3798 if (Reg) CurMBB->addLiveIn(Reg);
3800 // Insert the EXCEPTIONADDR instruction.
3801 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3803 Ops[0] = DAG.getRoot();
3804 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
3806 DAG.setRoot(Op.getValue(1));
3810 case Intrinsic::eh_selector_i32:
3811 case Intrinsic::eh_selector_i64: {
3812 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3813 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
3814 MVT::i32 : MVT::i64);
3817 if (CurMBB->isLandingPad())
3818 AddCatchInfo(I, MMI, CurMBB);
3821 FuncInfo.CatchInfoLost.insert(&I);
3823 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3824 unsigned Reg = TLI.getExceptionSelectorRegister();
3825 if (Reg) CurMBB->addLiveIn(Reg);
3828 // Insert the EHSELECTION instruction.
3829 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
3831 Ops[0] = getValue(I.getOperand(1));
3833 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
3835 DAG.setRoot(Op.getValue(1));
3837 setValue(&I, DAG.getConstant(0, VT));
3843 case Intrinsic::eh_typeid_for_i32:
3844 case Intrinsic::eh_typeid_for_i64: {
3845 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3846 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
3847 MVT::i32 : MVT::i64);
3850 // Find the type id for the given typeinfo.
3851 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3853 unsigned TypeID = MMI->getTypeIDFor(GV);
3854 setValue(&I, DAG.getConstant(TypeID, VT));
3856 // Return something different to eh_selector.
3857 setValue(&I, DAG.getConstant(1, VT));
3863 case Intrinsic::eh_return_i32:
3864 case Intrinsic::eh_return_i64:
3865 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3866 MMI->setCallsEHReturn(true);
3867 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
3870 getValue(I.getOperand(1)),
3871 getValue(I.getOperand(2))));
3873 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3877 case Intrinsic::eh_unwind_init:
3878 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3879 MMI->setCallsUnwindInit(true);
3884 case Intrinsic::eh_dwarf_cfa: {
3885 MVT VT = getValue(I.getOperand(1)).getValueType();
3887 if (VT.bitsGT(TLI.getPointerTy()))
3888 CfaArg = DAG.getNode(ISD::TRUNCATE,
3889 TLI.getPointerTy(), getValue(I.getOperand(1)));
3891 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
3892 TLI.getPointerTy(), getValue(I.getOperand(1)));
3894 SDValue Offset = DAG.getNode(ISD::ADD,
3896 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
3897 TLI.getPointerTy()),
3899 setValue(&I, DAG.getNode(ISD::ADD,
3901 DAG.getNode(ISD::FRAMEADDR,
3904 TLI.getPointerTy())),
3909 case Intrinsic::convertff:
3910 case Intrinsic::convertfsi:
3911 case Intrinsic::convertfui:
3912 case Intrinsic::convertsif:
3913 case Intrinsic::convertuif:
3914 case Intrinsic::convertss:
3915 case Intrinsic::convertsu:
3916 case Intrinsic::convertus:
3917 case Intrinsic::convertuu: {
3918 ISD::CvtCode Code = ISD::CVT_INVALID;
3919 switch (Intrinsic) {
3920 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
3921 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
3922 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
3923 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
3924 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
3925 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
3926 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
3927 case Intrinsic::convertus: Code = ISD::CVT_US; break;
3928 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
3930 MVT DestVT = TLI.getValueType(I.getType());
3931 Value* Op1 = I.getOperand(1);
3932 setValue(&I, DAG.getConvertRndSat(DestVT, getValue(Op1),
3933 DAG.getValueType(DestVT),
3934 DAG.getValueType(getValue(Op1).getValueType()),
3935 getValue(I.getOperand(2)),
3936 getValue(I.getOperand(3)),
3941 case Intrinsic::sqrt:
3942 setValue(&I, DAG.getNode(ISD::FSQRT,
3943 getValue(I.getOperand(1)).getValueType(),
3944 getValue(I.getOperand(1))));
3946 case Intrinsic::powi:
3947 setValue(&I, DAG.getNode(ISD::FPOWI,
3948 getValue(I.getOperand(1)).getValueType(),
3949 getValue(I.getOperand(1)),
3950 getValue(I.getOperand(2))));
3952 case Intrinsic::sin:
3953 setValue(&I, DAG.getNode(ISD::FSIN,
3954 getValue(I.getOperand(1)).getValueType(),
3955 getValue(I.getOperand(1))));
3957 case Intrinsic::cos:
3958 setValue(&I, DAG.getNode(ISD::FCOS,
3959 getValue(I.getOperand(1)).getValueType(),
3960 getValue(I.getOperand(1))));
3962 case Intrinsic::log:
3965 case Intrinsic::log2:
3968 case Intrinsic::log10:
3971 case Intrinsic::exp:
3974 case Intrinsic::exp2:
3977 case Intrinsic::pow:
3980 case Intrinsic::pcmarker: {
3981 SDValue Tmp = getValue(I.getOperand(1));
3982 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3985 case Intrinsic::readcyclecounter: {
3986 SDValue Op = getRoot();
3987 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3988 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3991 DAG.setRoot(Tmp.getValue(1));
3994 case Intrinsic::part_select: {
3995 // Currently not implemented: just abort
3996 assert(0 && "part_select intrinsic not implemented");
3999 case Intrinsic::part_set: {
4000 // Currently not implemented: just abort
4001 assert(0 && "part_set intrinsic not implemented");
4004 case Intrinsic::bswap:
4005 setValue(&I, DAG.getNode(ISD::BSWAP,
4006 getValue(I.getOperand(1)).getValueType(),
4007 getValue(I.getOperand(1))));
4009 case Intrinsic::cttz: {
4010 SDValue Arg = getValue(I.getOperand(1));
4011 MVT Ty = Arg.getValueType();
4012 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
4013 setValue(&I, result);
4016 case Intrinsic::ctlz: {
4017 SDValue Arg = getValue(I.getOperand(1));
4018 MVT Ty = Arg.getValueType();
4019 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
4020 setValue(&I, result);
4023 case Intrinsic::ctpop: {
4024 SDValue Arg = getValue(I.getOperand(1));
4025 MVT Ty = Arg.getValueType();
4026 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
4027 setValue(&I, result);
4030 case Intrinsic::stacksave: {
4031 SDValue Op = getRoot();
4032 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
4033 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
4035 DAG.setRoot(Tmp.getValue(1));
4038 case Intrinsic::stackrestore: {
4039 SDValue Tmp = getValue(I.getOperand(1));
4040 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
4043 case Intrinsic::stackprotector: {
4044 // Emit code into the DAG to store the stack guard onto the stack.
4045 MachineFunction &MF = DAG.getMachineFunction();
4046 MachineFrameInfo *MFI = MF.getFrameInfo();
4047 MVT PtrTy = TLI.getPointerTy();
4049 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4050 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
4052 int FI = FuncInfo.StaticAllocaMap[Slot];
4053 MFI->setStackProtectorIndex(FI);
4055 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4057 // Store the stack protector onto the stack.
4058 SDValue Result = DAG.getStore(getRoot(), Src, FIN,
4059 PseudoSourceValue::getFixedStack(FI),
4061 setValue(&I, Result);
4062 DAG.setRoot(Result);
4065 case Intrinsic::var_annotation:
4066 // Discard annotate attributes
4069 case Intrinsic::init_trampoline: {
4070 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4074 Ops[1] = getValue(I.getOperand(1));
4075 Ops[2] = getValue(I.getOperand(2));
4076 Ops[3] = getValue(I.getOperand(3));
4077 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4078 Ops[5] = DAG.getSrcValue(F);
4080 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
4081 DAG.getNodeValueTypes(TLI.getPointerTy(),
4086 DAG.setRoot(Tmp.getValue(1));
4090 case Intrinsic::gcroot:
4092 Value *Alloca = I.getOperand(1);
4093 Constant *TypeMap = cast<Constant>(I.getOperand(2));
4095 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4096 GFI->addStackRoot(FI->getIndex(), TypeMap);
4100 case Intrinsic::gcread:
4101 case Intrinsic::gcwrite:
4102 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
4105 case Intrinsic::flt_rounds: {
4106 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
4110 case Intrinsic::trap: {
4111 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
4115 case Intrinsic::uadd_with_overflow:
4116 return implVisitAluOverflow(I, ISD::UADDO);
4117 case Intrinsic::sadd_with_overflow:
4118 return implVisitAluOverflow(I, ISD::SADDO);
4119 case Intrinsic::usub_with_overflow:
4120 return implVisitAluOverflow(I, ISD::USUBO);
4121 case Intrinsic::ssub_with_overflow:
4122 return implVisitAluOverflow(I, ISD::SSUBO);
4123 case Intrinsic::umul_with_overflow:
4124 return implVisitAluOverflow(I, ISD::UMULO);
4125 case Intrinsic::smul_with_overflow:
4126 return implVisitAluOverflow(I, ISD::SMULO);
4128 case Intrinsic::prefetch: {
4131 Ops[1] = getValue(I.getOperand(1));
4132 Ops[2] = getValue(I.getOperand(2));
4133 Ops[3] = getValue(I.getOperand(3));
4134 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
4138 case Intrinsic::memory_barrier: {
4141 for (int x = 1; x < 6; ++x)
4142 Ops[x] = getValue(I.getOperand(x));
4144 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
4147 case Intrinsic::atomic_cmp_swap: {
4148 SDValue Root = getRoot();
4150 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP,
4151 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4153 getValue(I.getOperand(1)),
4154 getValue(I.getOperand(2)),
4155 getValue(I.getOperand(3)),
4158 DAG.setRoot(L.getValue(1));
4161 case Intrinsic::atomic_load_add:
4162 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4163 case Intrinsic::atomic_load_sub:
4164 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4165 case Intrinsic::atomic_load_or:
4166 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4167 case Intrinsic::atomic_load_xor:
4168 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4169 case Intrinsic::atomic_load_and:
4170 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4171 case Intrinsic::atomic_load_nand:
4172 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4173 case Intrinsic::atomic_load_max:
4174 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4175 case Intrinsic::atomic_load_min:
4176 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4177 case Intrinsic::atomic_load_umin:
4178 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4179 case Intrinsic::atomic_load_umax:
4180 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4181 case Intrinsic::atomic_swap:
4182 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4187 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
4189 MachineBasicBlock *LandingPad) {
4190 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4191 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4192 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4193 unsigned BeginLabel = 0, EndLabel = 0;
4195 TargetLowering::ArgListTy Args;
4196 TargetLowering::ArgListEntry Entry;
4197 Args.reserve(CS.arg_size());
4198 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4200 SDValue ArgNode = getValue(*i);
4201 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4203 unsigned attrInd = i - CS.arg_begin() + 1;
4204 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4205 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4206 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4207 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4208 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4209 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4210 Entry.Alignment = CS.getParamAlignment(attrInd);
4211 Args.push_back(Entry);
4214 if (LandingPad && MMI) {
4215 // Insert a label before the invoke call to mark the try range. This can be
4216 // used to detect deletion of the invoke via the MachineModuleInfo.
4217 BeginLabel = MMI->NextLabelID();
4218 // Both PendingLoads and PendingExports must be flushed here;
4219 // this call might not return.
4221 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
4224 std::pair<SDValue,SDValue> Result =
4225 TLI.LowerCallTo(getRoot(), CS.getType(),
4226 CS.paramHasAttr(0, Attribute::SExt),
4227 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4228 CS.paramHasAttr(0, Attribute::InReg),
4229 CS.getCallingConv(),
4230 IsTailCall && PerformTailCallOpt,
4232 if (CS.getType() != Type::VoidTy)
4233 setValue(CS.getInstruction(), Result.first);
4234 DAG.setRoot(Result.second);
4236 if (LandingPad && MMI) {
4237 // Insert a label at the end of the invoke call to mark the try range. This
4238 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4239 EndLabel = MMI->NextLabelID();
4240 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
4242 // Inform MachineModuleInfo of range.
4243 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4248 void SelectionDAGLowering::visitCall(CallInst &I) {
4249 const char *RenameFn = 0;
4250 if (Function *F = I.getCalledFunction()) {
4251 if (F->isDeclaration()) {
4252 if (unsigned IID = F->getIntrinsicID()) {
4253 RenameFn = visitIntrinsicCall(I, IID);
4259 // Check for well-known libc/libm calls. If the function is internal, it
4260 // can't be a library call.
4261 unsigned NameLen = F->getNameLen();
4262 if (!F->hasInternalLinkage() && NameLen) {
4263 const char *NameStr = F->getNameStart();
4264 if (NameStr[0] == 'c' &&
4265 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
4266 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
4267 if (I.getNumOperands() == 3 && // Basic sanity checks.
4268 I.getOperand(1)->getType()->isFloatingPoint() &&
4269 I.getType() == I.getOperand(1)->getType() &&
4270 I.getType() == I.getOperand(2)->getType()) {
4271 SDValue LHS = getValue(I.getOperand(1));
4272 SDValue RHS = getValue(I.getOperand(2));
4273 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
4277 } else if (NameStr[0] == 'f' &&
4278 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
4279 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
4280 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
4281 if (I.getNumOperands() == 2 && // Basic sanity checks.
4282 I.getOperand(1)->getType()->isFloatingPoint() &&
4283 I.getType() == I.getOperand(1)->getType()) {
4284 SDValue Tmp = getValue(I.getOperand(1));
4285 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
4288 } else if (NameStr[0] == 's' &&
4289 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
4290 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
4291 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
4292 if (I.getNumOperands() == 2 && // Basic sanity checks.
4293 I.getOperand(1)->getType()->isFloatingPoint() &&
4294 I.getType() == I.getOperand(1)->getType()) {
4295 SDValue Tmp = getValue(I.getOperand(1));
4296 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
4299 } else if (NameStr[0] == 'c' &&
4300 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
4301 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
4302 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
4303 if (I.getNumOperands() == 2 && // Basic sanity checks.
4304 I.getOperand(1)->getType()->isFloatingPoint() &&
4305 I.getType() == I.getOperand(1)->getType()) {
4306 SDValue Tmp = getValue(I.getOperand(1));
4307 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
4312 } else if (isa<InlineAsm>(I.getOperand(0))) {
4319 Callee = getValue(I.getOperand(0));
4321 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
4323 LowerCallTo(&I, Callee, I.isTailCall());
4327 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4328 /// this value and returns the result as a ValueVT value. This uses
4329 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4330 /// If the Flag pointer is NULL, no flag is used.
4331 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
4333 SDValue *Flag) const {
4334 // Assemble the legal parts into the final values.
4335 SmallVector<SDValue, 4> Values(ValueVTs.size());
4336 SmallVector<SDValue, 8> Parts;
4337 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4338 // Copy the legal parts from the registers.
4339 MVT ValueVT = ValueVTs[Value];
4340 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
4341 MVT RegisterVT = RegVTs[Value];
4343 Parts.resize(NumRegs);
4344 for (unsigned i = 0; i != NumRegs; ++i) {
4347 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
4349 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
4350 *Flag = P.getValue(2);
4352 Chain = P.getValue(1);
4354 // If the source register was virtual and if we know something about it,
4355 // add an assert node.
4356 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4357 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4358 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4359 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4360 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4361 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4363 unsigned RegSize = RegisterVT.getSizeInBits();
4364 unsigned NumSignBits = LOI.NumSignBits;
4365 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4367 // FIXME: We capture more information than the dag can represent. For
4368 // now, just use the tightest assertzext/assertsext possible.
4370 MVT FromVT(MVT::Other);
4371 if (NumSignBits == RegSize)
4372 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4373 else if (NumZeroBits >= RegSize-1)
4374 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4375 else if (NumSignBits > RegSize-8)
4376 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4377 else if (NumZeroBits >= RegSize-9)
4378 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4379 else if (NumSignBits > RegSize-16)
4380 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
4381 else if (NumZeroBits >= RegSize-17)
4382 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
4383 else if (NumSignBits > RegSize-32)
4384 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
4385 else if (NumZeroBits >= RegSize-33)
4386 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
4388 if (FromVT != MVT::Other) {
4389 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
4390 RegisterVT, P, DAG.getValueType(FromVT));
4399 Values[Value] = getCopyFromParts(DAG, Parts.begin(), NumRegs, RegisterVT,
4405 return DAG.getNode(ISD::MERGE_VALUES,
4406 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4407 &Values[0], ValueVTs.size());
4410 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4411 /// specified value into the registers specified by this object. This uses
4412 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4413 /// If the Flag pointer is NULL, no flag is used.
4414 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
4415 SDValue &Chain, SDValue *Flag) const {
4416 // Get the list of the values's legal parts.
4417 unsigned NumRegs = Regs.size();
4418 SmallVector<SDValue, 8> Parts(NumRegs);
4419 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4420 MVT ValueVT = ValueVTs[Value];
4421 unsigned NumParts = TLI->getNumRegisters(ValueVT);
4422 MVT RegisterVT = RegVTs[Value];
4424 getCopyToParts(DAG, Val.getValue(Val.getResNo() + Value),
4425 &Parts[Part], NumParts, RegisterVT);
4429 // Copy the parts into the registers.
4430 SmallVector<SDValue, 8> Chains(NumRegs);
4431 for (unsigned i = 0; i != NumRegs; ++i) {
4434 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
4436 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
4437 *Flag = Part.getValue(1);
4439 Chains[i] = Part.getValue(0);
4442 if (NumRegs == 1 || Flag)
4443 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4444 // flagged to it. That is the CopyToReg nodes and the user are considered
4445 // a single scheduling unit. If we create a TokenFactor and return it as
4446 // chain, then the TokenFactor is both a predecessor (operand) of the
4447 // user as well as a successor (the TF operands are flagged to the user).
4448 // c1, f1 = CopyToReg
4449 // c2, f2 = CopyToReg
4450 // c3 = TokenFactor c1, c2
4453 Chain = Chains[NumRegs-1];
4455 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
4458 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
4459 /// operand list. This adds the code marker and includes the number of
4460 /// values added into it.
4461 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
4462 std::vector<SDValue> &Ops) const {
4463 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4464 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
4465 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4466 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
4467 MVT RegisterVT = RegVTs[Value];
4468 for (unsigned i = 0; i != NumRegs; ++i) {
4469 assert(Reg < Regs.size() && "Mismatch in # registers expected");
4470 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
4475 /// isAllocatableRegister - If the specified register is safe to allocate,
4476 /// i.e. it isn't a stack pointer or some other special register, return the
4477 /// register class for the register. Otherwise, return null.
4478 static const TargetRegisterClass *
4479 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4480 const TargetLowering &TLI,
4481 const TargetRegisterInfo *TRI) {
4482 MVT FoundVT = MVT::Other;
4483 const TargetRegisterClass *FoundRC = 0;
4484 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4485 E = TRI->regclass_end(); RCI != E; ++RCI) {
4486 MVT ThisVT = MVT::Other;
4488 const TargetRegisterClass *RC = *RCI;
4489 // If none of the the value types for this register class are valid, we
4490 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4491 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4493 if (TLI.isTypeLegal(*I)) {
4494 // If we have already found this register in a different register class,
4495 // choose the one with the largest VT specified. For example, on
4496 // PowerPC, we favor f64 register classes over f32.
4497 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4504 if (ThisVT == MVT::Other) continue;
4506 // NOTE: This isn't ideal. In particular, this might allocate the
4507 // frame pointer in functions that need it (due to them not being taken
4508 // out of allocation, because a variable sized allocation hasn't been seen
4509 // yet). This is a slight code pessimization, but should still work.
4510 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4511 E = RC->allocation_order_end(MF); I != E; ++I)
4513 // We found a matching register class. Keep looking at others in case
4514 // we find one with larger registers that this physreg is also in.
4525 /// AsmOperandInfo - This contains information for each constraint that we are
4527 struct VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4528 public TargetLowering::AsmOperandInfo {
4529 /// CallOperand - If this is the result output operand or a clobber
4530 /// this is null, otherwise it is the incoming operand to the CallInst.
4531 /// This gets modified as the asm is processed.
4532 SDValue CallOperand;
4534 /// AssignedRegs - If this is a register or register class operand, this
4535 /// contains the set of register corresponding to the operand.
4536 RegsForValue AssignedRegs;
4538 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4539 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4542 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4543 /// busy in OutputRegs/InputRegs.
4544 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4545 std::set<unsigned> &OutputRegs,
4546 std::set<unsigned> &InputRegs,
4547 const TargetRegisterInfo &TRI) const {
4549 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4550 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4553 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4554 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4558 /// getCallOperandValMVT - Return the MVT of the Value* that this operand
4559 /// corresponds to. If there is no Value* for this operand, it returns
4561 MVT getCallOperandValMVT(const TargetLowering &TLI,
4562 const TargetData *TD) const {
4563 if (CallOperandVal == 0) return MVT::Other;
4565 if (isa<BasicBlock>(CallOperandVal))
4566 return TLI.getPointerTy();
4568 const llvm::Type *OpTy = CallOperandVal->getType();
4570 // If this is an indirect operand, the operand is a pointer to the
4573 OpTy = cast<PointerType>(OpTy)->getElementType();
4575 // If OpTy is not a single value, it may be a struct/union that we
4576 // can tile with integers.
4577 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4578 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4587 OpTy = IntegerType::get(BitSize);
4592 return TLI.getValueType(OpTy, true);
4596 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4598 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4599 const TargetRegisterInfo &TRI) {
4600 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4602 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4603 for (; *Aliases; ++Aliases)
4604 Regs.insert(*Aliases);
4607 } // end llvm namespace.
4610 /// GetRegistersForValue - Assign registers (virtual or physical) for the
4611 /// specified operand. We prefer to assign virtual registers, to allow the
4612 /// register allocator handle the assignment process. However, if the asm uses
4613 /// features that we can't model on machineinstrs, we have SDISel do the
4614 /// allocation. This produces generally horrible, but correct, code.
4616 /// OpInfo describes the operand.
4617 /// Input and OutputRegs are the set of already allocated physical registers.
4619 void SelectionDAGLowering::
4620 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
4621 std::set<unsigned> &OutputRegs,
4622 std::set<unsigned> &InputRegs) {
4623 // Compute whether this value requires an input register, an output register,
4625 bool isOutReg = false;
4626 bool isInReg = false;
4627 switch (OpInfo.Type) {
4628 case InlineAsm::isOutput:
4631 // If there is an input constraint that matches this, we need to reserve
4632 // the input register so no other inputs allocate to it.
4633 isInReg = OpInfo.hasMatchingInput();
4635 case InlineAsm::isInput:
4639 case InlineAsm::isClobber:
4646 MachineFunction &MF = DAG.getMachineFunction();
4647 SmallVector<unsigned, 4> Regs;
4649 // If this is a constraint for a single physreg, or a constraint for a
4650 // register class, find it.
4651 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4652 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4653 OpInfo.ConstraintVT);
4655 unsigned NumRegs = 1;
4656 if (OpInfo.ConstraintVT != MVT::Other) {
4657 // If this is a FP input in an integer register (or visa versa) insert a bit
4658 // cast of the input value. More generally, handle any case where the input
4659 // value disagrees with the register class we plan to stick this in.
4660 if (OpInfo.Type == InlineAsm::isInput &&
4661 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4662 // Try to convert to the first MVT that the reg class contains. If the
4663 // types are identical size, use a bitcast to convert (e.g. two differing
4665 MVT RegVT = *PhysReg.second->vt_begin();
4666 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
4667 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4668 OpInfo.CallOperand);
4669 OpInfo.ConstraintVT = RegVT;
4670 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4671 // If the input is a FP value and we want it in FP registers, do a
4672 // bitcast to the corresponding integer type. This turns an f64 value
4673 // into i64, which can be passed with two i32 values on a 32-bit
4675 RegVT = MVT::getIntegerVT(OpInfo.ConstraintVT.getSizeInBits());
4676 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, RegVT,
4677 OpInfo.CallOperand);
4678 OpInfo.ConstraintVT = RegVT;
4682 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
4686 MVT ValueVT = OpInfo.ConstraintVT;
4688 // If this is a constraint for a specific physical register, like {r17},
4690 if (PhysReg.first) {
4691 if (OpInfo.ConstraintVT == MVT::Other)
4692 ValueVT = *PhysReg.second->vt_begin();
4694 // Get the actual register value type. This is important, because the user
4695 // may have asked for (e.g.) the AX register in i32 type. We need to
4696 // remember that AX is actually i16 to get the right extension.
4697 RegVT = *PhysReg.second->vt_begin();
4699 // This is a explicit reference to a physical register.
4700 Regs.push_back(PhysReg.first);
4702 // If this is an expanded reference, add the rest of the regs to Regs.
4704 TargetRegisterClass::iterator I = PhysReg.second->begin();
4705 for (; *I != PhysReg.first; ++I)
4706 assert(I != PhysReg.second->end() && "Didn't find reg!");
4708 // Already added the first reg.
4710 for (; NumRegs; --NumRegs, ++I) {
4711 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
4715 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4716 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4717 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4721 // Otherwise, if this was a reference to an LLVM register class, create vregs
4722 // for this reference.
4723 std::vector<unsigned> RegClassRegs;
4724 const TargetRegisterClass *RC = PhysReg.second;
4726 // If this is a tied register, our regalloc doesn't know how to maintain
4727 // the constraint, so we have to pick a register to pin the input/output to.
4728 // If it isn't a matched constraint, go ahead and create vreg and let the
4729 // regalloc do its thing.
4730 if (!OpInfo.hasMatchingInput()) {
4731 RegVT = *PhysReg.second->vt_begin();
4732 if (OpInfo.ConstraintVT == MVT::Other)
4735 // Create the appropriate number of virtual registers.
4736 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4737 for (; NumRegs; --NumRegs)
4738 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
4740 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4744 // Otherwise, we can't allocate it. Let the code below figure out how to
4745 // maintain these constraints.
4746 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
4749 // This is a reference to a register class that doesn't directly correspond
4750 // to an LLVM register class. Allocate NumRegs consecutive, available,
4751 // registers from the class.
4752 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4753 OpInfo.ConstraintVT);
4756 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4757 unsigned NumAllocated = 0;
4758 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4759 unsigned Reg = RegClassRegs[i];
4760 // See if this register is available.
4761 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4762 (isInReg && InputRegs.count(Reg))) { // Already used.
4763 // Make sure we find consecutive registers.
4768 // Check to see if this register is allocatable (i.e. don't give out the
4771 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4772 if (!RC) { // Couldn't allocate this register.
4773 // Reset NumAllocated to make sure we return consecutive registers.
4779 // Okay, this register is good, we can use it.
4782 // If we allocated enough consecutive registers, succeed.
4783 if (NumAllocated == NumRegs) {
4784 unsigned RegStart = (i-NumAllocated)+1;
4785 unsigned RegEnd = i+1;
4786 // Mark all of the allocated registers used.
4787 for (unsigned i = RegStart; i != RegEnd; ++i)
4788 Regs.push_back(RegClassRegs[i]);
4790 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
4791 OpInfo.ConstraintVT);
4792 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4797 // Otherwise, we couldn't allocate enough registers for this.
4800 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
4801 /// processed uses a memory 'm' constraint.
4803 hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
4804 TargetLowering &TLI) {
4805 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
4806 InlineAsm::ConstraintInfo &CI = CInfos[i];
4807 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
4808 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
4809 if (CType == TargetLowering::C_Memory)
4817 /// visitInlineAsm - Handle a call to an InlineAsm object.
4819 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
4820 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4822 /// ConstraintOperands - Information about all of the constraints.
4823 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
4825 SDValue Chain = getRoot();
4828 std::set<unsigned> OutputRegs, InputRegs;
4830 // Do a prepass over the constraints, canonicalizing them, and building up the
4831 // ConstraintOperands list.
4832 std::vector<InlineAsm::ConstraintInfo>
4833 ConstraintInfos = IA->ParseConstraints();
4835 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
4837 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
4838 unsigned ResNo = 0; // ResNo - The result number of the next output.
4839 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4840 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
4841 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
4843 MVT OpVT = MVT::Other;
4845 // Compute the value type for each operand.
4846 switch (OpInfo.Type) {
4847 case InlineAsm::isOutput:
4848 // Indirect outputs just consume an argument.
4849 if (OpInfo.isIndirect) {
4850 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4854 // The return value of the call is this value. As such, there is no
4855 // corresponding argument.
4856 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4857 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
4858 OpVT = TLI.getValueType(STy->getElementType(ResNo));
4860 assert(ResNo == 0 && "Asm only has one result!");
4861 OpVT = TLI.getValueType(CS.getType());
4865 case InlineAsm::isInput:
4866 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
4868 case InlineAsm::isClobber:
4873 // If this is an input or an indirect output, process the call argument.
4874 // BasicBlocks are labels, currently appearing only in asm's.
4875 if (OpInfo.CallOperandVal) {
4876 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
4877 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
4879 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
4882 OpVT = OpInfo.getCallOperandValMVT(TLI, TD);
4885 OpInfo.ConstraintVT = OpVT;
4888 // Second pass over the constraints: compute which constraint option to use
4889 // and assign registers to constraints that want a specific physreg.
4890 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
4891 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4893 // If this is an output operand with a matching input operand, look up the
4894 // matching input. If their types mismatch, e.g. one is an integer, the
4895 // other is floating point, or their sizes are different, flag it as an
4897 if (OpInfo.hasMatchingInput()) {
4898 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
4899 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
4900 if ((OpInfo.ConstraintVT.isInteger() !=
4901 Input.ConstraintVT.isInteger()) ||
4902 (OpInfo.ConstraintVT.getSizeInBits() !=
4903 Input.ConstraintVT.getSizeInBits())) {
4904 cerr << "Unsupported asm: input constraint with a matching output "
4905 << "constraint of incompatible type!\n";
4908 Input.ConstraintVT = OpInfo.ConstraintVT;
4912 // Compute the constraint code and ConstraintType to use.
4913 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
4915 // If this is a memory input, and if the operand is not indirect, do what we
4916 // need to to provide an address for the memory input.
4917 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4918 !OpInfo.isIndirect) {
4919 assert(OpInfo.Type == InlineAsm::isInput &&
4920 "Can only indirectify direct input operands!");
4922 // Memory operands really want the address of the value. If we don't have
4923 // an indirect input, put it in the constpool if we can, otherwise spill
4924 // it to a stack slot.
4926 // If the operand is a float, integer, or vector constant, spill to a
4927 // constant pool entry to get its address.
4928 Value *OpVal = OpInfo.CallOperandVal;
4929 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4930 isa<ConstantVector>(OpVal)) {
4931 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4932 TLI.getPointerTy());
4934 // Otherwise, create a stack slot and emit a store to it before the
4936 const Type *Ty = OpVal->getType();
4937 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
4938 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4939 MachineFunction &MF = DAG.getMachineFunction();
4940 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4941 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4942 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4943 OpInfo.CallOperand = StackSlot;
4946 // There is no longer a Value* corresponding to this operand.
4947 OpInfo.CallOperandVal = 0;
4948 // It is now an indirect operand.
4949 OpInfo.isIndirect = true;
4952 // If this constraint is for a specific register, allocate it before
4954 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4955 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
4957 ConstraintInfos.clear();
4960 // Second pass - Loop over all of the operands, assigning virtual or physregs
4961 // to register class operands.
4962 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4963 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4965 // C_Register operands have already been allocated, Other/Memory don't need
4967 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4968 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
4971 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4972 std::vector<SDValue> AsmNodeOperands;
4973 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
4974 AsmNodeOperands.push_back(
4975 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4978 // Loop over all of the inputs, copying the operand values into the
4979 // appropriate registers and processing the output regs.
4980 RegsForValue RetValRegs;
4982 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4983 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4985 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4986 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4988 switch (OpInfo.Type) {
4989 case InlineAsm::isOutput: {
4990 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4991 OpInfo.ConstraintType != TargetLowering::C_Register) {
4992 // Memory output, or 'other' output (e.g. 'X' constraint).
4993 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
4995 // Add information to the INLINEASM node to know about this output.
4996 unsigned ResOpType = 4/*MEM*/ | (1<<3);
4997 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4998 TLI.getPointerTy()));
4999 AsmNodeOperands.push_back(OpInfo.CallOperand);
5003 // Otherwise, this is a register or register class output.
5005 // Copy the output from the appropriate register. Find a register that
5007 if (OpInfo.AssignedRegs.Regs.empty()) {
5008 cerr << "Couldn't allocate output reg for constraint '"
5009 << OpInfo.ConstraintCode << "'!\n";
5013 // If this is an indirect operand, store through the pointer after the
5015 if (OpInfo.isIndirect) {
5016 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5017 OpInfo.CallOperandVal));
5019 // This is the result value of the call.
5020 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
5021 // Concatenate this output onto the outputs list.
5022 RetValRegs.append(OpInfo.AssignedRegs);
5025 // Add information to the INLINEASM node to know that this register is
5027 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5028 6 /* EARLYCLOBBER REGDEF */ :
5030 DAG, AsmNodeOperands);
5033 case InlineAsm::isInput: {
5034 SDValue InOperandVal = OpInfo.CallOperand;
5036 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
5037 // If this is required to match an output register we have already set,
5038 // just use its register.
5039 unsigned OperandNo = OpInfo.getMatchedOperand();
5041 // Scan until we find the definition we already emitted of this operand.
5042 // When we find it, create a RegsForValue operand.
5043 unsigned CurOp = 2; // The first operand.
5044 for (; OperandNo; --OperandNo) {
5045 // Advance to the next operand.
5047 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5048 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
5049 (NumOps & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5050 (NumOps & 7) == 4 /*MEM*/) &&
5051 "Skipped past definitions?");
5052 CurOp += (NumOps>>3)+1;
5056 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5057 if ((NumOps & 7) == 2 /*REGDEF*/
5058 || (NumOps & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5059 // Add NumOps>>3 registers to MatchedRegs.
5060 RegsForValue MatchedRegs;
5061 MatchedRegs.TLI = &TLI;
5062 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5063 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
5064 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
5066 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
5067 MatchedRegs.Regs.push_back(Reg);
5070 // Use the produced MatchedRegs object to
5071 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
5072 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
5075 assert(((NumOps & 7) == 4) && "Unknown matching constraint!");
5076 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
5077 // Add information to the INLINEASM node to know about this input.
5078 AsmNodeOperands.push_back(DAG.getTargetConstant(NumOps,
5079 TLI.getPointerTy()));
5080 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5085 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5086 assert(!OpInfo.isIndirect &&
5087 "Don't know how to handle indirect other inputs yet!");
5089 std::vector<SDValue> Ops;
5090 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
5091 hasMemory, Ops, DAG);
5093 cerr << "Invalid operand for inline asm constraint '"
5094 << OpInfo.ConstraintCode << "'!\n";
5098 // Add information to the INLINEASM node to know about this input.
5099 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
5100 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5101 TLI.getPointerTy()));
5102 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5104 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5105 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5106 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5107 "Memory operands expect pointer values");
5109 // Add information to the INLINEASM node to know about this input.
5110 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5111 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5112 TLI.getPointerTy()));
5113 AsmNodeOperands.push_back(InOperandVal);
5117 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5118 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5119 "Unknown constraint type!");
5120 assert(!OpInfo.isIndirect &&
5121 "Don't know how to handle indirect register inputs yet!");
5123 // Copy the input into the appropriate registers.
5124 if (OpInfo.AssignedRegs.Regs.empty()) {
5125 cerr << "Couldn't allocate output reg for constraint '"
5126 << OpInfo.ConstraintCode << "'!\n";
5130 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
5132 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/,
5133 DAG, AsmNodeOperands);
5136 case InlineAsm::isClobber: {
5137 // Add the clobbered value to the operand list, so that the register
5138 // allocator is aware that the physreg got clobbered.
5139 if (!OpInfo.AssignedRegs.Regs.empty())
5140 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
5141 DAG, AsmNodeOperands);
5147 // Finish up input operands.
5148 AsmNodeOperands[0] = Chain;
5149 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5151 Chain = DAG.getNode(ISD::INLINEASM,
5152 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
5153 &AsmNodeOperands[0], AsmNodeOperands.size());
5154 Flag = Chain.getValue(1);
5156 // If this asm returns a register value, copy the result from that register
5157 // and set it as the value of the call.
5158 if (!RetValRegs.Regs.empty()) {
5159 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
5161 // FIXME: Why don't we do this for inline asms with MRVs?
5162 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5163 MVT ResultType = TLI.getValueType(CS.getType());
5165 // If any of the results of the inline asm is a vector, it may have the
5166 // wrong width/num elts. This can happen for register classes that can
5167 // contain multiple different value types. The preg or vreg allocated may
5168 // not have the same VT as was expected. Convert it to the right type
5169 // with bit_convert.
5170 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5171 Val = DAG.getNode(ISD::BIT_CONVERT, ResultType, Val);
5173 } else if (ResultType != Val.getValueType() &&
5174 ResultType.isInteger() && Val.getValueType().isInteger()) {
5175 // If a result value was tied to an input value, the computed result may
5176 // have a wider width than the expected result. Extract the relevant
5178 Val = DAG.getNode(ISD::TRUNCATE, ResultType, Val);
5181 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
5184 setValue(CS.getInstruction(), Val);
5187 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5189 // Process indirect outputs, first output all of the flagged copies out of
5191 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5192 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5193 Value *Ptr = IndirectStoresToEmit[i].second;
5194 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
5195 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5198 // Emit the non-flagged stores from the physregs.
5199 SmallVector<SDValue, 8> OutChains;
5200 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5201 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
5202 getValue(StoresToEmit[i].second),
5203 StoresToEmit[i].second, 0));
5204 if (!OutChains.empty())
5205 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5206 &OutChains[0], OutChains.size());
5211 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
5212 SDValue Src = getValue(I.getOperand(0));
5214 MVT IntPtr = TLI.getPointerTy();
5216 if (IntPtr.bitsLT(Src.getValueType()))
5217 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
5218 else if (IntPtr.bitsGT(Src.getValueType()))
5219 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
5221 // Scale the source by the type size.
5222 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
5223 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
5224 Src, DAG.getIntPtrConstant(ElementSize));
5226 TargetLowering::ArgListTy Args;
5227 TargetLowering::ArgListEntry Entry;
5229 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5230 Args.push_back(Entry);
5232 std::pair<SDValue,SDValue> Result =
5233 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, false,
5234 CallingConv::C, PerformTailCallOpt,
5235 DAG.getExternalSymbol("malloc", IntPtr),
5237 setValue(&I, Result.first); // Pointers always fit in registers
5238 DAG.setRoot(Result.second);
5241 void SelectionDAGLowering::visitFree(FreeInst &I) {
5242 TargetLowering::ArgListTy Args;
5243 TargetLowering::ArgListEntry Entry;
5244 Entry.Node = getValue(I.getOperand(0));
5245 Entry.Ty = TLI.getTargetData()->getIntPtrType();
5246 Args.push_back(Entry);
5247 MVT IntPtr = TLI.getPointerTy();
5248 std::pair<SDValue,SDValue> Result =
5249 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false, false,
5250 CallingConv::C, PerformTailCallOpt,
5251 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
5252 DAG.setRoot(Result.second);
5255 void SelectionDAGLowering::visitVAStart(CallInst &I) {
5256 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
5257 getValue(I.getOperand(1)),
5258 DAG.getSrcValue(I.getOperand(1))));
5261 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
5262 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
5263 getValue(I.getOperand(0)),
5264 DAG.getSrcValue(I.getOperand(0)));
5266 DAG.setRoot(V.getValue(1));
5269 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
5270 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
5271 getValue(I.getOperand(1)),
5272 DAG.getSrcValue(I.getOperand(1))));
5275 void SelectionDAGLowering::visitVACopy(CallInst &I) {
5276 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
5277 getValue(I.getOperand(1)),
5278 getValue(I.getOperand(2)),
5279 DAG.getSrcValue(I.getOperand(1)),
5280 DAG.getSrcValue(I.getOperand(2))));
5283 /// TargetLowering::LowerArguments - This is the default LowerArguments
5284 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
5285 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
5286 /// integrated into SDISel.
5287 void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
5288 SmallVectorImpl<SDValue> &ArgValues) {
5289 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
5290 SmallVector<SDValue, 3+16> Ops;
5291 Ops.push_back(DAG.getRoot());
5292 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
5293 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
5295 // Add one result value for each formal argument.
5296 SmallVector<MVT, 16> RetVals;
5298 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5300 SmallVector<MVT, 4> ValueVTs;
5301 ComputeValueVTs(*this, I->getType(), ValueVTs);
5302 for (unsigned Value = 0, NumValues = ValueVTs.size();
5303 Value != NumValues; ++Value) {
5304 MVT VT = ValueVTs[Value];
5305 const Type *ArgTy = VT.getTypeForMVT();
5306 ISD::ArgFlagsTy Flags;
5307 unsigned OriginalAlignment =
5308 getTargetData()->getABITypeAlignment(ArgTy);
5310 if (F.paramHasAttr(j, Attribute::ZExt))
5312 if (F.paramHasAttr(j, Attribute::SExt))
5314 if (F.paramHasAttr(j, Attribute::InReg))
5316 if (F.paramHasAttr(j, Attribute::StructRet))
5318 if (F.paramHasAttr(j, Attribute::ByVal)) {
5320 const PointerType *Ty = cast<PointerType>(I->getType());
5321 const Type *ElementTy = Ty->getElementType();
5322 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5323 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
5324 // For ByVal, alignment should be passed from FE. BE will guess if
5325 // this info is not there but there are cases it cannot get right.
5326 if (F.getParamAlignment(j))
5327 FrameAlign = F.getParamAlignment(j);
5328 Flags.setByValAlign(FrameAlign);
5329 Flags.setByValSize(FrameSize);
5331 if (F.paramHasAttr(j, Attribute::Nest))
5333 Flags.setOrigAlign(OriginalAlignment);
5335 MVT RegisterVT = getRegisterType(VT);
5336 unsigned NumRegs = getNumRegisters(VT);
5337 for (unsigned i = 0; i != NumRegs; ++i) {
5338 RetVals.push_back(RegisterVT);
5339 ISD::ArgFlagsTy MyFlags = Flags;
5340 if (NumRegs > 1 && i == 0)
5342 // if it isn't first piece, alignment must be 1
5344 MyFlags.setOrigAlign(1);
5345 Ops.push_back(DAG.getArgFlags(MyFlags));
5350 RetVals.push_back(MVT::Other);
5353 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
5354 DAG.getVTList(&RetVals[0], RetVals.size()),
5355 &Ops[0], Ops.size()).getNode();
5357 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
5358 // allows exposing the loads that may be part of the argument access to the
5359 // first DAGCombiner pass.
5360 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
5362 // The number of results should match up, except that the lowered one may have
5363 // an extra flag result.
5364 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
5365 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
5366 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
5367 && "Lowering produced unexpected number of results!");
5369 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
5370 if (Result != TmpRes.getNode() && Result->use_empty()) {
5371 HandleSDNode Dummy(DAG.getRoot());
5372 DAG.RemoveDeadNode(Result);
5375 Result = TmpRes.getNode();
5377 unsigned NumArgRegs = Result->getNumValues() - 1;
5378 DAG.setRoot(SDValue(Result, NumArgRegs));
5380 // Set up the return result vector.
5383 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5385 SmallVector<MVT, 4> ValueVTs;
5386 ComputeValueVTs(*this, I->getType(), ValueVTs);
5387 for (unsigned Value = 0, NumValues = ValueVTs.size();
5388 Value != NumValues; ++Value) {
5389 MVT VT = ValueVTs[Value];
5390 MVT PartVT = getRegisterType(VT);
5392 unsigned NumParts = getNumRegisters(VT);
5393 SmallVector<SDValue, 4> Parts(NumParts);
5394 for (unsigned j = 0; j != NumParts; ++j)
5395 Parts[j] = SDValue(Result, i++);
5397 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5398 if (F.paramHasAttr(Idx, Attribute::SExt))
5399 AssertOp = ISD::AssertSext;
5400 else if (F.paramHasAttr(Idx, Attribute::ZExt))
5401 AssertOp = ISD::AssertZext;
5403 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
5407 assert(i == NumArgRegs && "Argument register count mismatch!");
5411 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
5412 /// implementation, which just inserts an ISD::CALL node, which is later custom
5413 /// lowered by the target to something concrete. FIXME: When all targets are
5414 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
5415 std::pair<SDValue, SDValue>
5416 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5417 bool RetSExt, bool RetZExt, bool isVarArg,
5419 unsigned CallingConv, bool isTailCall,
5421 ArgListTy &Args, SelectionDAG &DAG) {
5422 assert((!isTailCall || PerformTailCallOpt) &&
5423 "isTailCall set when tail-call optimizations are disabled!");
5425 SmallVector<SDValue, 32> Ops;
5426 Ops.push_back(Chain); // Op#0 - Chain
5427 Ops.push_back(Callee);
5429 // Handle all of the outgoing arguments.
5430 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5431 SmallVector<MVT, 4> ValueVTs;
5432 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5433 for (unsigned Value = 0, NumValues = ValueVTs.size();
5434 Value != NumValues; ++Value) {
5435 MVT VT = ValueVTs[Value];
5436 const Type *ArgTy = VT.getTypeForMVT();
5437 SDValue Op = SDValue(Args[i].Node.getNode(),
5438 Args[i].Node.getResNo() + Value);
5439 ISD::ArgFlagsTy Flags;
5440 unsigned OriginalAlignment =
5441 getTargetData()->getABITypeAlignment(ArgTy);
5447 if (Args[i].isInReg)
5451 if (Args[i].isByVal) {
5453 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5454 const Type *ElementTy = Ty->getElementType();
5455 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5456 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
5457 // For ByVal, alignment should come from FE. BE will guess if this
5458 // info is not there but there are cases it cannot get right.
5459 if (Args[i].Alignment)
5460 FrameAlign = Args[i].Alignment;
5461 Flags.setByValAlign(FrameAlign);
5462 Flags.setByValSize(FrameSize);
5466 Flags.setOrigAlign(OriginalAlignment);
5468 MVT PartVT = getRegisterType(VT);
5469 unsigned NumParts = getNumRegisters(VT);
5470 SmallVector<SDValue, 4> Parts(NumParts);
5471 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5474 ExtendKind = ISD::SIGN_EXTEND;
5475 else if (Args[i].isZExt)
5476 ExtendKind = ISD::ZERO_EXTEND;
5478 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5480 for (unsigned i = 0; i != NumParts; ++i) {
5481 // if it isn't first piece, alignment must be 1
5482 ISD::ArgFlagsTy MyFlags = Flags;
5483 if (NumParts > 1 && i == 0)
5486 MyFlags.setOrigAlign(1);
5488 Ops.push_back(Parts[i]);
5489 Ops.push_back(DAG.getArgFlags(MyFlags));
5494 // Figure out the result value types. We start by making a list of
5495 // the potentially illegal return value types.
5496 SmallVector<MVT, 4> LoweredRetTys;
5497 SmallVector<MVT, 4> RetTys;
5498 ComputeValueVTs(*this, RetTy, RetTys);
5500 // Then we translate that to a list of legal types.
5501 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5503 MVT RegisterVT = getRegisterType(VT);
5504 unsigned NumRegs = getNumRegisters(VT);
5505 for (unsigned i = 0; i != NumRegs; ++i)
5506 LoweredRetTys.push_back(RegisterVT);
5509 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
5511 // Create the CALL node.
5512 SDValue Res = DAG.getCall(CallingConv, isVarArg, isTailCall, isInreg,
5513 DAG.getVTList(&LoweredRetTys[0],
5514 LoweredRetTys.size()),
5517 Chain = Res.getValue(LoweredRetTys.size() - 1);
5519 // Gather up the call result into a single value.
5520 if (RetTy != Type::VoidTy && !RetTys.empty()) {
5521 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5524 AssertOp = ISD::AssertSext;
5526 AssertOp = ISD::AssertZext;
5528 SmallVector<SDValue, 4> ReturnValues;
5530 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5532 MVT RegisterVT = getRegisterType(VT);
5533 unsigned NumRegs = getNumRegisters(VT);
5534 unsigned RegNoEnd = NumRegs + RegNo;
5535 SmallVector<SDValue, 4> Results;
5536 for (; RegNo != RegNoEnd; ++RegNo)
5537 Results.push_back(Res.getValue(RegNo));
5538 SDValue ReturnValue =
5539 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
5541 ReturnValues.push_back(ReturnValue);
5543 Res = DAG.getNode(ISD::MERGE_VALUES,
5544 DAG.getVTList(&RetTys[0], RetTys.size()),
5545 &ReturnValues[0], ReturnValues.size());
5548 return std::make_pair(Res, Chain);
5551 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5552 assert(0 && "LowerOperation not implemented for this target!");
5558 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5559 SDValue Op = getValue(V);
5560 assert((Op.getOpcode() != ISD::CopyFromReg ||
5561 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5562 "Copy from a reg to the same reg!");
5563 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5565 RegsForValue RFV(TLI, Reg, V->getType());
5566 SDValue Chain = DAG.getEntryNode();
5567 RFV.getCopyToRegs(Op, DAG, Chain, 0);
5568 PendingExports.push_back(Chain);
5571 #include "llvm/CodeGen/SelectionDAGISel.h"
5573 void SelectionDAGISel::
5574 LowerArguments(BasicBlock *LLVMBB) {
5575 // If this is the entry block, emit arguments.
5576 Function &F = *LLVMBB->getParent();
5577 SDValue OldRoot = SDL->DAG.getRoot();
5578 SmallVector<SDValue, 16> Args;
5579 TLI.LowerArguments(F, SDL->DAG, Args);
5582 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
5584 SmallVector<MVT, 4> ValueVTs;
5585 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
5586 unsigned NumValues = ValueVTs.size();
5587 if (!AI->use_empty()) {
5588 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues));
5589 // If this argument is live outside of the entry block, insert a copy from
5590 // whereever we got it to the vreg that other BB's will reference it as.
5591 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
5592 if (VMI != FuncInfo->ValueMap.end()) {
5593 SDL->CopyValueToVirtualRegister(AI, VMI->second);
5599 // Finally, if the target has anything special to do, allow it to do so.
5600 // FIXME: this should insert code into the DAG!
5601 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
5604 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5605 /// ensure constants are generated when needed. Remember the virtual registers
5606 /// that need to be added to the Machine PHI nodes as input. We cannot just
5607 /// directly add them, because expansion might result in multiple MBB's for one
5608 /// BB. As such, the start of the BB might correspond to a different MBB than
5612 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5613 TerminatorInst *TI = LLVMBB->getTerminator();
5615 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5617 // Check successor nodes' PHI nodes that expect a constant to be available
5619 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5620 BasicBlock *SuccBB = TI->getSuccessor(succ);
5621 if (!isa<PHINode>(SuccBB->begin())) continue;
5622 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5624 // If this terminator has multiple identical successors (common for
5625 // switches), only handle each succ once.
5626 if (!SuccsHandled.insert(SuccMBB)) continue;
5628 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5631 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5632 // nodes and Machine PHI nodes, but the incoming operands have not been
5634 for (BasicBlock::iterator I = SuccBB->begin();
5635 (PN = dyn_cast<PHINode>(I)); ++I) {
5636 // Ignore dead phi's.
5637 if (PN->use_empty()) continue;
5640 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5642 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5643 unsigned &RegOut = SDL->ConstantsOut[C];
5645 RegOut = FuncInfo->CreateRegForValue(C);
5646 SDL->CopyValueToVirtualRegister(C, RegOut);
5650 Reg = FuncInfo->ValueMap[PHIOp];
5652 assert(isa<AllocaInst>(PHIOp) &&
5653 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5654 "Didn't codegen value into a register!??");
5655 Reg = FuncInfo->CreateRegForValue(PHIOp);
5656 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
5660 // Remember that this register needs to added to the machine PHI node as
5661 // the input for this MBB.
5662 SmallVector<MVT, 4> ValueVTs;
5663 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5664 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5665 MVT VT = ValueVTs[vti];
5666 unsigned NumRegisters = TLI.getNumRegisters(VT);
5667 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5668 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5669 Reg += NumRegisters;
5673 SDL->ConstantsOut.clear();
5676 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5677 /// supports legal types, and it emits MachineInstrs directly instead of
5678 /// creating SelectionDAG nodes.
5681 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5683 TerminatorInst *TI = LLVMBB->getTerminator();
5685 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5686 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
5688 // Check successor nodes' PHI nodes that expect a constant to be available
5690 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5691 BasicBlock *SuccBB = TI->getSuccessor(succ);
5692 if (!isa<PHINode>(SuccBB->begin())) continue;
5693 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5695 // If this terminator has multiple identical successors (common for
5696 // switches), only handle each succ once.
5697 if (!SuccsHandled.insert(SuccMBB)) continue;
5699 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5702 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5703 // nodes and Machine PHI nodes, but the incoming operands have not been
5705 for (BasicBlock::iterator I = SuccBB->begin();
5706 (PN = dyn_cast<PHINode>(I)); ++I) {
5707 // Ignore dead phi's.
5708 if (PN->use_empty()) continue;
5710 // Only handle legal types. Two interesting things to note here. First,
5711 // by bailing out early, we may leave behind some dead instructions,
5712 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5713 // own moves. Second, this check is necessary becuase FastISel doesn't
5714 // use CreateRegForValue to create registers, so it always creates
5715 // exactly one register for each non-void instruction.
5716 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5717 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
5720 VT = TLI.getTypeToTransformTo(VT);
5722 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5727 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5729 unsigned Reg = F->getRegForValue(PHIOp);
5731 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5734 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));