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/Analysis/AliasAnalysis.h"
18 #include "llvm/Constants.h"
19 #include "llvm/CallingConv.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Function.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/InlineAsm.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/Intrinsics.h"
26 #include "llvm/IntrinsicInst.h"
27 #include "llvm/ParameterAttributes.h"
28 #include "llvm/CodeGen/FastISel.h"
29 #include "llvm/CodeGen/GCStrategy.h"
30 #include "llvm/CodeGen/GCMetadata.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineInstrBuilder.h"
34 #include "llvm/CodeGen/MachineJumpTableInfo.h"
35 #include "llvm/CodeGen/MachineModuleInfo.h"
36 #include "llvm/CodeGen/MachineRegisterInfo.h"
37 #include "llvm/CodeGen/SelectionDAG.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Target/TargetFrameInfo.h"
41 #include "llvm/Target/TargetInstrInfo.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetOptions.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/MathExtras.h"
51 /// ComputeLinearIndex - Given an LLVM IR aggregate type and a sequence
52 /// insertvalue or extractvalue indices that identify a member, return
53 /// the linearized index of the start of the member.
55 static unsigned ComputeLinearIndex(const TargetLowering &TLI, const Type *Ty,
56 const unsigned *Indices,
57 const unsigned *IndicesEnd,
58 unsigned CurIndex = 0) {
59 // Base case: We're done.
60 if (Indices && Indices == IndicesEnd)
63 // Given a struct type, recursively traverse the elements.
64 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
65 for (StructType::element_iterator EB = STy->element_begin(),
67 EE = STy->element_end();
69 if (Indices && *Indices == unsigned(EI - EB))
70 return ComputeLinearIndex(TLI, *EI, Indices+1, IndicesEnd, CurIndex);
71 CurIndex = ComputeLinearIndex(TLI, *EI, 0, 0, CurIndex);
74 // Given an array type, recursively traverse the elements.
75 else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
76 const Type *EltTy = ATy->getElementType();
77 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i) {
78 if (Indices && *Indices == i)
79 return ComputeLinearIndex(TLI, EltTy, Indices+1, IndicesEnd, CurIndex);
80 CurIndex = ComputeLinearIndex(TLI, EltTy, 0, 0, CurIndex);
83 // We haven't found the type we're looking for, so keep searching.
87 /// ComputeValueVTs - Given an LLVM IR type, compute a sequence of
88 /// MVTs that represent all the individual underlying
89 /// non-aggregate types that comprise it.
91 /// If Offsets is non-null, it points to a vector to be filled in
92 /// with the in-memory offsets of each of the individual values.
94 static void ComputeValueVTs(const TargetLowering &TLI, const Type *Ty,
95 SmallVectorImpl<MVT> &ValueVTs,
96 SmallVectorImpl<uint64_t> *Offsets = 0,
97 uint64_t StartingOffset = 0) {
98 // Given a struct type, recursively traverse the elements.
99 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
100 const StructLayout *SL = TLI.getTargetData()->getStructLayout(STy);
101 for (StructType::element_iterator EB = STy->element_begin(),
103 EE = STy->element_end();
105 ComputeValueVTs(TLI, *EI, ValueVTs, Offsets,
106 StartingOffset + SL->getElementOffset(EI - EB));
109 // Given an array type, recursively traverse the elements.
110 if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
111 const Type *EltTy = ATy->getElementType();
112 uint64_t EltSize = TLI.getTargetData()->getABITypeSize(EltTy);
113 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
114 ComputeValueVTs(TLI, EltTy, ValueVTs, Offsets,
115 StartingOffset + i * EltSize);
118 // Base case: we can get an MVT for this LLVM IR type.
119 ValueVTs.push_back(TLI.getValueType(Ty));
121 Offsets->push_back(StartingOffset);
125 /// RegsForValue - This struct represents the registers (physical or virtual)
126 /// that a particular set of values is assigned, and the type information about
127 /// the value. The most common situation is to represent one value at a time,
128 /// but struct or array values are handled element-wise as multiple values.
129 /// The splitting of aggregates is performed recursively, so that we never
130 /// have aggregate-typed registers. The values at this point do not necessarily
131 /// have legal types, so each value may require one or more registers of some
134 struct VISIBILITY_HIDDEN RegsForValue {
135 /// TLI - The TargetLowering object.
137 const TargetLowering *TLI;
139 /// ValueVTs - The value types of the values, which may not be legal, and
140 /// may need be promoted or synthesized from one or more registers.
142 SmallVector<MVT, 4> ValueVTs;
144 /// RegVTs - The value types of the registers. This is the same size as
145 /// ValueVTs and it records, for each value, what the type of the assigned
146 /// register or registers are. (Individual values are never synthesized
147 /// from more than one type of register.)
149 /// With virtual registers, the contents of RegVTs is redundant with TLI's
150 /// getRegisterType member function, however when with physical registers
151 /// it is necessary to have a separate record of the types.
153 SmallVector<MVT, 4> RegVTs;
155 /// Regs - This list holds the registers assigned to the values.
156 /// Each legal or promoted value requires one register, and each
157 /// expanded value requires multiple registers.
159 SmallVector<unsigned, 4> Regs;
161 RegsForValue() : TLI(0) {}
163 RegsForValue(const TargetLowering &tli,
164 const SmallVector<unsigned, 4> ®s,
165 MVT regvt, MVT valuevt)
166 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
167 RegsForValue(const TargetLowering &tli,
168 const SmallVector<unsigned, 4> ®s,
169 const SmallVector<MVT, 4> ®vts,
170 const SmallVector<MVT, 4> &valuevts)
171 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
172 RegsForValue(const TargetLowering &tli,
173 unsigned Reg, const Type *Ty) : TLI(&tli) {
174 ComputeValueVTs(tli, Ty, ValueVTs);
176 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
177 MVT ValueVT = ValueVTs[Value];
178 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
179 MVT RegisterVT = TLI->getRegisterType(ValueVT);
180 for (unsigned i = 0; i != NumRegs; ++i)
181 Regs.push_back(Reg + i);
182 RegVTs.push_back(RegisterVT);
187 /// append - Add the specified values to this one.
188 void append(const RegsForValue &RHS) {
190 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
191 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
192 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
196 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
197 /// this value and returns the result as a ValueVTs value. This uses
198 /// Chain/Flag as the input and updates them for the output Chain/Flag.
199 /// If the Flag pointer is NULL, no flag is used.
200 SDValue getCopyFromRegs(SelectionDAG &DAG,
201 SDValue &Chain, SDValue *Flag) const;
203 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
204 /// specified value into the registers specified by this object. This uses
205 /// Chain/Flag as the input and updates them for the output Chain/Flag.
206 /// If the Flag pointer is NULL, no flag is used.
207 void getCopyToRegs(SDValue Val, SelectionDAG &DAG,
208 SDValue &Chain, SDValue *Flag) const;
210 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
211 /// operand list. This adds the code marker and includes the number of
212 /// values added into it.
213 void AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
214 std::vector<SDValue> &Ops) const;
218 /// isUsedOutsideOfDefiningBlock - Return true if this instruction is used by
219 /// PHI nodes or outside of the basic block that defines it, or used by a
220 /// switch or atomic instruction, which may expand to multiple basic blocks.
221 static bool isUsedOutsideOfDefiningBlock(Instruction *I) {
222 if (isa<PHINode>(I)) return true;
223 BasicBlock *BB = I->getParent();
224 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E; ++UI)
225 if (cast<Instruction>(*UI)->getParent() != BB || isa<PHINode>(*UI) ||
226 // FIXME: Remove switchinst special case.
227 isa<SwitchInst>(*UI))
232 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
233 /// entry block, return true. This includes arguments used by switches, since
234 /// the switch may expand into multiple basic blocks.
235 static bool isOnlyUsedInEntryBlock(Argument *A, bool EnableFastISel) {
236 // With FastISel active, we may be splitting blocks, so force creation
237 // of virtual registers for all non-dead arguments.
239 return A->use_empty();
241 BasicBlock *Entry = A->getParent()->begin();
242 for (Value::use_iterator UI = A->use_begin(), E = A->use_end(); UI != E; ++UI)
243 if (cast<Instruction>(*UI)->getParent() != Entry || isa<SwitchInst>(*UI))
244 return false; // Use not in entry block.
248 FunctionLoweringInfo::FunctionLoweringInfo(TargetLowering &tli)
252 void FunctionLoweringInfo::set(Function &fn, MachineFunction &mf,
253 bool EnableFastISel) {
256 RegInfo = &MF->getRegInfo();
258 // Create a vreg for each argument register that is not dead and is used
259 // outside of the entry block for the function.
260 for (Function::arg_iterator AI = Fn->arg_begin(), E = Fn->arg_end();
262 if (!isOnlyUsedInEntryBlock(AI, EnableFastISel))
263 InitializeRegForValue(AI);
265 // Initialize the mapping of values to registers. This is only set up for
266 // instruction values that are used outside of the block that defines
268 Function::iterator BB = Fn->begin(), EB = Fn->end();
269 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
270 if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
271 if (ConstantInt *CUI = dyn_cast<ConstantInt>(AI->getArraySize())) {
272 const Type *Ty = AI->getAllocatedType();
273 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
275 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
278 TySize *= CUI->getZExtValue(); // Get total allocated size.
279 if (TySize == 0) TySize = 1; // Don't create zero-sized stack objects.
280 StaticAllocaMap[AI] =
281 MF->getFrameInfo()->CreateStackObject(TySize, Align);
284 for (; BB != EB; ++BB)
285 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
286 if (!I->use_empty() && isUsedOutsideOfDefiningBlock(I))
287 if (!isa<AllocaInst>(I) ||
288 !StaticAllocaMap.count(cast<AllocaInst>(I)))
289 InitializeRegForValue(I);
291 // Create an initial MachineBasicBlock for each LLVM BasicBlock in F. This
292 // also creates the initial PHI MachineInstrs, though none of the input
293 // operands are populated.
294 for (BB = Fn->begin(), EB = Fn->end(); BB != EB; ++BB) {
295 MachineBasicBlock *MBB = mf.CreateMachineBasicBlock(BB);
299 // Create Machine PHI nodes for LLVM PHI nodes, lowering them as
302 for (BasicBlock::iterator I = BB->begin();(PN = dyn_cast<PHINode>(I)); ++I){
303 if (PN->use_empty()) continue;
305 unsigned PHIReg = ValueMap[PN];
306 assert(PHIReg && "PHI node does not have an assigned virtual register!");
308 SmallVector<MVT, 4> ValueVTs;
309 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
310 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
311 MVT VT = ValueVTs[vti];
312 unsigned NumRegisters = TLI.getNumRegisters(VT);
313 const TargetInstrInfo *TII = TLI.getTargetMachine().getInstrInfo();
314 for (unsigned i = 0; i != NumRegisters; ++i)
315 BuildMI(MBB, TII->get(TargetInstrInfo::PHI), PHIReg+i);
316 PHIReg += NumRegisters;
322 unsigned FunctionLoweringInfo::MakeReg(MVT VT) {
323 return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
326 /// CreateRegForValue - Allocate the appropriate number of virtual registers of
327 /// the correctly promoted or expanded types. Assign these registers
328 /// consecutive vreg numbers and return the first assigned number.
330 /// In the case that the given value has struct or array type, this function
331 /// will assign registers for each member or element.
333 unsigned FunctionLoweringInfo::CreateRegForValue(const Value *V) {
334 SmallVector<MVT, 4> ValueVTs;
335 ComputeValueVTs(TLI, V->getType(), ValueVTs);
337 unsigned FirstReg = 0;
338 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
339 MVT ValueVT = ValueVTs[Value];
340 MVT RegisterVT = TLI.getRegisterType(ValueVT);
342 unsigned NumRegs = TLI.getNumRegisters(ValueVT);
343 for (unsigned i = 0; i != NumRegs; ++i) {
344 unsigned R = MakeReg(RegisterVT);
345 if (!FirstReg) FirstReg = R;
351 /// getCopyFromParts - Create a value that contains the specified legal parts
352 /// combined into the value they represent. If the parts combine to a type
353 /// larger then ValueVT then AssertOp can be used to specify whether the extra
354 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
355 /// (ISD::AssertSext).
356 static SDValue getCopyFromParts(SelectionDAG &DAG,
357 const SDValue *Parts,
361 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
362 assert(NumParts > 0 && "No parts to assemble!");
363 TargetLowering &TLI = DAG.getTargetLoweringInfo();
364 SDValue Val = Parts[0];
367 // Assemble the value from multiple parts.
368 if (!ValueVT.isVector()) {
369 unsigned PartBits = PartVT.getSizeInBits();
370 unsigned ValueBits = ValueVT.getSizeInBits();
372 // Assemble the power of 2 part.
373 unsigned RoundParts = NumParts & (NumParts - 1) ?
374 1 << Log2_32(NumParts) : NumParts;
375 unsigned RoundBits = PartBits * RoundParts;
376 MVT RoundVT = RoundBits == ValueBits ?
377 ValueVT : MVT::getIntegerVT(RoundBits);
380 if (RoundParts > 2) {
381 MVT HalfVT = MVT::getIntegerVT(RoundBits/2);
382 Lo = getCopyFromParts(DAG, Parts, RoundParts/2, PartVT, HalfVT);
383 Hi = getCopyFromParts(DAG, Parts+RoundParts/2, RoundParts/2,
389 if (TLI.isBigEndian())
391 Val = DAG.getNode(ISD::BUILD_PAIR, RoundVT, Lo, Hi);
393 if (RoundParts < NumParts) {
394 // Assemble the trailing non-power-of-2 part.
395 unsigned OddParts = NumParts - RoundParts;
396 MVT OddVT = MVT::getIntegerVT(OddParts * PartBits);
397 Hi = getCopyFromParts(DAG, Parts+RoundParts, OddParts, PartVT, OddVT);
399 // Combine the round and odd parts.
401 if (TLI.isBigEndian())
403 MVT TotalVT = MVT::getIntegerVT(NumParts * PartBits);
404 Hi = DAG.getNode(ISD::ANY_EXTEND, TotalVT, Hi);
405 Hi = DAG.getNode(ISD::SHL, TotalVT, Hi,
406 DAG.getConstant(Lo.getValueType().getSizeInBits(),
407 TLI.getShiftAmountTy()));
408 Lo = DAG.getNode(ISD::ZERO_EXTEND, TotalVT, Lo);
409 Val = DAG.getNode(ISD::OR, TotalVT, Lo, Hi);
412 // Handle a multi-element vector.
413 MVT IntermediateVT, RegisterVT;
414 unsigned NumIntermediates;
416 TLI.getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
418 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
419 NumParts = NumRegs; // Silence a compiler warning.
420 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
421 assert(RegisterVT == Parts[0].getValueType() &&
422 "Part type doesn't match part!");
424 // Assemble the parts into intermediate operands.
425 SmallVector<SDValue, 8> Ops(NumIntermediates);
426 if (NumIntermediates == NumParts) {
427 // If the register was not expanded, truncate or copy the value,
429 for (unsigned i = 0; i != NumParts; ++i)
430 Ops[i] = getCopyFromParts(DAG, &Parts[i], 1,
431 PartVT, IntermediateVT);
432 } else if (NumParts > 0) {
433 // If the intermediate type was expanded, build the intermediate operands
435 assert(NumParts % NumIntermediates == 0 &&
436 "Must expand into a divisible number of parts!");
437 unsigned Factor = NumParts / NumIntermediates;
438 for (unsigned i = 0; i != NumIntermediates; ++i)
439 Ops[i] = getCopyFromParts(DAG, &Parts[i * Factor], Factor,
440 PartVT, IntermediateVT);
443 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
445 Val = DAG.getNode(IntermediateVT.isVector() ?
446 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR,
447 ValueVT, &Ops[0], NumIntermediates);
451 // There is now one part, held in Val. Correct it to match ValueVT.
452 PartVT = Val.getValueType();
454 if (PartVT == ValueVT)
457 if (PartVT.isVector()) {
458 assert(ValueVT.isVector() && "Unknown vector conversion!");
459 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
462 if (ValueVT.isVector()) {
463 assert(ValueVT.getVectorElementType() == PartVT &&
464 ValueVT.getVectorNumElements() == 1 &&
465 "Only trivial scalar-to-vector conversions should get here!");
466 return DAG.getNode(ISD::BUILD_VECTOR, ValueVT, Val);
469 if (PartVT.isInteger() &&
470 ValueVT.isInteger()) {
471 if (ValueVT.bitsLT(PartVT)) {
472 // For a truncate, see if we have any information to
473 // indicate whether the truncated bits will always be
474 // zero or sign-extension.
475 if (AssertOp != ISD::DELETED_NODE)
476 Val = DAG.getNode(AssertOp, PartVT, Val,
477 DAG.getValueType(ValueVT));
478 return DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
480 return DAG.getNode(ISD::ANY_EXTEND, ValueVT, Val);
484 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
485 if (ValueVT.bitsLT(Val.getValueType()))
486 // FP_ROUND's are always exact here.
487 return DAG.getNode(ISD::FP_ROUND, ValueVT, Val,
488 DAG.getIntPtrConstant(1));
489 return DAG.getNode(ISD::FP_EXTEND, ValueVT, Val);
492 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
493 return DAG.getNode(ISD::BIT_CONVERT, ValueVT, Val);
495 assert(0 && "Unknown mismatch!");
499 /// getCopyToParts - Create a series of nodes that contain the specified value
500 /// split into legal parts. If the parts contain more bits than Val, then, for
501 /// integers, ExtendKind can be used to specify how to generate the extra bits.
502 static void getCopyToParts(SelectionDAG &DAG,
507 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
508 TargetLowering &TLI = DAG.getTargetLoweringInfo();
509 MVT PtrVT = TLI.getPointerTy();
510 MVT ValueVT = Val.getValueType();
511 unsigned PartBits = PartVT.getSizeInBits();
512 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
517 if (!ValueVT.isVector()) {
518 if (PartVT == ValueVT) {
519 assert(NumParts == 1 && "No-op copy with multiple parts!");
524 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
525 // If the parts cover more bits than the value has, promote the value.
526 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
527 assert(NumParts == 1 && "Do not know what to promote to!");
528 Val = DAG.getNode(ISD::FP_EXTEND, PartVT, Val);
529 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
530 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
531 Val = DAG.getNode(ExtendKind, ValueVT, Val);
533 assert(0 && "Unknown mismatch!");
535 } else if (PartBits == ValueVT.getSizeInBits()) {
536 // Different types of the same size.
537 assert(NumParts == 1 && PartVT != ValueVT);
538 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
539 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
540 // If the parts cover less bits than value has, truncate the value.
541 if (PartVT.isInteger() && ValueVT.isInteger()) {
542 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
543 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
545 assert(0 && "Unknown mismatch!");
549 // The value may have changed - recompute ValueVT.
550 ValueVT = Val.getValueType();
551 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
552 "Failed to tile the value with PartVT!");
555 assert(PartVT == ValueVT && "Type conversion failed!");
560 // Expand the value into multiple parts.
561 if (NumParts & (NumParts - 1)) {
562 // The number of parts is not a power of 2. Split off and copy the tail.
563 assert(PartVT.isInteger() && ValueVT.isInteger() &&
564 "Do not know what to expand to!");
565 unsigned RoundParts = 1 << Log2_32(NumParts);
566 unsigned RoundBits = RoundParts * PartBits;
567 unsigned OddParts = NumParts - RoundParts;
568 SDValue OddVal = DAG.getNode(ISD::SRL, ValueVT, Val,
569 DAG.getConstant(RoundBits,
570 TLI.getShiftAmountTy()));
571 getCopyToParts(DAG, OddVal, Parts + RoundParts, OddParts, PartVT);
572 if (TLI.isBigEndian())
573 // The odd parts were reversed by getCopyToParts - unreverse them.
574 std::reverse(Parts + RoundParts, Parts + NumParts);
575 NumParts = RoundParts;
576 ValueVT = MVT::getIntegerVT(NumParts * PartBits);
577 Val = DAG.getNode(ISD::TRUNCATE, ValueVT, Val);
580 // The number of parts is a power of 2. Repeatedly bisect the value using
582 Parts[0] = DAG.getNode(ISD::BIT_CONVERT,
583 MVT::getIntegerVT(ValueVT.getSizeInBits()),
585 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
586 for (unsigned i = 0; i < NumParts; i += StepSize) {
587 unsigned ThisBits = StepSize * PartBits / 2;
588 MVT ThisVT = MVT::getIntegerVT (ThisBits);
589 SDValue &Part0 = Parts[i];
590 SDValue &Part1 = Parts[i+StepSize/2];
592 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
593 DAG.getConstant(1, PtrVT));
594 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, ThisVT, Part0,
595 DAG.getConstant(0, PtrVT));
597 if (ThisBits == PartBits && ThisVT != PartVT) {
598 Part0 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part0);
599 Part1 = DAG.getNode(ISD::BIT_CONVERT, PartVT, Part1);
604 if (TLI.isBigEndian())
605 std::reverse(Parts, Parts + NumParts);
612 if (PartVT != ValueVT) {
613 if (PartVT.isVector()) {
614 Val = DAG.getNode(ISD::BIT_CONVERT, PartVT, Val);
616 assert(ValueVT.getVectorElementType() == PartVT &&
617 ValueVT.getVectorNumElements() == 1 &&
618 "Only trivial vector-to-scalar conversions should get here!");
619 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, PartVT, Val,
620 DAG.getConstant(0, PtrVT));
628 // Handle a multi-element vector.
629 MVT IntermediateVT, RegisterVT;
630 unsigned NumIntermediates;
632 DAG.getTargetLoweringInfo()
633 .getVectorTypeBreakdown(ValueVT, IntermediateVT, NumIntermediates,
635 unsigned NumElements = ValueVT.getVectorNumElements();
637 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
638 NumParts = NumRegs; // Silence a compiler warning.
639 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
641 // Split the vector into intermediate operands.
642 SmallVector<SDValue, 8> Ops(NumIntermediates);
643 for (unsigned i = 0; i != NumIntermediates; ++i)
644 if (IntermediateVT.isVector())
645 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR,
647 DAG.getConstant(i * (NumElements / NumIntermediates),
650 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
652 DAG.getConstant(i, PtrVT));
654 // Split the intermediate operands into legal parts.
655 if (NumParts == NumIntermediates) {
656 // If the register was not expanded, promote or copy the value,
658 for (unsigned i = 0; i != NumParts; ++i)
659 getCopyToParts(DAG, Ops[i], &Parts[i], 1, PartVT);
660 } else if (NumParts > 0) {
661 // If the intermediate type was expanded, split each the value into
663 assert(NumParts % NumIntermediates == 0 &&
664 "Must expand into a divisible number of parts!");
665 unsigned Factor = NumParts / NumIntermediates;
666 for (unsigned i = 0; i != NumIntermediates; ++i)
667 getCopyToParts(DAG, Ops[i], &Parts[i * Factor], Factor, PartVT);
672 void SelectionDAGLowering::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
675 TD = DAG.getTarget().getTargetData();
678 /// clear - Clear out the curret SelectionDAG and the associated
679 /// state and prepare this SelectionDAGLowering object to be used
680 /// for a new block. This doesn't clear out information about
681 /// additional blocks that are needed to complete switch lowering
682 /// or PHI node updating; that information is cleared out as it is
684 void SelectionDAGLowering::clear() {
686 PendingLoads.clear();
687 PendingExports.clear();
691 /// getRoot - Return the current virtual root of the Selection DAG,
692 /// flushing any PendingLoad items. This must be done before emitting
693 /// a store or any other node that may need to be ordered after any
694 /// prior load instructions.
696 SDValue SelectionDAGLowering::getRoot() {
697 if (PendingLoads.empty())
698 return DAG.getRoot();
700 if (PendingLoads.size() == 1) {
701 SDValue Root = PendingLoads[0];
703 PendingLoads.clear();
707 // Otherwise, we have to make a token factor node.
708 SDValue Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
709 &PendingLoads[0], PendingLoads.size());
710 PendingLoads.clear();
715 /// getControlRoot - Similar to getRoot, but instead of flushing all the
716 /// PendingLoad items, flush all the PendingExports items. It is necessary
717 /// to do this before emitting a terminator instruction.
719 SDValue SelectionDAGLowering::getControlRoot() {
720 SDValue Root = DAG.getRoot();
722 if (PendingExports.empty())
725 // Turn all of the CopyToReg chains into one factored node.
726 if (Root.getOpcode() != ISD::EntryToken) {
727 unsigned i = 0, e = PendingExports.size();
728 for (; i != e; ++i) {
729 assert(PendingExports[i].getNode()->getNumOperands() > 1);
730 if (PendingExports[i].getNode()->getOperand(0) == Root)
731 break; // Don't add the root if we already indirectly depend on it.
735 PendingExports.push_back(Root);
738 Root = DAG.getNode(ISD::TokenFactor, MVT::Other,
740 PendingExports.size());
741 PendingExports.clear();
746 void SelectionDAGLowering::visit(Instruction &I) {
747 visit(I.getOpcode(), I);
750 void SelectionDAGLowering::visit(unsigned Opcode, User &I) {
751 // Note: this doesn't use InstVisitor, because it has to work with
752 // ConstantExpr's in addition to instructions.
754 default: assert(0 && "Unknown instruction type encountered!");
756 // Build the switch statement using the Instruction.def file.
757 #define HANDLE_INST(NUM, OPCODE, CLASS) \
758 case Instruction::OPCODE:return visit##OPCODE((CLASS&)I);
759 #include "llvm/Instruction.def"
763 void SelectionDAGLowering::visitAdd(User &I) {
764 if (I.getType()->isFPOrFPVector())
765 visitBinary(I, ISD::FADD);
767 visitBinary(I, ISD::ADD);
770 void SelectionDAGLowering::visitMul(User &I) {
771 if (I.getType()->isFPOrFPVector())
772 visitBinary(I, ISD::FMUL);
774 visitBinary(I, ISD::MUL);
777 SDValue SelectionDAGLowering::getValue(const Value *V) {
778 SDValue &N = NodeMap[V];
779 if (N.getNode()) return N;
781 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
782 MVT VT = TLI.getValueType(V->getType(), true);
784 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
785 return N = DAG.getConstant(CI->getValue(), VT);
787 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
788 return N = DAG.getGlobalAddress(GV, VT);
790 if (isa<ConstantPointerNull>(C))
791 return N = DAG.getConstant(0, TLI.getPointerTy());
793 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
794 return N = DAG.getConstantFP(CFP->getValueAPF(), VT);
796 if (isa<UndefValue>(C) && !isa<VectorType>(V->getType()) &&
797 !V->getType()->isAggregateType())
798 return N = DAG.getNode(ISD::UNDEF, VT);
800 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
801 visit(CE->getOpcode(), *CE);
802 SDValue N1 = NodeMap[V];
803 assert(N1.getNode() && "visit didn't populate the ValueMap!");
807 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
808 SmallVector<SDValue, 4> Constants;
809 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
811 SDNode *Val = getValue(*OI).getNode();
812 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
813 Constants.push_back(SDValue(Val, i));
815 return DAG.getMergeValues(&Constants[0], Constants.size());
818 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
819 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
820 "Unknown struct or array constant!");
822 SmallVector<MVT, 4> ValueVTs;
823 ComputeValueVTs(TLI, C->getType(), ValueVTs);
824 unsigned NumElts = ValueVTs.size();
826 return SDValue(); // empty struct
827 SmallVector<SDValue, 4> Constants(NumElts);
828 for (unsigned i = 0; i != NumElts; ++i) {
829 MVT EltVT = ValueVTs[i];
830 if (isa<UndefValue>(C))
831 Constants[i] = DAG.getNode(ISD::UNDEF, EltVT);
832 else if (EltVT.isFloatingPoint())
833 Constants[i] = DAG.getConstantFP(0, EltVT);
835 Constants[i] = DAG.getConstant(0, EltVT);
837 return DAG.getMergeValues(&Constants[0], NumElts);
840 const VectorType *VecTy = cast<VectorType>(V->getType());
841 unsigned NumElements = VecTy->getNumElements();
843 // Now that we know the number and type of the elements, get that number of
844 // elements into the Ops array based on what kind of constant it is.
845 SmallVector<SDValue, 16> Ops;
846 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
847 for (unsigned i = 0; i != NumElements; ++i)
848 Ops.push_back(getValue(CP->getOperand(i)));
850 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
851 "Unknown vector constant!");
852 MVT EltVT = TLI.getValueType(VecTy->getElementType());
855 if (isa<UndefValue>(C))
856 Op = DAG.getNode(ISD::UNDEF, EltVT);
857 else if (EltVT.isFloatingPoint())
858 Op = DAG.getConstantFP(0, EltVT);
860 Op = DAG.getConstant(0, EltVT);
861 Ops.assign(NumElements, Op);
864 // Create a BUILD_VECTOR node.
865 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
868 // If this is a static alloca, generate it as the frameindex instead of
870 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
871 DenseMap<const AllocaInst*, int>::iterator SI =
872 FuncInfo.StaticAllocaMap.find(AI);
873 if (SI != FuncInfo.StaticAllocaMap.end())
874 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
877 unsigned InReg = FuncInfo.ValueMap[V];
878 assert(InReg && "Value not in map!");
880 RegsForValue RFV(TLI, InReg, V->getType());
881 SDValue Chain = DAG.getEntryNode();
882 return RFV.getCopyFromRegs(DAG, Chain, NULL);
886 void SelectionDAGLowering::visitRet(ReturnInst &I) {
887 if (I.getNumOperands() == 0) {
888 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other, getControlRoot()));
892 SmallVector<SDValue, 8> NewValues;
893 NewValues.push_back(getControlRoot());
894 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
895 SDValue RetOp = getValue(I.getOperand(i));
897 SmallVector<MVT, 4> ValueVTs;
898 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
899 for (unsigned j = 0, f = ValueVTs.size(); j != f; ++j) {
900 MVT VT = ValueVTs[j];
902 // FIXME: C calling convention requires the return type to be promoted to
903 // at least 32-bit. But this is not necessary for non-C calling conventions.
904 if (VT.isInteger()) {
905 MVT MinVT = TLI.getRegisterType(MVT::i32);
906 if (VT.bitsLT(MinVT))
910 unsigned NumParts = TLI.getNumRegisters(VT);
911 MVT PartVT = TLI.getRegisterType(VT);
912 SmallVector<SDValue, 4> Parts(NumParts);
913 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
915 const Function *F = I.getParent()->getParent();
916 if (F->paramHasAttr(0, ParamAttr::SExt))
917 ExtendKind = ISD::SIGN_EXTEND;
918 else if (F->paramHasAttr(0, ParamAttr::ZExt))
919 ExtendKind = ISD::ZERO_EXTEND;
921 getCopyToParts(DAG, SDValue(RetOp.getNode(), RetOp.getResNo() + j),
922 &Parts[0], NumParts, PartVT, ExtendKind);
924 for (unsigned i = 0; i < NumParts; ++i) {
925 NewValues.push_back(Parts[i]);
926 NewValues.push_back(DAG.getArgFlags(ISD::ArgFlagsTy()));
930 DAG.setRoot(DAG.getNode(ISD::RET, MVT::Other,
931 &NewValues[0], NewValues.size()));
934 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
935 /// the current basic block, add it to ValueMap now so that we'll get a
937 void SelectionDAGLowering::ExportFromCurrentBlock(Value *V) {
938 // No need to export constants.
939 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
942 if (FuncInfo.isExportedInst(V)) return;
944 unsigned Reg = FuncInfo.InitializeRegForValue(V);
945 CopyValueToVirtualRegister(V, Reg);
948 bool SelectionDAGLowering::isExportableFromCurrentBlock(Value *V,
949 const BasicBlock *FromBB) {
950 // The operands of the setcc have to be in this block. We don't know
951 // how to export them from some other block.
952 if (Instruction *VI = dyn_cast<Instruction>(V)) {
953 // Can export from current BB.
954 if (VI->getParent() == FromBB)
957 // Is already exported, noop.
958 return FuncInfo.isExportedInst(V);
961 // If this is an argument, we can export it if the BB is the entry block or
962 // if it is already exported.
963 if (isa<Argument>(V)) {
964 if (FromBB == &FromBB->getParent()->getEntryBlock())
967 // Otherwise, can only export this if it is already exported.
968 return FuncInfo.isExportedInst(V);
971 // Otherwise, constants can always be exported.
975 static bool InBlock(const Value *V, const BasicBlock *BB) {
976 if (const Instruction *I = dyn_cast<Instruction>(V))
977 return I->getParent() == BB;
981 /// FindMergedConditions - If Cond is an expression like
982 void SelectionDAGLowering::FindMergedConditions(Value *Cond,
983 MachineBasicBlock *TBB,
984 MachineBasicBlock *FBB,
985 MachineBasicBlock *CurBB,
987 // If this node is not part of the or/and tree, emit it as a branch.
988 Instruction *BOp = dyn_cast<Instruction>(Cond);
990 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
991 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
992 BOp->getParent() != CurBB->getBasicBlock() ||
993 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
994 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
995 const BasicBlock *BB = CurBB->getBasicBlock();
997 // If the leaf of the tree is a comparison, merge the condition into
999 if ((isa<ICmpInst>(Cond) || isa<FCmpInst>(Cond)) &&
1000 // The operands of the cmp have to be in this block. We don't know
1001 // how to export them from some other block. If this is the first block
1002 // of the sequence, no exporting is needed.
1004 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1005 isExportableFromCurrentBlock(BOp->getOperand(1), BB)))) {
1006 BOp = cast<Instruction>(Cond);
1007 ISD::CondCode Condition;
1008 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1009 switch (IC->getPredicate()) {
1010 default: assert(0 && "Unknown icmp predicate opcode!");
1011 case ICmpInst::ICMP_EQ: Condition = ISD::SETEQ; break;
1012 case ICmpInst::ICMP_NE: Condition = ISD::SETNE; break;
1013 case ICmpInst::ICMP_SLE: Condition = ISD::SETLE; break;
1014 case ICmpInst::ICMP_ULE: Condition = ISD::SETULE; break;
1015 case ICmpInst::ICMP_SGE: Condition = ISD::SETGE; break;
1016 case ICmpInst::ICMP_UGE: Condition = ISD::SETUGE; break;
1017 case ICmpInst::ICMP_SLT: Condition = ISD::SETLT; break;
1018 case ICmpInst::ICMP_ULT: Condition = ISD::SETULT; break;
1019 case ICmpInst::ICMP_SGT: Condition = ISD::SETGT; break;
1020 case ICmpInst::ICMP_UGT: Condition = ISD::SETUGT; break;
1022 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1023 ISD::CondCode FPC, FOC;
1024 switch (FC->getPredicate()) {
1025 default: assert(0 && "Unknown fcmp predicate opcode!");
1026 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
1027 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
1028 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
1029 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
1030 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
1031 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
1032 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
1033 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
1034 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
1035 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
1036 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
1037 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
1038 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
1039 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
1040 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
1041 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
1043 if (FiniteOnlyFPMath())
1048 Condition = ISD::SETEQ; // silence warning.
1049 assert(0 && "Unknown compare instruction");
1052 CaseBlock CB(Condition, BOp->getOperand(0),
1053 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1054 SwitchCases.push_back(CB);
1058 // Create a CaseBlock record representing this branch.
1059 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(),
1060 NULL, TBB, FBB, CurBB);
1061 SwitchCases.push_back(CB);
1066 // Create TmpBB after CurBB.
1067 MachineFunction::iterator BBI = CurBB;
1068 MachineFunction &MF = DAG.getMachineFunction();
1069 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1070 CurBB->getParent()->insert(++BBI, TmpBB);
1072 if (Opc == Instruction::Or) {
1073 // Codegen X | Y as:
1081 // Emit the LHS condition.
1082 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1084 // Emit the RHS condition into TmpBB.
1085 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1087 assert(Opc == Instruction::And && "Unknown merge op!");
1088 // Codegen X & Y as:
1095 // This requires creation of TmpBB after CurBB.
1097 // Emit the LHS condition.
1098 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1100 // Emit the RHS condition into TmpBB.
1101 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1105 /// If the set of cases should be emitted as a series of branches, return true.
1106 /// If we should emit this as a bunch of and/or'd together conditions, return
1109 SelectionDAGLowering::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1110 if (Cases.size() != 2) return true;
1112 // If this is two comparisons of the same values or'd or and'd together, they
1113 // will get folded into a single comparison, so don't emit two blocks.
1114 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1115 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1116 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1117 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1124 void SelectionDAGLowering::visitBr(BranchInst &I) {
1125 // Update machine-CFG edges.
1126 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1128 // Figure out which block is immediately after the current one.
1129 MachineBasicBlock *NextBlock = 0;
1130 MachineFunction::iterator BBI = CurMBB;
1131 if (++BBI != CurMBB->getParent()->end())
1134 if (I.isUnconditional()) {
1135 // Update machine-CFG edges.
1136 CurMBB->addSuccessor(Succ0MBB);
1138 // If this is not a fall-through branch, emit the branch.
1139 if (Succ0MBB != NextBlock)
1140 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1141 DAG.getBasicBlock(Succ0MBB)));
1145 // If this condition is one of the special cases we handle, do special stuff
1147 Value *CondVal = I.getCondition();
1148 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1150 // If this is a series of conditions that are or'd or and'd together, emit
1151 // this as a sequence of branches instead of setcc's with and/or operations.
1152 // For example, instead of something like:
1165 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1166 if (BOp->hasOneUse() &&
1167 (BOp->getOpcode() == Instruction::And ||
1168 BOp->getOpcode() == Instruction::Or)) {
1169 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1170 // If the compares in later blocks need to use values not currently
1171 // exported from this block, export them now. This block should always
1172 // be the first entry.
1173 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1175 // Allow some cases to be rejected.
1176 if (ShouldEmitAsBranches(SwitchCases)) {
1177 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1178 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1179 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1182 // Emit the branch for this block.
1183 visitSwitchCase(SwitchCases[0]);
1184 SwitchCases.erase(SwitchCases.begin());
1188 // Okay, we decided not to do this, remove any inserted MBB's and clear
1190 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1191 CurMBB->getParent()->erase(SwitchCases[i].ThisBB);
1193 SwitchCases.clear();
1197 // Create a CaseBlock record representing this branch.
1198 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(),
1199 NULL, Succ0MBB, Succ1MBB, CurMBB);
1200 // Use visitSwitchCase to actually insert the fast branch sequence for this
1202 visitSwitchCase(CB);
1205 /// visitSwitchCase - Emits the necessary code to represent a single node in
1206 /// the binary search tree resulting from lowering a switch instruction.
1207 void SelectionDAGLowering::visitSwitchCase(CaseBlock &CB) {
1209 SDValue CondLHS = getValue(CB.CmpLHS);
1211 // Build the setcc now.
1212 if (CB.CmpMHS == NULL) {
1213 // Fold "(X == true)" to X and "(X == false)" to !X to
1214 // handle common cases produced by branch lowering.
1215 if (CB.CmpRHS == ConstantInt::getTrue() && CB.CC == ISD::SETEQ)
1217 else if (CB.CmpRHS == ConstantInt::getFalse() && CB.CC == ISD::SETEQ) {
1218 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1219 Cond = DAG.getNode(ISD::XOR, CondLHS.getValueType(), CondLHS, True);
1221 Cond = DAG.getSetCC(MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1223 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1225 uint64_t Low = cast<ConstantInt>(CB.CmpLHS)->getSExtValue();
1226 uint64_t High = cast<ConstantInt>(CB.CmpRHS)->getSExtValue();
1228 SDValue CmpOp = getValue(CB.CmpMHS);
1229 MVT VT = CmpOp.getValueType();
1231 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1232 Cond = DAG.getSetCC(MVT::i1, CmpOp, DAG.getConstant(High, VT), ISD::SETLE);
1234 SDValue SUB = DAG.getNode(ISD::SUB, VT, CmpOp, DAG.getConstant(Low, VT));
1235 Cond = DAG.getSetCC(MVT::i1, SUB,
1236 DAG.getConstant(High-Low, VT), ISD::SETULE);
1240 // Update successor info
1241 CurMBB->addSuccessor(CB.TrueBB);
1242 CurMBB->addSuccessor(CB.FalseBB);
1244 // Set NextBlock to be the MBB immediately after the current one, if any.
1245 // This is used to avoid emitting unnecessary branches to the next block.
1246 MachineBasicBlock *NextBlock = 0;
1247 MachineFunction::iterator BBI = CurMBB;
1248 if (++BBI != CurMBB->getParent()->end())
1251 // If the lhs block is the next block, invert the condition so that we can
1252 // fall through to the lhs instead of the rhs block.
1253 if (CB.TrueBB == NextBlock) {
1254 std::swap(CB.TrueBB, CB.FalseBB);
1255 SDValue True = DAG.getConstant(1, Cond.getValueType());
1256 Cond = DAG.getNode(ISD::XOR, Cond.getValueType(), Cond, True);
1258 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(), Cond,
1259 DAG.getBasicBlock(CB.TrueBB));
1261 // If the branch was constant folded, fix up the CFG.
1262 if (BrCond.getOpcode() == ISD::BR) {
1263 CurMBB->removeSuccessor(CB.FalseBB);
1264 DAG.setRoot(BrCond);
1266 // Otherwise, go ahead and insert the false branch.
1267 if (BrCond == getControlRoot())
1268 CurMBB->removeSuccessor(CB.TrueBB);
1270 if (CB.FalseBB == NextBlock)
1271 DAG.setRoot(BrCond);
1273 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1274 DAG.getBasicBlock(CB.FalseBB)));
1278 /// visitJumpTable - Emit JumpTable node in the current MBB
1279 void SelectionDAGLowering::visitJumpTable(JumpTable &JT) {
1280 // Emit the code for the jump table
1281 assert(JT.Reg != -1U && "Should lower JT Header first!");
1282 MVT PTy = TLI.getPointerTy();
1283 SDValue Index = DAG.getCopyFromReg(getControlRoot(), JT.Reg, PTy);
1284 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1285 DAG.setRoot(DAG.getNode(ISD::BR_JT, MVT::Other, Index.getValue(1),
1290 /// visitJumpTableHeader - This function emits necessary code to produce index
1291 /// in the JumpTable from switch case.
1292 void SelectionDAGLowering::visitJumpTableHeader(JumpTable &JT,
1293 JumpTableHeader &JTH) {
1294 // Subtract the lowest switch case value from the value being switched on
1295 // and conditional branch to default mbb if the result is greater than the
1296 // difference between smallest and largest cases.
1297 SDValue SwitchOp = getValue(JTH.SValue);
1298 MVT VT = SwitchOp.getValueType();
1299 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1300 DAG.getConstant(JTH.First, VT));
1302 // The SDNode we just created, which holds the value being switched on
1303 // minus the the smallest case value, needs to be copied to a virtual
1304 // register so it can be used as an index into the jump table in a
1305 // subsequent basic block. This value may be smaller or larger than the
1306 // target's pointer type, and therefore require extension or truncating.
1307 if (VT.bitsGT(TLI.getPointerTy()))
1308 SwitchOp = DAG.getNode(ISD::TRUNCATE, TLI.getPointerTy(), SUB);
1310 SwitchOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(), SUB);
1312 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1313 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), JumpTableReg, SwitchOp);
1314 JT.Reg = JumpTableReg;
1316 // Emit the range check for the jump table, and branch to the default
1317 // block for the switch statement if the value being switched on exceeds
1318 // the largest case in the switch.
1319 SDValue CMP = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1320 DAG.getConstant(JTH.Last-JTH.First,VT),
1323 // Set NextBlock to be the MBB immediately after the current one, if any.
1324 // This is used to avoid emitting unnecessary branches to the next block.
1325 MachineBasicBlock *NextBlock = 0;
1326 MachineFunction::iterator BBI = CurMBB;
1327 if (++BBI != CurMBB->getParent()->end())
1330 SDValue BrCond = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, CMP,
1331 DAG.getBasicBlock(JT.Default));
1333 if (JT.MBB == NextBlock)
1334 DAG.setRoot(BrCond);
1336 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrCond,
1337 DAG.getBasicBlock(JT.MBB)));
1342 /// visitBitTestHeader - This function emits necessary code to produce value
1343 /// suitable for "bit tests"
1344 void SelectionDAGLowering::visitBitTestHeader(BitTestBlock &B) {
1345 // Subtract the minimum value
1346 SDValue SwitchOp = getValue(B.SValue);
1347 MVT VT = SwitchOp.getValueType();
1348 SDValue SUB = DAG.getNode(ISD::SUB, VT, SwitchOp,
1349 DAG.getConstant(B.First, VT));
1352 SDValue RangeCmp = DAG.getSetCC(TLI.getSetCCResultType(SUB), SUB,
1353 DAG.getConstant(B.Range, VT),
1357 if (VT.bitsGT(TLI.getShiftAmountTy()))
1358 ShiftOp = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), SUB);
1360 ShiftOp = DAG.getNode(ISD::ZERO_EXTEND, TLI.getShiftAmountTy(), SUB);
1362 // Make desired shift
1363 SDValue SwitchVal = DAG.getNode(ISD::SHL, TLI.getPointerTy(),
1364 DAG.getConstant(1, TLI.getPointerTy()),
1367 unsigned SwitchReg = FuncInfo.MakeReg(TLI.getPointerTy());
1368 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), SwitchReg, SwitchVal);
1371 // Set NextBlock to be the MBB immediately after the current one, if any.
1372 // This is used to avoid emitting unnecessary branches to the next block.
1373 MachineBasicBlock *NextBlock = 0;
1374 MachineFunction::iterator BBI = CurMBB;
1375 if (++BBI != CurMBB->getParent()->end())
1378 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1380 CurMBB->addSuccessor(B.Default);
1381 CurMBB->addSuccessor(MBB);
1383 SDValue BrRange = DAG.getNode(ISD::BRCOND, MVT::Other, CopyTo, RangeCmp,
1384 DAG.getBasicBlock(B.Default));
1386 if (MBB == NextBlock)
1387 DAG.setRoot(BrRange);
1389 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, CopyTo,
1390 DAG.getBasicBlock(MBB)));
1395 /// visitBitTestCase - this function produces one "bit test"
1396 void SelectionDAGLowering::visitBitTestCase(MachineBasicBlock* NextMBB,
1399 // Emit bit tests and jumps
1400 SDValue SwitchVal = DAG.getCopyFromReg(getControlRoot(), Reg,
1401 TLI.getPointerTy());
1403 SDValue AndOp = DAG.getNode(ISD::AND, TLI.getPointerTy(), SwitchVal,
1404 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1405 SDValue AndCmp = DAG.getSetCC(TLI.getSetCCResultType(AndOp), AndOp,
1406 DAG.getConstant(0, TLI.getPointerTy()),
1409 CurMBB->addSuccessor(B.TargetBB);
1410 CurMBB->addSuccessor(NextMBB);
1412 SDValue BrAnd = DAG.getNode(ISD::BRCOND, MVT::Other, getControlRoot(),
1413 AndCmp, DAG.getBasicBlock(B.TargetBB));
1415 // Set NextBlock to be the MBB immediately after the current one, if any.
1416 // This is used to avoid emitting unnecessary branches to the next block.
1417 MachineBasicBlock *NextBlock = 0;
1418 MachineFunction::iterator BBI = CurMBB;
1419 if (++BBI != CurMBB->getParent()->end())
1422 if (NextMBB == NextBlock)
1425 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, BrAnd,
1426 DAG.getBasicBlock(NextMBB)));
1431 void SelectionDAGLowering::visitInvoke(InvokeInst &I) {
1432 // Retrieve successors.
1433 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1434 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1436 if (isa<InlineAsm>(I.getCalledValue()))
1439 LowerCallTo(&I, getValue(I.getOperand(0)), false, LandingPad);
1441 // If the value of the invoke is used outside of its defining block, make it
1442 // available as a virtual register.
1443 if (!I.use_empty()) {
1444 DenseMap<const Value*, unsigned>::iterator VMI = FuncInfo.ValueMap.find(&I);
1445 if (VMI != FuncInfo.ValueMap.end())
1446 CopyValueToVirtualRegister(&I, VMI->second);
1449 // Update successor info
1450 CurMBB->addSuccessor(Return);
1451 CurMBB->addSuccessor(LandingPad);
1453 // Drop into normal successor.
1454 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1455 DAG.getBasicBlock(Return)));
1458 void SelectionDAGLowering::visitUnwind(UnwindInst &I) {
1461 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1462 /// small case ranges).
1463 bool SelectionDAGLowering::handleSmallSwitchRange(CaseRec& CR,
1464 CaseRecVector& WorkList,
1466 MachineBasicBlock* Default) {
1467 Case& BackCase = *(CR.Range.second-1);
1469 // Size is the number of Cases represented by this range.
1470 unsigned Size = CR.Range.second - CR.Range.first;
1474 // Get the MachineFunction which holds the current MBB. This is used when
1475 // inserting any additional MBBs necessary to represent the switch.
1476 MachineFunction *CurMF = CurMBB->getParent();
1478 // Figure out which block is immediately after the current one.
1479 MachineBasicBlock *NextBlock = 0;
1480 MachineFunction::iterator BBI = CR.CaseBB;
1482 if (++BBI != CurMBB->getParent()->end())
1485 // TODO: If any two of the cases has the same destination, and if one value
1486 // is the same as the other, but has one bit unset that the other has set,
1487 // use bit manipulation to do two compares at once. For example:
1488 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1490 // Rearrange the case blocks so that the last one falls through if possible.
1491 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1492 // The last case block won't fall through into 'NextBlock' if we emit the
1493 // branches in this order. See if rearranging a case value would help.
1494 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1495 if (I->BB == NextBlock) {
1496 std::swap(*I, BackCase);
1502 // Create a CaseBlock record representing a conditional branch to
1503 // the Case's target mbb if the value being switched on SV is equal
1505 MachineBasicBlock *CurBlock = CR.CaseBB;
1506 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1507 MachineBasicBlock *FallThrough;
1509 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1510 CurMF->insert(BBI, FallThrough);
1512 // If the last case doesn't match, go to the default block.
1513 FallThrough = Default;
1516 Value *RHS, *LHS, *MHS;
1518 if (I->High == I->Low) {
1519 // This is just small small case range :) containing exactly 1 case
1521 LHS = SV; RHS = I->High; MHS = NULL;
1524 LHS = I->Low; MHS = SV; RHS = I->High;
1526 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1528 // If emitting the first comparison, just call visitSwitchCase to emit the
1529 // code into the current block. Otherwise, push the CaseBlock onto the
1530 // vector to be later processed by SDISel, and insert the node's MBB
1531 // before the next MBB.
1532 if (CurBlock == CurMBB)
1533 visitSwitchCase(CB);
1535 SwitchCases.push_back(CB);
1537 CurBlock = FallThrough;
1543 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1544 return !DisableJumpTables &&
1545 (TLI.isOperationLegal(ISD::BR_JT, MVT::Other) ||
1546 TLI.isOperationLegal(ISD::BRIND, MVT::Other));
1549 /// handleJTSwitchCase - Emit jumptable for current switch case range
1550 bool SelectionDAGLowering::handleJTSwitchCase(CaseRec& CR,
1551 CaseRecVector& WorkList,
1553 MachineBasicBlock* Default) {
1554 Case& FrontCase = *CR.Range.first;
1555 Case& BackCase = *(CR.Range.second-1);
1557 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1558 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1561 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1565 if (!areJTsAllowed(TLI) || TSize <= 3)
1568 double Density = (double)TSize / (double)((Last - First) + 1ULL);
1572 DOUT << "Lowering jump table\n"
1573 << "First entry: " << First << ". Last entry: " << Last << "\n"
1574 << "Size: " << TSize << ". Density: " << Density << "\n\n";
1576 // Get the MachineFunction which holds the current MBB. This is used when
1577 // inserting any additional MBBs necessary to represent the switch.
1578 MachineFunction *CurMF = CurMBB->getParent();
1580 // Figure out which block is immediately after the current one.
1581 MachineBasicBlock *NextBlock = 0;
1582 MachineFunction::iterator BBI = CR.CaseBB;
1584 if (++BBI != CurMBB->getParent()->end())
1587 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1589 // Create a new basic block to hold the code for loading the address
1590 // of the jump table, and jumping to it. Update successor information;
1591 // we will either branch to the default case for the switch, or the jump
1593 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1594 CurMF->insert(BBI, JumpTableBB);
1595 CR.CaseBB->addSuccessor(Default);
1596 CR.CaseBB->addSuccessor(JumpTableBB);
1598 // Build a vector of destination BBs, corresponding to each target
1599 // of the jump table. If the value of the jump table slot corresponds to
1600 // a case statement, push the case's BB onto the vector, otherwise, push
1602 std::vector<MachineBasicBlock*> DestBBs;
1603 int64_t TEI = First;
1604 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1605 int64_t Low = cast<ConstantInt>(I->Low)->getSExtValue();
1606 int64_t High = cast<ConstantInt>(I->High)->getSExtValue();
1608 if ((Low <= TEI) && (TEI <= High)) {
1609 DestBBs.push_back(I->BB);
1613 DestBBs.push_back(Default);
1617 // Update successor info. Add one edge to each unique successor.
1618 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1619 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1620 E = DestBBs.end(); I != E; ++I) {
1621 if (!SuccsHandled[(*I)->getNumber()]) {
1622 SuccsHandled[(*I)->getNumber()] = true;
1623 JumpTableBB->addSuccessor(*I);
1627 // Create a jump table index for this jump table, or return an existing
1629 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1631 // Set the jump table information so that we can codegen it as a second
1632 // MachineBasicBlock
1633 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1634 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1635 if (CR.CaseBB == CurMBB)
1636 visitJumpTableHeader(JT, JTH);
1638 JTCases.push_back(JumpTableBlock(JTH, JT));
1643 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1645 bool SelectionDAGLowering::handleBTSplitSwitchCase(CaseRec& CR,
1646 CaseRecVector& WorkList,
1648 MachineBasicBlock* Default) {
1649 // Get the MachineFunction which holds the current MBB. This is used when
1650 // inserting any additional MBBs necessary to represent the switch.
1651 MachineFunction *CurMF = CurMBB->getParent();
1653 // Figure out which block is immediately after the current one.
1654 MachineBasicBlock *NextBlock = 0;
1655 MachineFunction::iterator BBI = CR.CaseBB;
1657 if (++BBI != CurMBB->getParent()->end())
1660 Case& FrontCase = *CR.Range.first;
1661 Case& BackCase = *(CR.Range.second-1);
1662 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1664 // Size is the number of Cases represented by this range.
1665 unsigned Size = CR.Range.second - CR.Range.first;
1667 int64_t First = cast<ConstantInt>(FrontCase.Low)->getSExtValue();
1668 int64_t Last = cast<ConstantInt>(BackCase.High)->getSExtValue();
1670 CaseItr Pivot = CR.Range.first + Size/2;
1672 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1673 // (heuristically) allow us to emit JumpTable's later.
1675 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1679 uint64_t LSize = FrontCase.size();
1680 uint64_t RSize = TSize-LSize;
1681 DOUT << "Selecting best pivot: \n"
1682 << "First: " << First << ", Last: " << Last <<"\n"
1683 << "LSize: " << LSize << ", RSize: " << RSize << "\n";
1684 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1686 int64_t LEnd = cast<ConstantInt>(I->High)->getSExtValue();
1687 int64_t RBegin = cast<ConstantInt>(J->Low)->getSExtValue();
1688 assert((RBegin-LEnd>=1) && "Invalid case distance");
1689 double LDensity = (double)LSize / (double)((LEnd - First) + 1ULL);
1690 double RDensity = (double)RSize / (double)((Last - RBegin) + 1ULL);
1691 double Metric = Log2_64(RBegin-LEnd)*(LDensity+RDensity);
1692 // Should always split in some non-trivial place
1694 << "LEnd: " << LEnd << ", RBegin: " << RBegin << "\n"
1695 << "LDensity: " << LDensity << ", RDensity: " << RDensity << "\n"
1696 << "Metric: " << Metric << "\n";
1697 if (FMetric < Metric) {
1700 DOUT << "Current metric set to: " << FMetric << "\n";
1706 if (areJTsAllowed(TLI)) {
1707 // If our case is dense we *really* should handle it earlier!
1708 assert((FMetric > 0) && "Should handle dense range earlier!");
1710 Pivot = CR.Range.first + Size/2;
1713 CaseRange LHSR(CR.Range.first, Pivot);
1714 CaseRange RHSR(Pivot, CR.Range.second);
1715 Constant *C = Pivot->Low;
1716 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1718 // We know that we branch to the LHS if the Value being switched on is
1719 // less than the Pivot value, C. We use this to optimize our binary
1720 // tree a bit, by recognizing that if SV is greater than or equal to the
1721 // LHS's Case Value, and that Case Value is exactly one less than the
1722 // Pivot's Value, then we can branch directly to the LHS's Target,
1723 // rather than creating a leaf node for it.
1724 if ((LHSR.second - LHSR.first) == 1 &&
1725 LHSR.first->High == CR.GE &&
1726 cast<ConstantInt>(C)->getSExtValue() ==
1727 (cast<ConstantInt>(CR.GE)->getSExtValue() + 1LL)) {
1728 TrueBB = LHSR.first->BB;
1730 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1731 CurMF->insert(BBI, TrueBB);
1732 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1735 // Similar to the optimization above, if the Value being switched on is
1736 // known to be less than the Constant CR.LT, and the current Case Value
1737 // is CR.LT - 1, then we can branch directly to the target block for
1738 // the current Case Value, rather than emitting a RHS leaf node for it.
1739 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1740 cast<ConstantInt>(RHSR.first->Low)->getSExtValue() ==
1741 (cast<ConstantInt>(CR.LT)->getSExtValue() - 1LL)) {
1742 FalseBB = RHSR.first->BB;
1744 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1745 CurMF->insert(BBI, FalseBB);
1746 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1749 // Create a CaseBlock record representing a conditional branch to
1750 // the LHS node if the value being switched on SV is less than C.
1751 // Otherwise, branch to LHS.
1752 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1754 if (CR.CaseBB == CurMBB)
1755 visitSwitchCase(CB);
1757 SwitchCases.push_back(CB);
1762 /// handleBitTestsSwitchCase - if current case range has few destination and
1763 /// range span less, than machine word bitwidth, encode case range into series
1764 /// of masks and emit bit tests with these masks.
1765 bool SelectionDAGLowering::handleBitTestsSwitchCase(CaseRec& CR,
1766 CaseRecVector& WorkList,
1768 MachineBasicBlock* Default){
1769 unsigned IntPtrBits = TLI.getPointerTy().getSizeInBits();
1771 Case& FrontCase = *CR.Range.first;
1772 Case& BackCase = *(CR.Range.second-1);
1774 // Get the MachineFunction which holds the current MBB. This is used when
1775 // inserting any additional MBBs necessary to represent the switch.
1776 MachineFunction *CurMF = CurMBB->getParent();
1778 unsigned numCmps = 0;
1779 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1781 // Single case counts one, case range - two.
1782 if (I->Low == I->High)
1788 // Count unique destinations
1789 SmallSet<MachineBasicBlock*, 4> Dests;
1790 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1791 Dests.insert(I->BB);
1792 if (Dests.size() > 3)
1793 // Don't bother the code below, if there are too much unique destinations
1796 DOUT << "Total number of unique destinations: " << Dests.size() << "\n"
1797 << "Total number of comparisons: " << numCmps << "\n";
1799 // Compute span of values.
1800 Constant* minValue = FrontCase.Low;
1801 Constant* maxValue = BackCase.High;
1802 uint64_t range = cast<ConstantInt>(maxValue)->getSExtValue() -
1803 cast<ConstantInt>(minValue)->getSExtValue();
1804 DOUT << "Compare range: " << range << "\n"
1805 << "Low bound: " << cast<ConstantInt>(minValue)->getSExtValue() << "\n"
1806 << "High bound: " << cast<ConstantInt>(maxValue)->getSExtValue() << "\n";
1808 if (range>=IntPtrBits ||
1809 (!(Dests.size() == 1 && numCmps >= 3) &&
1810 !(Dests.size() == 2 && numCmps >= 5) &&
1811 !(Dests.size() >= 3 && numCmps >= 6)))
1814 DOUT << "Emitting bit tests\n";
1815 int64_t lowBound = 0;
1817 // Optimize the case where all the case values fit in a
1818 // word without having to subtract minValue. In this case,
1819 // we can optimize away the subtraction.
1820 if (cast<ConstantInt>(minValue)->getSExtValue() >= 0 &&
1821 cast<ConstantInt>(maxValue)->getSExtValue() < IntPtrBits) {
1822 range = cast<ConstantInt>(maxValue)->getSExtValue();
1824 lowBound = cast<ConstantInt>(minValue)->getSExtValue();
1827 CaseBitsVector CasesBits;
1828 unsigned i, count = 0;
1830 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1831 MachineBasicBlock* Dest = I->BB;
1832 for (i = 0; i < count; ++i)
1833 if (Dest == CasesBits[i].BB)
1837 assert((count < 3) && "Too much destinations to test!");
1838 CasesBits.push_back(CaseBits(0, Dest, 0));
1842 uint64_t lo = cast<ConstantInt>(I->Low)->getSExtValue() - lowBound;
1843 uint64_t hi = cast<ConstantInt>(I->High)->getSExtValue() - lowBound;
1845 for (uint64_t j = lo; j <= hi; j++) {
1846 CasesBits[i].Mask |= 1ULL << j;
1847 CasesBits[i].Bits++;
1851 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1855 // Figure out which block is immediately after the current one.
1856 MachineFunction::iterator BBI = CR.CaseBB;
1859 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1862 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1863 DOUT << "Mask: " << CasesBits[i].Mask << ", Bits: " << CasesBits[i].Bits
1864 << ", BB: " << CasesBits[i].BB << "\n";
1866 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1867 CurMF->insert(BBI, CaseBB);
1868 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1873 BitTestBlock BTB(lowBound, range, SV,
1874 -1U, (CR.CaseBB == CurMBB),
1875 CR.CaseBB, Default, BTC);
1877 if (CR.CaseBB == CurMBB)
1878 visitBitTestHeader(BTB);
1880 BitTestCases.push_back(BTB);
1886 /// Clusterify - Transform simple list of Cases into list of CaseRange's
1887 unsigned SelectionDAGLowering::Clusterify(CaseVector& Cases,
1888 const SwitchInst& SI) {
1889 unsigned numCmps = 0;
1891 // Start with "simple" cases
1892 for (unsigned i = 1; i < SI.getNumSuccessors(); ++i) {
1893 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1894 Cases.push_back(Case(SI.getSuccessorValue(i),
1895 SI.getSuccessorValue(i),
1898 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1900 // Merge case into clusters
1901 if (Cases.size()>=2)
1902 // Must recompute end() each iteration because it may be
1903 // invalidated by erase if we hold on to it
1904 for (CaseItr I=Cases.begin(), J=++(Cases.begin()); J!=Cases.end(); ) {
1905 int64_t nextValue = cast<ConstantInt>(J->Low)->getSExtValue();
1906 int64_t currentValue = cast<ConstantInt>(I->High)->getSExtValue();
1907 MachineBasicBlock* nextBB = J->BB;
1908 MachineBasicBlock* currentBB = I->BB;
1910 // If the two neighboring cases go to the same destination, merge them
1911 // into a single case.
1912 if ((nextValue-currentValue==1) && (currentBB == nextBB)) {
1920 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1921 if (I->Low != I->High)
1922 // A range counts double, since it requires two compares.
1929 void SelectionDAGLowering::visitSwitch(SwitchInst &SI) {
1930 // Figure out which block is immediately after the current one.
1931 MachineBasicBlock *NextBlock = 0;
1932 MachineFunction::iterator BBI = CurMBB;
1934 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1936 // If there is only the default destination, branch to it if it is not the
1937 // next basic block. Otherwise, just fall through.
1938 if (SI.getNumOperands() == 2) {
1939 // Update machine-CFG edges.
1941 // If this is not a fall-through branch, emit the branch.
1942 CurMBB->addSuccessor(Default);
1943 if (Default != NextBlock)
1944 DAG.setRoot(DAG.getNode(ISD::BR, MVT::Other, getControlRoot(),
1945 DAG.getBasicBlock(Default)));
1950 // If there are any non-default case statements, create a vector of Cases
1951 // representing each one, and sort the vector so that we can efficiently
1952 // create a binary search tree from them.
1954 unsigned numCmps = Clusterify(Cases, SI);
1955 DOUT << "Clusterify finished. Total clusters: " << Cases.size()
1956 << ". Total compares: " << numCmps << "\n";
1958 // Get the Value to be switched on and default basic blocks, which will be
1959 // inserted into CaseBlock records, representing basic blocks in the binary
1961 Value *SV = SI.getOperand(0);
1963 // Push the initial CaseRec onto the worklist
1964 CaseRecVector WorkList;
1965 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
1967 while (!WorkList.empty()) {
1968 // Grab a record representing a case range to process off the worklist
1969 CaseRec CR = WorkList.back();
1970 WorkList.pop_back();
1972 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
1975 // If the range has few cases (two or less) emit a series of specific
1977 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
1980 // If the switch has more than 5 blocks, and at least 40% dense, and the
1981 // target supports indirect branches, then emit a jump table rather than
1982 // lowering the switch to a binary tree of conditional branches.
1983 if (handleJTSwitchCase(CR, WorkList, SV, Default))
1986 // Emit binary tree. We need to pick a pivot, and push left and right ranges
1987 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
1988 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
1993 void SelectionDAGLowering::visitSub(User &I) {
1994 // -0.0 - X --> fneg
1995 const Type *Ty = I.getType();
1996 if (isa<VectorType>(Ty)) {
1997 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
1998 const VectorType *DestTy = cast<VectorType>(I.getType());
1999 const Type *ElTy = DestTy->getElementType();
2000 if (ElTy->isFloatingPoint()) {
2001 unsigned VL = DestTy->getNumElements();
2002 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2003 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2005 SDValue Op2 = getValue(I.getOperand(1));
2006 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2012 if (Ty->isFloatingPoint()) {
2013 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2014 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2015 SDValue Op2 = getValue(I.getOperand(1));
2016 setValue(&I, DAG.getNode(ISD::FNEG, Op2.getValueType(), Op2));
2021 visitBinary(I, Ty->isFPOrFPVector() ? ISD::FSUB : ISD::SUB);
2024 void SelectionDAGLowering::visitBinary(User &I, unsigned OpCode) {
2025 SDValue Op1 = getValue(I.getOperand(0));
2026 SDValue Op2 = getValue(I.getOperand(1));
2028 setValue(&I, DAG.getNode(OpCode, Op1.getValueType(), Op1, Op2));
2031 void SelectionDAGLowering::visitShift(User &I, unsigned Opcode) {
2032 SDValue Op1 = getValue(I.getOperand(0));
2033 SDValue Op2 = getValue(I.getOperand(1));
2034 if (!isa<VectorType>(I.getType())) {
2035 if (TLI.getShiftAmountTy().bitsLT(Op2.getValueType()))
2036 Op2 = DAG.getNode(ISD::TRUNCATE, TLI.getShiftAmountTy(), Op2);
2037 else if (TLI.getShiftAmountTy().bitsGT(Op2.getValueType()))
2038 Op2 = DAG.getNode(ISD::ANY_EXTEND, TLI.getShiftAmountTy(), Op2);
2041 setValue(&I, DAG.getNode(Opcode, Op1.getValueType(), Op1, Op2));
2044 void SelectionDAGLowering::visitICmp(User &I) {
2045 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2046 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2047 predicate = IC->getPredicate();
2048 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2049 predicate = ICmpInst::Predicate(IC->getPredicate());
2050 SDValue Op1 = getValue(I.getOperand(0));
2051 SDValue Op2 = getValue(I.getOperand(1));
2052 ISD::CondCode Opcode;
2053 switch (predicate) {
2054 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2055 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2056 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2057 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2058 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2059 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2060 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2061 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2062 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2063 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2065 assert(!"Invalid ICmp predicate value");
2066 Opcode = ISD::SETEQ;
2069 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Opcode));
2072 void SelectionDAGLowering::visitFCmp(User &I) {
2073 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2074 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2075 predicate = FC->getPredicate();
2076 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2077 predicate = FCmpInst::Predicate(FC->getPredicate());
2078 SDValue Op1 = getValue(I.getOperand(0));
2079 SDValue Op2 = getValue(I.getOperand(1));
2080 ISD::CondCode Condition, FOC, FPC;
2081 switch (predicate) {
2082 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2083 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2084 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2085 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2086 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2087 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2088 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2089 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2090 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2091 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2092 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2093 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2094 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2095 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2096 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2097 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2099 assert(!"Invalid FCmp predicate value");
2100 FOC = FPC = ISD::SETFALSE;
2103 if (FiniteOnlyFPMath())
2107 setValue(&I, DAG.getSetCC(MVT::i1, Op1, Op2, Condition));
2110 void SelectionDAGLowering::visitVICmp(User &I) {
2111 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2112 if (VICmpInst *IC = dyn_cast<VICmpInst>(&I))
2113 predicate = IC->getPredicate();
2114 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2115 predicate = ICmpInst::Predicate(IC->getPredicate());
2116 SDValue Op1 = getValue(I.getOperand(0));
2117 SDValue Op2 = getValue(I.getOperand(1));
2118 ISD::CondCode Opcode;
2119 switch (predicate) {
2120 case ICmpInst::ICMP_EQ : Opcode = ISD::SETEQ; break;
2121 case ICmpInst::ICMP_NE : Opcode = ISD::SETNE; break;
2122 case ICmpInst::ICMP_UGT : Opcode = ISD::SETUGT; break;
2123 case ICmpInst::ICMP_UGE : Opcode = ISD::SETUGE; break;
2124 case ICmpInst::ICMP_ULT : Opcode = ISD::SETULT; break;
2125 case ICmpInst::ICMP_ULE : Opcode = ISD::SETULE; break;
2126 case ICmpInst::ICMP_SGT : Opcode = ISD::SETGT; break;
2127 case ICmpInst::ICMP_SGE : Opcode = ISD::SETGE; break;
2128 case ICmpInst::ICMP_SLT : Opcode = ISD::SETLT; break;
2129 case ICmpInst::ICMP_SLE : Opcode = ISD::SETLE; break;
2131 assert(!"Invalid ICmp predicate value");
2132 Opcode = ISD::SETEQ;
2135 setValue(&I, DAG.getVSetCC(Op1.getValueType(), Op1, Op2, Opcode));
2138 void SelectionDAGLowering::visitVFCmp(User &I) {
2139 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2140 if (VFCmpInst *FC = dyn_cast<VFCmpInst>(&I))
2141 predicate = FC->getPredicate();
2142 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2143 predicate = FCmpInst::Predicate(FC->getPredicate());
2144 SDValue Op1 = getValue(I.getOperand(0));
2145 SDValue Op2 = getValue(I.getOperand(1));
2146 ISD::CondCode Condition, FOC, FPC;
2147 switch (predicate) {
2148 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
2149 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
2150 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
2151 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
2152 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
2153 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
2154 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
2155 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
2156 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
2157 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
2158 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
2159 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
2160 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
2161 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
2162 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
2163 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
2165 assert(!"Invalid VFCmp predicate value");
2166 FOC = FPC = ISD::SETFALSE;
2169 if (FiniteOnlyFPMath())
2174 MVT DestVT = TLI.getValueType(I.getType());
2176 setValue(&I, DAG.getVSetCC(DestVT, Op1, Op2, Condition));
2179 void SelectionDAGLowering::visitSelect(User &I) {
2180 SDValue Cond = getValue(I.getOperand(0));
2181 SDValue TrueVal = getValue(I.getOperand(1));
2182 SDValue FalseVal = getValue(I.getOperand(2));
2183 setValue(&I, DAG.getNode(ISD::SELECT, TrueVal.getValueType(), Cond,
2184 TrueVal, FalseVal));
2188 void SelectionDAGLowering::visitTrunc(User &I) {
2189 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2190 SDValue N = getValue(I.getOperand(0));
2191 MVT DestVT = TLI.getValueType(I.getType());
2192 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2195 void SelectionDAGLowering::visitZExt(User &I) {
2196 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2197 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2198 SDValue N = getValue(I.getOperand(0));
2199 MVT DestVT = TLI.getValueType(I.getType());
2200 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2203 void SelectionDAGLowering::visitSExt(User &I) {
2204 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2205 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2206 SDValue N = getValue(I.getOperand(0));
2207 MVT DestVT = TLI.getValueType(I.getType());
2208 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, DestVT, N));
2211 void SelectionDAGLowering::visitFPTrunc(User &I) {
2212 // FPTrunc 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_ROUND, DestVT, N, DAG.getIntPtrConstant(0)));
2218 void SelectionDAGLowering::visitFPExt(User &I){
2219 // FPTrunc 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::FP_EXTEND, DestVT, N));
2225 void SelectionDAGLowering::visitFPToUI(User &I) {
2226 // FPToUI 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::FP_TO_UINT, DestVT, N));
2232 void SelectionDAGLowering::visitFPToSI(User &I) {
2233 // FPToSI is never a no-op cast, no need to check
2234 SDValue N = getValue(I.getOperand(0));
2235 MVT DestVT = TLI.getValueType(I.getType());
2236 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, DestVT, N));
2239 void SelectionDAGLowering::visitUIToFP(User &I) {
2240 // UIToFP is never a no-op cast, no need to check
2241 SDValue N = getValue(I.getOperand(0));
2242 MVT DestVT = TLI.getValueType(I.getType());
2243 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, DestVT, N));
2246 void SelectionDAGLowering::visitSIToFP(User &I){
2247 // UIToFP is never a no-op cast, no need to check
2248 SDValue N = getValue(I.getOperand(0));
2249 MVT DestVT = TLI.getValueType(I.getType());
2250 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, DestVT, N));
2253 void SelectionDAGLowering::visitPtrToInt(User &I) {
2254 // What to do depends on the size of the integer and the size of the pointer.
2255 // We can either truncate, zero extend, or no-op, accordingly.
2256 SDValue N = getValue(I.getOperand(0));
2257 MVT SrcVT = N.getValueType();
2258 MVT DestVT = TLI.getValueType(I.getType());
2260 if (DestVT.bitsLT(SrcVT))
2261 Result = DAG.getNode(ISD::TRUNCATE, DestVT, N);
2263 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2264 Result = DAG.getNode(ISD::ZERO_EXTEND, DestVT, N);
2265 setValue(&I, Result);
2268 void SelectionDAGLowering::visitIntToPtr(User &I) {
2269 // What to do depends on the size of the integer and the size of the pointer.
2270 // We can either truncate, zero extend, or no-op, accordingly.
2271 SDValue N = getValue(I.getOperand(0));
2272 MVT SrcVT = N.getValueType();
2273 MVT DestVT = TLI.getValueType(I.getType());
2274 if (DestVT.bitsLT(SrcVT))
2275 setValue(&I, DAG.getNode(ISD::TRUNCATE, DestVT, N));
2277 // Note: ZERO_EXTEND can handle cases where the sizes are equal too
2278 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, DestVT, N));
2281 void SelectionDAGLowering::visitBitCast(User &I) {
2282 SDValue N = getValue(I.getOperand(0));
2283 MVT DestVT = TLI.getValueType(I.getType());
2285 // BitCast assures us that source and destination are the same size so this
2286 // is either a BIT_CONVERT or a no-op.
2287 if (DestVT != N.getValueType())
2288 setValue(&I, DAG.getNode(ISD::BIT_CONVERT, DestVT, N)); // convert types
2290 setValue(&I, N); // noop cast.
2293 void SelectionDAGLowering::visitInsertElement(User &I) {
2294 SDValue InVec = getValue(I.getOperand(0));
2295 SDValue InVal = getValue(I.getOperand(1));
2296 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2297 getValue(I.getOperand(2)));
2299 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT,
2300 TLI.getValueType(I.getType()),
2301 InVec, InVal, InIdx));
2304 void SelectionDAGLowering::visitExtractElement(User &I) {
2305 SDValue InVec = getValue(I.getOperand(0));
2306 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, TLI.getPointerTy(),
2307 getValue(I.getOperand(1)));
2308 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
2309 TLI.getValueType(I.getType()), InVec, InIdx));
2312 void SelectionDAGLowering::visitShuffleVector(User &I) {
2313 SDValue V1 = getValue(I.getOperand(0));
2314 SDValue V2 = getValue(I.getOperand(1));
2315 SDValue Mask = getValue(I.getOperand(2));
2317 setValue(&I, DAG.getNode(ISD::VECTOR_SHUFFLE,
2318 TLI.getValueType(I.getType()),
2322 void SelectionDAGLowering::visitInsertValue(InsertValueInst &I) {
2323 const Value *Op0 = I.getOperand(0);
2324 const Value *Op1 = I.getOperand(1);
2325 const Type *AggTy = I.getType();
2326 const Type *ValTy = Op1->getType();
2327 bool IntoUndef = isa<UndefValue>(Op0);
2328 bool FromUndef = isa<UndefValue>(Op1);
2330 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2331 I.idx_begin(), I.idx_end());
2333 SmallVector<MVT, 4> AggValueVTs;
2334 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2335 SmallVector<MVT, 4> ValValueVTs;
2336 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2338 unsigned NumAggValues = AggValueVTs.size();
2339 unsigned NumValValues = ValValueVTs.size();
2340 SmallVector<SDValue, 4> Values(NumAggValues);
2342 SDValue Agg = getValue(Op0);
2343 SDValue Val = getValue(Op1);
2345 // Copy the beginning value(s) from the original aggregate.
2346 for (; i != LinearIndex; ++i)
2347 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2348 SDValue(Agg.getNode(), Agg.getResNo() + i);
2349 // Copy values from the inserted value(s).
2350 for (; i != LinearIndex + NumValValues; ++i)
2351 Values[i] = FromUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2352 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2353 // Copy remaining value(s) from the original aggregate.
2354 for (; i != NumAggValues; ++i)
2355 Values[i] = IntoUndef ? DAG.getNode(ISD::UNDEF, AggValueVTs[i]) :
2356 SDValue(Agg.getNode(), Agg.getResNo() + i);
2358 setValue(&I, DAG.getMergeValues(DAG.getVTList(&AggValueVTs[0], NumAggValues),
2359 &Values[0], NumAggValues));
2362 void SelectionDAGLowering::visitExtractValue(ExtractValueInst &I) {
2363 const Value *Op0 = I.getOperand(0);
2364 const Type *AggTy = Op0->getType();
2365 const Type *ValTy = I.getType();
2366 bool OutOfUndef = isa<UndefValue>(Op0);
2368 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2369 I.idx_begin(), I.idx_end());
2371 SmallVector<MVT, 4> ValValueVTs;
2372 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2374 unsigned NumValValues = ValValueVTs.size();
2375 SmallVector<SDValue, 4> Values(NumValValues);
2377 SDValue Agg = getValue(Op0);
2378 // Copy out the selected value(s).
2379 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2380 Values[i - LinearIndex] =
2381 OutOfUndef ? DAG.getNode(ISD::UNDEF, Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2382 SDValue(Agg.getNode(), Agg.getResNo() + i);
2384 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValValueVTs[0], NumValValues),
2385 &Values[0], NumValValues));
2389 void SelectionDAGLowering::visitGetElementPtr(User &I) {
2390 SDValue N = getValue(I.getOperand(0));
2391 const Type *Ty = I.getOperand(0)->getType();
2393 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2396 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2397 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2400 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2401 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2402 DAG.getIntPtrConstant(Offset));
2404 Ty = StTy->getElementType(Field);
2406 Ty = cast<SequentialType>(Ty)->getElementType();
2408 // If this is a constant subscript, handle it quickly.
2409 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2410 if (CI->getZExtValue() == 0) continue;
2412 TD->getABITypeSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2413 N = DAG.getNode(ISD::ADD, N.getValueType(), N,
2414 DAG.getIntPtrConstant(Offs));
2418 // N = N + Idx * ElementSize;
2419 uint64_t ElementSize = TD->getABITypeSize(Ty);
2420 SDValue IdxN = getValue(Idx);
2422 // If the index is smaller or larger than intptr_t, truncate or extend
2424 if (IdxN.getValueType().bitsLT(N.getValueType()))
2425 IdxN = DAG.getNode(ISD::SIGN_EXTEND, N.getValueType(), IdxN);
2426 else if (IdxN.getValueType().bitsGT(N.getValueType()))
2427 IdxN = DAG.getNode(ISD::TRUNCATE, N.getValueType(), IdxN);
2429 // If this is a multiply by a power of two, turn it into a shl
2430 // immediately. This is a very common case.
2431 if (ElementSize != 1) {
2432 if (isPowerOf2_64(ElementSize)) {
2433 unsigned Amt = Log2_64(ElementSize);
2434 IdxN = DAG.getNode(ISD::SHL, N.getValueType(), IdxN,
2435 DAG.getConstant(Amt, TLI.getShiftAmountTy()));
2437 SDValue Scale = DAG.getIntPtrConstant(ElementSize);
2438 IdxN = DAG.getNode(ISD::MUL, N.getValueType(), IdxN, Scale);
2442 N = DAG.getNode(ISD::ADD, N.getValueType(), N, IdxN);
2448 void SelectionDAGLowering::visitAlloca(AllocaInst &I) {
2449 // If this is a fixed sized alloca in the entry block of the function,
2450 // allocate it statically on the stack.
2451 if (FuncInfo.StaticAllocaMap.count(&I))
2452 return; // getValue will auto-populate this.
2454 const Type *Ty = I.getAllocatedType();
2455 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
2457 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2460 SDValue AllocSize = getValue(I.getArraySize());
2461 MVT IntPtr = TLI.getPointerTy();
2462 if (IntPtr.bitsLT(AllocSize.getValueType()))
2463 AllocSize = DAG.getNode(ISD::TRUNCATE, IntPtr, AllocSize);
2464 else if (IntPtr.bitsGT(AllocSize.getValueType()))
2465 AllocSize = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, AllocSize);
2467 AllocSize = DAG.getNode(ISD::MUL, IntPtr, AllocSize,
2468 DAG.getIntPtrConstant(TySize));
2470 // Handle alignment. If the requested alignment is less than or equal to
2471 // the stack alignment, ignore it. If the size is greater than or equal to
2472 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2473 unsigned StackAlign =
2474 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2475 if (Align <= StackAlign)
2478 // Round the size of the allocation up to the stack alignment size
2479 // by add SA-1 to the size.
2480 AllocSize = DAG.getNode(ISD::ADD, AllocSize.getValueType(), AllocSize,
2481 DAG.getIntPtrConstant(StackAlign-1));
2482 // Mask out the low bits for alignment purposes.
2483 AllocSize = DAG.getNode(ISD::AND, AllocSize.getValueType(), AllocSize,
2484 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2486 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2487 const MVT *VTs = DAG.getNodeValueTypes(AllocSize.getValueType(),
2489 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, VTs, 2, Ops, 3);
2491 DAG.setRoot(DSA.getValue(1));
2493 // Inform the Frame Information that we have just allocated a variable-sized
2495 CurMBB->getParent()->getFrameInfo()->CreateVariableSizedObject();
2498 void SelectionDAGLowering::visitLoad(LoadInst &I) {
2499 const Value *SV = I.getOperand(0);
2500 SDValue Ptr = getValue(SV);
2502 const Type *Ty = I.getType();
2503 bool isVolatile = I.isVolatile();
2504 unsigned Alignment = I.getAlignment();
2506 SmallVector<MVT, 4> ValueVTs;
2507 SmallVector<uint64_t, 4> Offsets;
2508 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2509 unsigned NumValues = ValueVTs.size();
2514 bool ConstantMemory = false;
2516 // Serialize volatile loads with other side effects.
2518 else if (AA->pointsToConstantMemory(SV)) {
2519 // Do not serialize (non-volatile) loads of constant memory with anything.
2520 Root = DAG.getEntryNode();
2521 ConstantMemory = true;
2523 // Do not serialize non-volatile loads against each other.
2524 Root = DAG.getRoot();
2527 SmallVector<SDValue, 4> Values(NumValues);
2528 SmallVector<SDValue, 4> Chains(NumValues);
2529 MVT PtrVT = Ptr.getValueType();
2530 for (unsigned i = 0; i != NumValues; ++i) {
2531 SDValue L = DAG.getLoad(ValueVTs[i], Root,
2532 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2533 DAG.getConstant(Offsets[i], PtrVT)),
2535 isVolatile, Alignment);
2537 Chains[i] = L.getValue(1);
2540 if (!ConstantMemory) {
2541 SDValue Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
2542 &Chains[0], NumValues);
2546 PendingLoads.push_back(Chain);
2549 setValue(&I, DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], NumValues),
2550 &Values[0], NumValues));
2554 void SelectionDAGLowering::visitStore(StoreInst &I) {
2555 Value *SrcV = I.getOperand(0);
2556 Value *PtrV = I.getOperand(1);
2558 SmallVector<MVT, 4> ValueVTs;
2559 SmallVector<uint64_t, 4> Offsets;
2560 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2561 unsigned NumValues = ValueVTs.size();
2565 // Get the lowered operands. Note that we do this after
2566 // checking if NumResults is zero, because with zero results
2567 // the operands won't have values in the map.
2568 SDValue Src = getValue(SrcV);
2569 SDValue Ptr = getValue(PtrV);
2571 SDValue Root = getRoot();
2572 SmallVector<SDValue, 4> Chains(NumValues);
2573 MVT PtrVT = Ptr.getValueType();
2574 bool isVolatile = I.isVolatile();
2575 unsigned Alignment = I.getAlignment();
2576 for (unsigned i = 0; i != NumValues; ++i)
2577 Chains[i] = DAG.getStore(Root, SDValue(Src.getNode(), Src.getResNo() + i),
2578 DAG.getNode(ISD::ADD, PtrVT, Ptr,
2579 DAG.getConstant(Offsets[i], PtrVT)),
2581 isVolatile, Alignment);
2583 DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumValues));
2586 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2588 void SelectionDAGLowering::visitTargetIntrinsic(CallInst &I,
2589 unsigned Intrinsic) {
2590 bool HasChain = !I.doesNotAccessMemory();
2591 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2593 // Build the operand list.
2594 SmallVector<SDValue, 8> Ops;
2595 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2597 // We don't need to serialize loads against other loads.
2598 Ops.push_back(DAG.getRoot());
2600 Ops.push_back(getRoot());
2604 // Add the intrinsic ID as an integer operand.
2605 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2607 // Add all operands of the call to the operand list.
2608 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2609 SDValue Op = getValue(I.getOperand(i));
2610 assert(TLI.isTypeLegal(Op.getValueType()) &&
2611 "Intrinsic uses a non-legal type?");
2615 std::vector<MVT> VTs;
2616 if (I.getType() != Type::VoidTy) {
2617 MVT VT = TLI.getValueType(I.getType());
2618 if (VT.isVector()) {
2619 const VectorType *DestTy = cast<VectorType>(I.getType());
2620 MVT EltVT = TLI.getValueType(DestTy->getElementType());
2622 VT = MVT::getVectorVT(EltVT, DestTy->getNumElements());
2623 assert(VT != MVT::Other && "Intrinsic uses a non-legal type?");
2626 assert(TLI.isTypeLegal(VT) && "Intrinsic uses a non-legal type?");
2630 VTs.push_back(MVT::Other);
2632 const MVT *VTList = DAG.getNodeValueTypes(VTs);
2637 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, VTList, VTs.size(),
2638 &Ops[0], Ops.size());
2639 else if (I.getType() != Type::VoidTy)
2640 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, VTList, VTs.size(),
2641 &Ops[0], Ops.size());
2643 Result = DAG.getNode(ISD::INTRINSIC_VOID, VTList, VTs.size(),
2644 &Ops[0], Ops.size());
2647 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2649 PendingLoads.push_back(Chain);
2653 if (I.getType() != Type::VoidTy) {
2654 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2655 MVT VT = TLI.getValueType(PTy);
2656 Result = DAG.getNode(ISD::BIT_CONVERT, VT, Result);
2658 setValue(&I, Result);
2662 /// ExtractTypeInfo - Returns the type info, possibly bitcast, encoded in V.
2663 static GlobalVariable *ExtractTypeInfo(Value *V) {
2664 V = V->stripPointerCasts();
2665 GlobalVariable *GV = dyn_cast<GlobalVariable>(V);
2666 assert ((GV || isa<ConstantPointerNull>(V)) &&
2667 "TypeInfo must be a global variable or NULL");
2673 /// AddCatchInfo - Extract the personality and type infos from an eh.selector
2674 /// call, and add them to the specified machine basic block.
2675 void AddCatchInfo(CallInst &I, MachineModuleInfo *MMI,
2676 MachineBasicBlock *MBB) {
2677 // Inform the MachineModuleInfo of the personality for this landing pad.
2678 ConstantExpr *CE = cast<ConstantExpr>(I.getOperand(2));
2679 assert(CE->getOpcode() == Instruction::BitCast &&
2680 isa<Function>(CE->getOperand(0)) &&
2681 "Personality should be a function");
2682 MMI->addPersonality(MBB, cast<Function>(CE->getOperand(0)));
2684 // Gather all the type infos for this landing pad and pass them along to
2685 // MachineModuleInfo.
2686 std::vector<GlobalVariable *> TyInfo;
2687 unsigned N = I.getNumOperands();
2689 for (unsigned i = N - 1; i > 2; --i) {
2690 if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(i))) {
2691 unsigned FilterLength = CI->getZExtValue();
2692 unsigned FirstCatch = i + FilterLength + !FilterLength;
2693 assert (FirstCatch <= N && "Invalid filter length");
2695 if (FirstCatch < N) {
2696 TyInfo.reserve(N - FirstCatch);
2697 for (unsigned j = FirstCatch; j < N; ++j)
2698 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2699 MMI->addCatchTypeInfo(MBB, TyInfo);
2703 if (!FilterLength) {
2705 MMI->addCleanup(MBB);
2708 TyInfo.reserve(FilterLength - 1);
2709 for (unsigned j = i + 1; j < FirstCatch; ++j)
2710 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2711 MMI->addFilterTypeInfo(MBB, TyInfo);
2720 TyInfo.reserve(N - 3);
2721 for (unsigned j = 3; j < N; ++j)
2722 TyInfo.push_back(ExtractTypeInfo(I.getOperand(j)));
2723 MMI->addCatchTypeInfo(MBB, TyInfo);
2729 /// Inlined utility function to implement binary input atomic intrinsics for
2730 /// visitIntrinsicCall: I is a call instruction
2731 /// Op is the associated NodeType for I
2733 SelectionDAGLowering::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2734 SDValue Root = getRoot();
2735 SDValue L = DAG.getAtomic(Op, Root,
2736 getValue(I.getOperand(1)),
2737 getValue(I.getOperand(2)),
2740 DAG.setRoot(L.getValue(1));
2744 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
2745 /// we want to emit this as a call to a named external function, return the name
2746 /// otherwise lower it and return null.
2748 SelectionDAGLowering::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
2749 switch (Intrinsic) {
2751 // By default, turn this into a target intrinsic node.
2752 visitTargetIntrinsic(I, Intrinsic);
2754 case Intrinsic::vastart: visitVAStart(I); return 0;
2755 case Intrinsic::vaend: visitVAEnd(I); return 0;
2756 case Intrinsic::vacopy: visitVACopy(I); return 0;
2757 case Intrinsic::returnaddress:
2758 setValue(&I, DAG.getNode(ISD::RETURNADDR, TLI.getPointerTy(),
2759 getValue(I.getOperand(1))));
2761 case Intrinsic::frameaddress:
2762 setValue(&I, DAG.getNode(ISD::FRAMEADDR, TLI.getPointerTy(),
2763 getValue(I.getOperand(1))));
2765 case Intrinsic::setjmp:
2766 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
2768 case Intrinsic::longjmp:
2769 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
2771 case Intrinsic::memcpy_i32:
2772 case Intrinsic::memcpy_i64: {
2773 SDValue Op1 = getValue(I.getOperand(1));
2774 SDValue Op2 = getValue(I.getOperand(2));
2775 SDValue Op3 = getValue(I.getOperand(3));
2776 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2777 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2778 I.getOperand(1), 0, I.getOperand(2), 0));
2781 case Intrinsic::memset_i32:
2782 case Intrinsic::memset_i64: {
2783 SDValue Op1 = getValue(I.getOperand(1));
2784 SDValue Op2 = getValue(I.getOperand(2));
2785 SDValue Op3 = getValue(I.getOperand(3));
2786 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2787 DAG.setRoot(DAG.getMemset(getRoot(), Op1, Op2, Op3, Align,
2788 I.getOperand(1), 0));
2791 case Intrinsic::memmove_i32:
2792 case Intrinsic::memmove_i64: {
2793 SDValue Op1 = getValue(I.getOperand(1));
2794 SDValue Op2 = getValue(I.getOperand(2));
2795 SDValue Op3 = getValue(I.getOperand(3));
2796 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
2798 // If the source and destination are known to not be aliases, we can
2799 // lower memmove as memcpy.
2800 uint64_t Size = -1ULL;
2801 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
2802 Size = C->getValue();
2803 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
2804 AliasAnalysis::NoAlias) {
2805 DAG.setRoot(DAG.getMemcpy(getRoot(), Op1, Op2, Op3, Align, false,
2806 I.getOperand(1), 0, I.getOperand(2), 0));
2810 DAG.setRoot(DAG.getMemmove(getRoot(), Op1, Op2, Op3, Align,
2811 I.getOperand(1), 0, I.getOperand(2), 0));
2814 case Intrinsic::dbg_stoppoint: {
2815 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2816 DbgStopPointInst &SPI = cast<DbgStopPointInst>(I);
2817 if (MMI && SPI.getContext() && MMI->Verify(SPI.getContext())) {
2818 DebugInfoDesc *DD = MMI->getDescFor(SPI.getContext());
2819 assert(DD && "Not a debug information descriptor");
2820 DAG.setRoot(DAG.getDbgStopPoint(getRoot(),
2823 cast<CompileUnitDesc>(DD)));
2828 case Intrinsic::dbg_region_start: {
2829 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2830 DbgRegionStartInst &RSI = cast<DbgRegionStartInst>(I);
2831 if (MMI && RSI.getContext() && MMI->Verify(RSI.getContext())) {
2832 unsigned LabelID = MMI->RecordRegionStart(RSI.getContext());
2833 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
2838 case Intrinsic::dbg_region_end: {
2839 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2840 DbgRegionEndInst &REI = cast<DbgRegionEndInst>(I);
2841 if (MMI && REI.getContext() && MMI->Verify(REI.getContext())) {
2842 unsigned LabelID = MMI->RecordRegionEnd(REI.getContext());
2843 DAG.setRoot(DAG.getLabel(ISD::DBG_LABEL, getRoot(), LabelID));
2848 case Intrinsic::dbg_func_start: {
2849 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2851 DbgFuncStartInst &FSI = cast<DbgFuncStartInst>(I);
2852 Value *SP = FSI.getSubprogram();
2853 if (SP && MMI->Verify(SP)) {
2854 // llvm.dbg.func.start implicitly defines a dbg_stoppoint which is
2855 // what (most?) gdb expects.
2856 DebugInfoDesc *DD = MMI->getDescFor(SP);
2857 assert(DD && "Not a debug information descriptor");
2858 SubprogramDesc *Subprogram = cast<SubprogramDesc>(DD);
2859 const CompileUnitDesc *CompileUnit = Subprogram->getFile();
2860 unsigned SrcFile = MMI->RecordSource(CompileUnit);
2861 // Record the source line but does create a label. It will be emitted
2862 // at asm emission time.
2863 MMI->RecordSourceLine(Subprogram->getLine(), 0, SrcFile);
2868 case Intrinsic::dbg_declare: {
2869 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2870 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
2871 Value *Variable = DI.getVariable();
2872 if (MMI && Variable && MMI->Verify(Variable))
2873 DAG.setRoot(DAG.getNode(ISD::DECLARE, MVT::Other, getRoot(),
2874 getValue(DI.getAddress()), getValue(Variable)));
2878 case Intrinsic::eh_exception: {
2879 if (!CurMBB->isLandingPad()) {
2880 // FIXME: Mark exception register as live in. Hack for PR1508.
2881 unsigned Reg = TLI.getExceptionAddressRegister();
2882 if (Reg) CurMBB->addLiveIn(Reg);
2884 // Insert the EXCEPTIONADDR instruction.
2885 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
2887 Ops[0] = DAG.getRoot();
2888 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, VTs, Ops, 1);
2890 DAG.setRoot(Op.getValue(1));
2894 case Intrinsic::eh_selector_i32:
2895 case Intrinsic::eh_selector_i64: {
2896 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2897 MVT VT = (Intrinsic == Intrinsic::eh_selector_i32 ?
2898 MVT::i32 : MVT::i64);
2901 if (CurMBB->isLandingPad())
2902 AddCatchInfo(I, MMI, CurMBB);
2905 FuncInfo.CatchInfoLost.insert(&I);
2907 // FIXME: Mark exception selector register as live in. Hack for PR1508.
2908 unsigned Reg = TLI.getExceptionSelectorRegister();
2909 if (Reg) CurMBB->addLiveIn(Reg);
2912 // Insert the EHSELECTION instruction.
2913 SDVTList VTs = DAG.getVTList(VT, MVT::Other);
2915 Ops[0] = getValue(I.getOperand(1));
2917 SDValue Op = DAG.getNode(ISD::EHSELECTION, VTs, Ops, 2);
2919 DAG.setRoot(Op.getValue(1));
2921 setValue(&I, DAG.getConstant(0, VT));
2927 case Intrinsic::eh_typeid_for_i32:
2928 case Intrinsic::eh_typeid_for_i64: {
2929 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2930 MVT VT = (Intrinsic == Intrinsic::eh_typeid_for_i32 ?
2931 MVT::i32 : MVT::i64);
2934 // Find the type id for the given typeinfo.
2935 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
2937 unsigned TypeID = MMI->getTypeIDFor(GV);
2938 setValue(&I, DAG.getConstant(TypeID, VT));
2940 // Return something different to eh_selector.
2941 setValue(&I, DAG.getConstant(1, VT));
2947 case Intrinsic::eh_return: {
2948 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
2951 MMI->setCallsEHReturn(true);
2952 DAG.setRoot(DAG.getNode(ISD::EH_RETURN,
2955 getValue(I.getOperand(1)),
2956 getValue(I.getOperand(2))));
2958 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
2964 case Intrinsic::eh_unwind_init: {
2965 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
2966 MMI->setCallsUnwindInit(true);
2972 case Intrinsic::eh_dwarf_cfa: {
2973 MVT VT = getValue(I.getOperand(1)).getValueType();
2975 if (VT.bitsGT(TLI.getPointerTy()))
2976 CfaArg = DAG.getNode(ISD::TRUNCATE,
2977 TLI.getPointerTy(), getValue(I.getOperand(1)));
2979 CfaArg = DAG.getNode(ISD::SIGN_EXTEND,
2980 TLI.getPointerTy(), getValue(I.getOperand(1)));
2982 SDValue Offset = DAG.getNode(ISD::ADD,
2984 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET,
2985 TLI.getPointerTy()),
2987 setValue(&I, DAG.getNode(ISD::ADD,
2989 DAG.getNode(ISD::FRAMEADDR,
2992 TLI.getPointerTy())),
2997 case Intrinsic::sqrt:
2998 setValue(&I, DAG.getNode(ISD::FSQRT,
2999 getValue(I.getOperand(1)).getValueType(),
3000 getValue(I.getOperand(1))));
3002 case Intrinsic::powi:
3003 setValue(&I, DAG.getNode(ISD::FPOWI,
3004 getValue(I.getOperand(1)).getValueType(),
3005 getValue(I.getOperand(1)),
3006 getValue(I.getOperand(2))));
3008 case Intrinsic::sin:
3009 setValue(&I, DAG.getNode(ISD::FSIN,
3010 getValue(I.getOperand(1)).getValueType(),
3011 getValue(I.getOperand(1))));
3013 case Intrinsic::cos:
3014 setValue(&I, DAG.getNode(ISD::FCOS,
3015 getValue(I.getOperand(1)).getValueType(),
3016 getValue(I.getOperand(1))));
3018 case Intrinsic::log:
3019 setValue(&I, DAG.getNode(ISD::FLOG,
3020 getValue(I.getOperand(1)).getValueType(),
3021 getValue(I.getOperand(1))));
3023 case Intrinsic::log2:
3024 setValue(&I, DAG.getNode(ISD::FLOG2,
3025 getValue(I.getOperand(1)).getValueType(),
3026 getValue(I.getOperand(1))));
3028 case Intrinsic::log10:
3029 setValue(&I, DAG.getNode(ISD::FLOG10,
3030 getValue(I.getOperand(1)).getValueType(),
3031 getValue(I.getOperand(1))));
3033 case Intrinsic::exp:
3034 setValue(&I, DAG.getNode(ISD::FEXP,
3035 getValue(I.getOperand(1)).getValueType(),
3036 getValue(I.getOperand(1))));
3038 case Intrinsic::exp2:
3039 setValue(&I, DAG.getNode(ISD::FEXP2,
3040 getValue(I.getOperand(1)).getValueType(),
3041 getValue(I.getOperand(1))));
3043 case Intrinsic::pow:
3044 setValue(&I, DAG.getNode(ISD::FPOW,
3045 getValue(I.getOperand(1)).getValueType(),
3046 getValue(I.getOperand(1)),
3047 getValue(I.getOperand(2))));
3049 case Intrinsic::pcmarker: {
3050 SDValue Tmp = getValue(I.getOperand(1));
3051 DAG.setRoot(DAG.getNode(ISD::PCMARKER, MVT::Other, getRoot(), Tmp));
3054 case Intrinsic::readcyclecounter: {
3055 SDValue Op = getRoot();
3056 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER,
3057 DAG.getNodeValueTypes(MVT::i64, MVT::Other), 2,
3060 DAG.setRoot(Tmp.getValue(1));
3063 case Intrinsic::part_select: {
3064 // Currently not implemented: just abort
3065 assert(0 && "part_select intrinsic not implemented");
3068 case Intrinsic::part_set: {
3069 // Currently not implemented: just abort
3070 assert(0 && "part_set intrinsic not implemented");
3073 case Intrinsic::bswap:
3074 setValue(&I, DAG.getNode(ISD::BSWAP,
3075 getValue(I.getOperand(1)).getValueType(),
3076 getValue(I.getOperand(1))));
3078 case Intrinsic::cttz: {
3079 SDValue Arg = getValue(I.getOperand(1));
3080 MVT Ty = Arg.getValueType();
3081 SDValue result = DAG.getNode(ISD::CTTZ, Ty, Arg);
3082 setValue(&I, result);
3085 case Intrinsic::ctlz: {
3086 SDValue Arg = getValue(I.getOperand(1));
3087 MVT Ty = Arg.getValueType();
3088 SDValue result = DAG.getNode(ISD::CTLZ, Ty, Arg);
3089 setValue(&I, result);
3092 case Intrinsic::ctpop: {
3093 SDValue Arg = getValue(I.getOperand(1));
3094 MVT Ty = Arg.getValueType();
3095 SDValue result = DAG.getNode(ISD::CTPOP, Ty, Arg);
3096 setValue(&I, result);
3099 case Intrinsic::stacksave: {
3100 SDValue Op = getRoot();
3101 SDValue Tmp = DAG.getNode(ISD::STACKSAVE,
3102 DAG.getNodeValueTypes(TLI.getPointerTy(), MVT::Other), 2, &Op, 1);
3104 DAG.setRoot(Tmp.getValue(1));
3107 case Intrinsic::stackrestore: {
3108 SDValue Tmp = getValue(I.getOperand(1));
3109 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, MVT::Other, getRoot(), Tmp));
3112 case Intrinsic::var_annotation:
3113 // Discard annotate attributes
3116 case Intrinsic::init_trampoline: {
3117 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
3121 Ops[1] = getValue(I.getOperand(1));
3122 Ops[2] = getValue(I.getOperand(2));
3123 Ops[3] = getValue(I.getOperand(3));
3124 Ops[4] = DAG.getSrcValue(I.getOperand(1));
3125 Ops[5] = DAG.getSrcValue(F);
3127 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE,
3128 DAG.getNodeValueTypes(TLI.getPointerTy(),
3133 DAG.setRoot(Tmp.getValue(1));
3137 case Intrinsic::gcroot:
3139 Value *Alloca = I.getOperand(1);
3140 Constant *TypeMap = cast<Constant>(I.getOperand(2));
3142 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
3143 GFI->addStackRoot(FI->getIndex(), TypeMap);
3147 case Intrinsic::gcread:
3148 case Intrinsic::gcwrite:
3149 assert(0 && "GC failed to lower gcread/gcwrite intrinsics!");
3152 case Intrinsic::flt_rounds: {
3153 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, MVT::i32));
3157 case Intrinsic::trap: {
3158 DAG.setRoot(DAG.getNode(ISD::TRAP, MVT::Other, getRoot()));
3161 case Intrinsic::prefetch: {
3164 Ops[1] = getValue(I.getOperand(1));
3165 Ops[2] = getValue(I.getOperand(2));
3166 Ops[3] = getValue(I.getOperand(3));
3167 DAG.setRoot(DAG.getNode(ISD::PREFETCH, MVT::Other, &Ops[0], 4));
3171 case Intrinsic::memory_barrier: {
3174 for (int x = 1; x < 6; ++x)
3175 Ops[x] = getValue(I.getOperand(x));
3177 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, MVT::Other, &Ops[0], 6));
3180 case Intrinsic::atomic_cmp_swap: {
3181 SDValue Root = getRoot();
3183 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3185 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_8, Root,
3186 getValue(I.getOperand(1)),
3187 getValue(I.getOperand(2)),
3188 getValue(I.getOperand(3)),
3192 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_16, Root,
3193 getValue(I.getOperand(1)),
3194 getValue(I.getOperand(2)),
3195 getValue(I.getOperand(3)),
3199 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_32, Root,
3200 getValue(I.getOperand(1)),
3201 getValue(I.getOperand(2)),
3202 getValue(I.getOperand(3)),
3206 L = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP_64, Root,
3207 getValue(I.getOperand(1)),
3208 getValue(I.getOperand(2)),
3209 getValue(I.getOperand(3)),
3213 assert(0 && "Invalid atomic type");
3217 DAG.setRoot(L.getValue(1));
3220 case Intrinsic::atomic_load_add:
3221 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3223 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_8);
3225 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_16);
3227 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_32);
3229 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD_64);
3231 assert(0 && "Invalid atomic type");
3234 case Intrinsic::atomic_load_sub:
3235 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3237 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_8);
3239 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_16);
3241 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_32);
3243 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB_64);
3245 assert(0 && "Invalid atomic type");
3248 case Intrinsic::atomic_load_or:
3249 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3251 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_8);
3253 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_16);
3255 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_32);
3257 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR_64);
3259 assert(0 && "Invalid atomic type");
3262 case Intrinsic::atomic_load_xor:
3263 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3265 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_8);
3267 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_16);
3269 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_32);
3271 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR_64);
3273 assert(0 && "Invalid atomic type");
3276 case Intrinsic::atomic_load_and:
3277 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3279 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_8);
3281 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_16);
3283 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_32);
3285 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND_64);
3287 assert(0 && "Invalid atomic type");
3290 case Intrinsic::atomic_load_nand:
3291 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3293 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_8);
3295 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_16);
3297 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_32);
3299 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND_64);
3301 assert(0 && "Invalid atomic type");
3304 case Intrinsic::atomic_load_max:
3305 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3307 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_8);
3309 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_16);
3311 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_32);
3313 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX_64);
3315 assert(0 && "Invalid atomic type");
3318 case Intrinsic::atomic_load_min:
3319 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3321 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_8);
3323 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_16);
3325 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_32);
3327 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN_64);
3329 assert(0 && "Invalid atomic type");
3332 case Intrinsic::atomic_load_umin:
3333 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3335 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_8);
3337 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_16);
3339 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_32);
3341 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN_64);
3343 assert(0 && "Invalid atomic type");
3346 case Intrinsic::atomic_load_umax:
3347 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3349 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_8);
3351 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_16);
3353 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_32);
3355 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX_64);
3357 assert(0 && "Invalid atomic type");
3360 case Intrinsic::atomic_swap:
3361 switch (getValue(I.getOperand(2)).getValueType().getSimpleVT()) {
3363 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_8);
3365 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_16);
3367 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_32);
3369 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP_64);
3371 assert(0 && "Invalid atomic type");
3378 void SelectionDAGLowering::LowerCallTo(CallSite CS, SDValue Callee,
3380 MachineBasicBlock *LandingPad) {
3381 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
3382 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
3383 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3384 unsigned BeginLabel = 0, EndLabel = 0;
3386 TargetLowering::ArgListTy Args;
3387 TargetLowering::ArgListEntry Entry;
3388 Args.reserve(CS.arg_size());
3389 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
3391 SDValue ArgNode = getValue(*i);
3392 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
3394 unsigned attrInd = i - CS.arg_begin() + 1;
3395 Entry.isSExt = CS.paramHasAttr(attrInd, ParamAttr::SExt);
3396 Entry.isZExt = CS.paramHasAttr(attrInd, ParamAttr::ZExt);
3397 Entry.isInReg = CS.paramHasAttr(attrInd, ParamAttr::InReg);
3398 Entry.isSRet = CS.paramHasAttr(attrInd, ParamAttr::StructRet);
3399 Entry.isNest = CS.paramHasAttr(attrInd, ParamAttr::Nest);
3400 Entry.isByVal = CS.paramHasAttr(attrInd, ParamAttr::ByVal);
3401 Entry.Alignment = CS.getParamAlignment(attrInd);
3402 Args.push_back(Entry);
3405 if (LandingPad && MMI) {
3406 // Insert a label before the invoke call to mark the try range. This can be
3407 // used to detect deletion of the invoke via the MachineModuleInfo.
3408 BeginLabel = MMI->NextLabelID();
3409 // Both PendingLoads and PendingExports must be flushed here;
3410 // this call might not return.
3412 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getControlRoot(), BeginLabel));
3415 std::pair<SDValue,SDValue> Result =
3416 TLI.LowerCallTo(getRoot(), CS.getType(),
3417 CS.paramHasAttr(0, ParamAttr::SExt),
3418 CS.paramHasAttr(0, ParamAttr::ZExt),
3419 FTy->isVarArg(), CS.getCallingConv(), IsTailCall,
3421 if (CS.getType() != Type::VoidTy)
3422 setValue(CS.getInstruction(), Result.first);
3423 DAG.setRoot(Result.second);
3425 if (LandingPad && MMI) {
3426 // Insert a label at the end of the invoke call to mark the try range. This
3427 // can be used to detect deletion of the invoke via the MachineModuleInfo.
3428 EndLabel = MMI->NextLabelID();
3429 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getRoot(), EndLabel));
3431 // Inform MachineModuleInfo of range.
3432 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
3437 void SelectionDAGLowering::visitCall(CallInst &I) {
3438 const char *RenameFn = 0;
3439 if (Function *F = I.getCalledFunction()) {
3440 if (F->isDeclaration()) {
3441 if (unsigned IID = F->getIntrinsicID()) {
3442 RenameFn = visitIntrinsicCall(I, IID);
3448 // Check for well-known libc/libm calls. If the function is internal, it
3449 // can't be a library call.
3450 unsigned NameLen = F->getNameLen();
3451 if (!F->hasInternalLinkage() && NameLen) {
3452 const char *NameStr = F->getNameStart();
3453 if (NameStr[0] == 'c' &&
3454 ((NameLen == 8 && !strcmp(NameStr, "copysign")) ||
3455 (NameLen == 9 && !strcmp(NameStr, "copysignf")))) {
3456 if (I.getNumOperands() == 3 && // Basic sanity checks.
3457 I.getOperand(1)->getType()->isFloatingPoint() &&
3458 I.getType() == I.getOperand(1)->getType() &&
3459 I.getType() == I.getOperand(2)->getType()) {
3460 SDValue LHS = getValue(I.getOperand(1));
3461 SDValue RHS = getValue(I.getOperand(2));
3462 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, LHS.getValueType(),
3466 } else if (NameStr[0] == 'f' &&
3467 ((NameLen == 4 && !strcmp(NameStr, "fabs")) ||
3468 (NameLen == 5 && !strcmp(NameStr, "fabsf")) ||
3469 (NameLen == 5 && !strcmp(NameStr, "fabsl")))) {
3470 if (I.getNumOperands() == 2 && // Basic sanity checks.
3471 I.getOperand(1)->getType()->isFloatingPoint() &&
3472 I.getType() == I.getOperand(1)->getType()) {
3473 SDValue Tmp = getValue(I.getOperand(1));
3474 setValue(&I, DAG.getNode(ISD::FABS, Tmp.getValueType(), Tmp));
3477 } else if (NameStr[0] == 's' &&
3478 ((NameLen == 3 && !strcmp(NameStr, "sin")) ||
3479 (NameLen == 4 && !strcmp(NameStr, "sinf")) ||
3480 (NameLen == 4 && !strcmp(NameStr, "sinl")))) {
3481 if (I.getNumOperands() == 2 && // Basic sanity checks.
3482 I.getOperand(1)->getType()->isFloatingPoint() &&
3483 I.getType() == I.getOperand(1)->getType()) {
3484 SDValue Tmp = getValue(I.getOperand(1));
3485 setValue(&I, DAG.getNode(ISD::FSIN, Tmp.getValueType(), Tmp));
3488 } else if (NameStr[0] == 'c' &&
3489 ((NameLen == 3 && !strcmp(NameStr, "cos")) ||
3490 (NameLen == 4 && !strcmp(NameStr, "cosf")) ||
3491 (NameLen == 4 && !strcmp(NameStr, "cosl")))) {
3492 if (I.getNumOperands() == 2 && // Basic sanity checks.
3493 I.getOperand(1)->getType()->isFloatingPoint() &&
3494 I.getType() == I.getOperand(1)->getType()) {
3495 SDValue Tmp = getValue(I.getOperand(1));
3496 setValue(&I, DAG.getNode(ISD::FCOS, Tmp.getValueType(), Tmp));
3501 } else if (isa<InlineAsm>(I.getOperand(0))) {
3508 Callee = getValue(I.getOperand(0));
3510 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
3512 LowerCallTo(&I, Callee, I.isTailCall());
3516 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
3517 /// this value and returns the result as a ValueVT value. This uses
3518 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3519 /// If the Flag pointer is NULL, no flag is used.
3520 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
3522 SDValue *Flag) const {
3523 // Assemble the legal parts into the final values.
3524 SmallVector<SDValue, 4> Values(ValueVTs.size());
3525 SmallVector<SDValue, 8> Parts;
3526 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
3527 // Copy the legal parts from the registers.
3528 MVT ValueVT = ValueVTs[Value];
3529 unsigned NumRegs = TLI->getNumRegisters(ValueVT);
3530 MVT RegisterVT = RegVTs[Value];
3532 Parts.resize(NumRegs);
3533 for (unsigned i = 0; i != NumRegs; ++i) {
3536 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT);
3538 P = DAG.getCopyFromReg(Chain, Regs[Part+i], RegisterVT, *Flag);
3539 *Flag = P.getValue(2);
3541 Chain = P.getValue(1);
3543 // If the source register was virtual and if we know something about it,
3544 // add an assert node.
3545 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
3546 RegisterVT.isInteger() && !RegisterVT.isVector()) {
3547 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
3548 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
3549 if (FLI.LiveOutRegInfo.size() > SlotNo) {
3550 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
3552 unsigned RegSize = RegisterVT.getSizeInBits();
3553 unsigned NumSignBits = LOI.NumSignBits;
3554 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
3556 // FIXME: We capture more information than the dag can represent. For
3557 // now, just use the tightest assertzext/assertsext possible.
3559 MVT FromVT(MVT::Other);
3560 if (NumSignBits == RegSize)
3561 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
3562 else if (NumZeroBits >= RegSize-1)
3563 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
3564 else if (NumSignBits > RegSize-8)
3565 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
3566 else if (NumZeroBits >= RegSize-9)
3567 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
3568 else if (NumSignBits > RegSize-16)
3569 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
3570 else if (NumZeroBits >= RegSize-17)
3571 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
3572 else if (NumSignBits > RegSize-32)
3573 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
3574 else if (NumZeroBits >= RegSize-33)
3575 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
3577 if (FromVT != MVT::Other) {
3578 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext,
3579 RegisterVT, P, DAG.getValueType(FromVT));
3588 Values[Value] = getCopyFromParts(DAG, Parts.begin(), NumRegs, RegisterVT,
3594 return DAG.getMergeValues(DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
3595 &Values[0], ValueVTs.size());
3598 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
3599 /// specified value into the registers specified by this object. This uses
3600 /// Chain/Flag as the input and updates them for the output Chain/Flag.
3601 /// If the Flag pointer is NULL, no flag is used.
3602 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG,
3603 SDValue &Chain, SDValue *Flag) const {
3604 // Get the list of the values's legal parts.
3605 unsigned NumRegs = Regs.size();
3606 SmallVector<SDValue, 8> Parts(NumRegs);
3607 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
3608 MVT ValueVT = ValueVTs[Value];
3609 unsigned NumParts = TLI->getNumRegisters(ValueVT);
3610 MVT RegisterVT = RegVTs[Value];
3612 getCopyToParts(DAG, Val.getValue(Val.getResNo() + Value),
3613 &Parts[Part], NumParts, RegisterVT);
3617 // Copy the parts into the registers.
3618 SmallVector<SDValue, 8> Chains(NumRegs);
3619 for (unsigned i = 0; i != NumRegs; ++i) {
3622 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i]);
3624 Part = DAG.getCopyToReg(Chain, Regs[i], Parts[i], *Flag);
3625 *Flag = Part.getValue(1);
3627 Chains[i] = Part.getValue(0);
3630 if (NumRegs == 1 || Flag)
3631 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
3632 // flagged to it. That is the CopyToReg nodes and the user are considered
3633 // a single scheduling unit. If we create a TokenFactor and return it as
3634 // chain, then the TokenFactor is both a predecessor (operand) of the
3635 // user as well as a successor (the TF operands are flagged to the user).
3636 // c1, f1 = CopyToReg
3637 // c2, f2 = CopyToReg
3638 // c3 = TokenFactor c1, c2
3641 Chain = Chains[NumRegs-1];
3643 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, &Chains[0], NumRegs);
3646 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
3647 /// operand list. This adds the code marker and includes the number of
3648 /// values added into it.
3649 void RegsForValue::AddInlineAsmOperands(unsigned Code, SelectionDAG &DAG,
3650 std::vector<SDValue> &Ops) const {
3651 MVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
3652 Ops.push_back(DAG.getTargetConstant(Code | (Regs.size() << 3), IntPtrTy));
3653 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
3654 unsigned NumRegs = TLI->getNumRegisters(ValueVTs[Value]);
3655 MVT RegisterVT = RegVTs[Value];
3656 for (unsigned i = 0; i != NumRegs; ++i)
3657 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
3661 /// isAllocatableRegister - If the specified register is safe to allocate,
3662 /// i.e. it isn't a stack pointer or some other special register, return the
3663 /// register class for the register. Otherwise, return null.
3664 static const TargetRegisterClass *
3665 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
3666 const TargetLowering &TLI,
3667 const TargetRegisterInfo *TRI) {
3668 MVT FoundVT = MVT::Other;
3669 const TargetRegisterClass *FoundRC = 0;
3670 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
3671 E = TRI->regclass_end(); RCI != E; ++RCI) {
3672 MVT ThisVT = MVT::Other;
3674 const TargetRegisterClass *RC = *RCI;
3675 // If none of the the value types for this register class are valid, we
3676 // can't use it. For example, 64-bit reg classes on 32-bit targets.
3677 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
3679 if (TLI.isTypeLegal(*I)) {
3680 // If we have already found this register in a different register class,
3681 // choose the one with the largest VT specified. For example, on
3682 // PowerPC, we favor f64 register classes over f32.
3683 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
3690 if (ThisVT == MVT::Other) continue;
3692 // NOTE: This isn't ideal. In particular, this might allocate the
3693 // frame pointer in functions that need it (due to them not being taken
3694 // out of allocation, because a variable sized allocation hasn't been seen
3695 // yet). This is a slight code pessimization, but should still work.
3696 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
3697 E = RC->allocation_order_end(MF); I != E; ++I)
3699 // We found a matching register class. Keep looking at others in case
3700 // we find one with larger registers that this physreg is also in.
3711 /// AsmOperandInfo - This contains information for each constraint that we are
3713 struct SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
3714 /// CallOperand - If this is the result output operand or a clobber
3715 /// this is null, otherwise it is the incoming operand to the CallInst.
3716 /// This gets modified as the asm is processed.
3717 SDValue CallOperand;
3719 /// AssignedRegs - If this is a register or register class operand, this
3720 /// contains the set of register corresponding to the operand.
3721 RegsForValue AssignedRegs;
3723 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
3724 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
3727 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
3728 /// busy in OutputRegs/InputRegs.
3729 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
3730 std::set<unsigned> &OutputRegs,
3731 std::set<unsigned> &InputRegs,
3732 const TargetRegisterInfo &TRI) const {
3734 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3735 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
3738 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
3739 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
3744 /// MarkRegAndAliases - Mark the specified register and all aliases in the
3746 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
3747 const TargetRegisterInfo &TRI) {
3748 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
3750 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
3751 for (; *Aliases; ++Aliases)
3752 Regs.insert(*Aliases);
3755 } // end llvm namespace.
3758 /// GetRegistersForValue - Assign registers (virtual or physical) for the
3759 /// specified operand. We prefer to assign virtual registers, to allow the
3760 /// register allocator handle the assignment process. However, if the asm uses
3761 /// features that we can't model on machineinstrs, we have SDISel do the
3762 /// allocation. This produces generally horrible, but correct, code.
3764 /// OpInfo describes the operand.
3765 /// HasEarlyClobber is true if there are any early clobber constraints (=&r)
3766 /// or any explicitly clobbered registers.
3767 /// Input and OutputRegs are the set of already allocated physical registers.
3769 void SelectionDAGLowering::
3770 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo, bool HasEarlyClobber,
3771 std::set<unsigned> &OutputRegs,
3772 std::set<unsigned> &InputRegs) {
3773 // Compute whether this value requires an input register, an output register,
3775 bool isOutReg = false;
3776 bool isInReg = false;
3777 switch (OpInfo.Type) {
3778 case InlineAsm::isOutput:
3781 // If this is an early-clobber output, or if there is an input
3782 // constraint that matches this, we need to reserve the input register
3783 // so no other inputs allocate to it.
3784 isInReg = OpInfo.isEarlyClobber || OpInfo.hasMatchingInput;
3786 case InlineAsm::isInput:
3790 case InlineAsm::isClobber:
3797 MachineFunction &MF = DAG.getMachineFunction();
3798 SmallVector<unsigned, 4> Regs;
3800 // If this is a constraint for a single physreg, or a constraint for a
3801 // register class, find it.
3802 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
3803 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
3804 OpInfo.ConstraintVT);
3806 unsigned NumRegs = 1;
3807 if (OpInfo.ConstraintVT != MVT::Other)
3808 NumRegs = TLI.getNumRegisters(OpInfo.ConstraintVT);
3810 MVT ValueVT = OpInfo.ConstraintVT;
3813 // If this is a constraint for a specific physical register, like {r17},
3815 if (PhysReg.first) {
3816 if (OpInfo.ConstraintVT == MVT::Other)
3817 ValueVT = *PhysReg.second->vt_begin();
3819 // Get the actual register value type. This is important, because the user
3820 // may have asked for (e.g.) the AX register in i32 type. We need to
3821 // remember that AX is actually i16 to get the right extension.
3822 RegVT = *PhysReg.second->vt_begin();
3824 // This is a explicit reference to a physical register.
3825 Regs.push_back(PhysReg.first);
3827 // If this is an expanded reference, add the rest of the regs to Regs.
3829 TargetRegisterClass::iterator I = PhysReg.second->begin();
3830 for (; *I != PhysReg.first; ++I)
3831 assert(I != PhysReg.second->end() && "Didn't find reg!");
3833 // Already added the first reg.
3835 for (; NumRegs; --NumRegs, ++I) {
3836 assert(I != PhysReg.second->end() && "Ran out of registers to allocate!");
3840 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
3841 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3842 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
3846 // Otherwise, if this was a reference to an LLVM register class, create vregs
3847 // for this reference.
3848 std::vector<unsigned> RegClassRegs;
3849 const TargetRegisterClass *RC = PhysReg.second;
3851 // If this is an early clobber or tied register, our regalloc doesn't know
3852 // how to maintain the constraint. If it isn't, go ahead and create vreg
3853 // and let the regalloc do the right thing.
3854 if (!OpInfo.hasMatchingInput && !OpInfo.isEarlyClobber &&
3855 // If there is some other early clobber and this is an input register,
3856 // then we are forced to pre-allocate the input reg so it doesn't
3857 // conflict with the earlyclobber.
3858 !(OpInfo.Type == InlineAsm::isInput && HasEarlyClobber)) {
3859 RegVT = *PhysReg.second->vt_begin();
3861 if (OpInfo.ConstraintVT == MVT::Other)
3864 // Create the appropriate number of virtual registers.
3865 MachineRegisterInfo &RegInfo = MF.getRegInfo();
3866 for (; NumRegs; --NumRegs)
3867 Regs.push_back(RegInfo.createVirtualRegister(PhysReg.second));
3869 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
3873 // Otherwise, we can't allocate it. Let the code below figure out how to
3874 // maintain these constraints.
3875 RegClassRegs.assign(PhysReg.second->begin(), PhysReg.second->end());
3878 // This is a reference to a register class that doesn't directly correspond
3879 // to an LLVM register class. Allocate NumRegs consecutive, available,
3880 // registers from the class.
3881 RegClassRegs = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
3882 OpInfo.ConstraintVT);
3885 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
3886 unsigned NumAllocated = 0;
3887 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
3888 unsigned Reg = RegClassRegs[i];
3889 // See if this register is available.
3890 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
3891 (isInReg && InputRegs.count(Reg))) { // Already used.
3892 // Make sure we find consecutive registers.
3897 // Check to see if this register is allocatable (i.e. don't give out the
3900 RC = isAllocatableRegister(Reg, MF, TLI, TRI);
3901 if (!RC) { // Couldn't allocate this register.
3902 // Reset NumAllocated to make sure we return consecutive registers.
3908 // Okay, this register is good, we can use it.
3911 // If we allocated enough consecutive registers, succeed.
3912 if (NumAllocated == NumRegs) {
3913 unsigned RegStart = (i-NumAllocated)+1;
3914 unsigned RegEnd = i+1;
3915 // Mark all of the allocated registers used.
3916 for (unsigned i = RegStart; i != RegEnd; ++i)
3917 Regs.push_back(RegClassRegs[i]);
3919 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
3920 OpInfo.ConstraintVT);
3921 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
3926 // Otherwise, we couldn't allocate enough registers for this.
3930 /// visitInlineAsm - Handle a call to an InlineAsm object.
3932 void SelectionDAGLowering::visitInlineAsm(CallSite CS) {
3933 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
3935 /// ConstraintOperands - Information about all of the constraints.
3936 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
3938 SDValue Chain = getRoot();
3941 std::set<unsigned> OutputRegs, InputRegs;
3943 // Do a prepass over the constraints, canonicalizing them, and building up the
3944 // ConstraintOperands list.
3945 std::vector<InlineAsm::ConstraintInfo>
3946 ConstraintInfos = IA->ParseConstraints();
3948 // SawEarlyClobber - Keep track of whether we saw an earlyclobber output
3949 // constraint. If so, we can't let the register allocator allocate any input
3950 // registers, because it will not know to avoid the earlyclobbered output reg.
3951 bool SawEarlyClobber = false;
3953 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
3954 unsigned ResNo = 0; // ResNo - The result number of the next output.
3955 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
3956 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
3957 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
3959 MVT OpVT = MVT::Other;
3961 // Compute the value type for each operand.
3962 switch (OpInfo.Type) {
3963 case InlineAsm::isOutput:
3964 // Indirect outputs just consume an argument.
3965 if (OpInfo.isIndirect) {
3966 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
3969 // The return value of the call is this value. As such, there is no
3970 // corresponding argument.
3971 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
3972 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
3973 OpVT = TLI.getValueType(STy->getElementType(ResNo));
3975 assert(ResNo == 0 && "Asm only has one result!");
3976 OpVT = TLI.getValueType(CS.getType());
3980 case InlineAsm::isInput:
3981 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
3983 case InlineAsm::isClobber:
3988 // If this is an input or an indirect output, process the call argument.
3989 // BasicBlocks are labels, currently appearing only in asm's.
3990 if (OpInfo.CallOperandVal) {
3991 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal))
3992 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
3994 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
3995 const Type *OpTy = OpInfo.CallOperandVal->getType();
3996 // If this is an indirect operand, the operand is a pointer to the
3998 if (OpInfo.isIndirect)
3999 OpTy = cast<PointerType>(OpTy)->getElementType();
4001 // If OpTy is not a single value, it may be a struct/union that we
4002 // can tile with integers.
4003 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4004 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4012 OpTy = IntegerType::get(BitSize);
4017 OpVT = TLI.getValueType(OpTy, true);
4021 OpInfo.ConstraintVT = OpVT;
4023 // Compute the constraint code and ConstraintType to use.
4024 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
4026 // Keep track of whether we see an earlyclobber.
4027 SawEarlyClobber |= OpInfo.isEarlyClobber;
4029 // If we see a clobber of a register, it is an early clobber.
4030 if (!SawEarlyClobber &&
4031 OpInfo.Type == InlineAsm::isClobber &&
4032 OpInfo.ConstraintType == TargetLowering::C_Register) {
4033 // Note that we want to ignore things that we don't track here, like
4034 // dirflag, fpsr, flags, etc.
4035 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4036 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4037 OpInfo.ConstraintVT);
4038 if (PhysReg.first || PhysReg.second) {
4039 // This is a register we know of.
4040 SawEarlyClobber = true;
4044 // If this is a memory input, and if the operand is not indirect, do what we
4045 // need to to provide an address for the memory input.
4046 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
4047 !OpInfo.isIndirect) {
4048 assert(OpInfo.Type == InlineAsm::isInput &&
4049 "Can only indirectify direct input operands!");
4051 // Memory operands really want the address of the value. If we don't have
4052 // an indirect input, put it in the constpool if we can, otherwise spill
4053 // it to a stack slot.
4055 // If the operand is a float, integer, or vector constant, spill to a
4056 // constant pool entry to get its address.
4057 Value *OpVal = OpInfo.CallOperandVal;
4058 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
4059 isa<ConstantVector>(OpVal)) {
4060 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
4061 TLI.getPointerTy());
4063 // Otherwise, create a stack slot and emit a store to it before the
4065 const Type *Ty = OpVal->getType();
4066 uint64_t TySize = TLI.getTargetData()->getABITypeSize(Ty);
4067 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
4068 MachineFunction &MF = DAG.getMachineFunction();
4069 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align);
4070 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4071 Chain = DAG.getStore(Chain, OpInfo.CallOperand, StackSlot, NULL, 0);
4072 OpInfo.CallOperand = StackSlot;
4075 // There is no longer a Value* corresponding to this operand.
4076 OpInfo.CallOperandVal = 0;
4077 // It is now an indirect operand.
4078 OpInfo.isIndirect = true;
4081 // If this constraint is for a specific register, allocate it before
4083 if (OpInfo.ConstraintType == TargetLowering::C_Register)
4084 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4086 ConstraintInfos.clear();
4089 // Second pass - Loop over all of the operands, assigning virtual or physregs
4090 // to registerclass operands.
4091 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4092 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4094 // C_Register operands have already been allocated, Other/Memory don't need
4096 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
4097 GetRegistersForValue(OpInfo, SawEarlyClobber, OutputRegs, InputRegs);
4100 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
4101 std::vector<SDValue> AsmNodeOperands;
4102 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
4103 AsmNodeOperands.push_back(
4104 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
4107 // Loop over all of the inputs, copying the operand values into the
4108 // appropriate registers and processing the output regs.
4109 RegsForValue RetValRegs;
4111 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
4112 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
4114 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
4115 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
4117 switch (OpInfo.Type) {
4118 case InlineAsm::isOutput: {
4119 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
4120 OpInfo.ConstraintType != TargetLowering::C_Register) {
4121 // Memory output, or 'other' output (e.g. 'X' constraint).
4122 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
4124 // Add information to the INLINEASM node to know about this output.
4125 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4126 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4127 TLI.getPointerTy()));
4128 AsmNodeOperands.push_back(OpInfo.CallOperand);
4132 // Otherwise, this is a register or register class output.
4134 // Copy the output from the appropriate register. Find a register that
4136 if (OpInfo.AssignedRegs.Regs.empty()) {
4137 cerr << "Couldn't allocate output reg for constraint '"
4138 << OpInfo.ConstraintCode << "'!\n";
4142 // If this is an indirect operand, store through the pointer after the
4144 if (OpInfo.isIndirect) {
4145 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
4146 OpInfo.CallOperandVal));
4148 // This is the result value of the call.
4149 assert(CS.getType() != Type::VoidTy && "Bad inline asm!");
4150 // Concatenate this output onto the outputs list.
4151 RetValRegs.append(OpInfo.AssignedRegs);
4154 // Add information to the INLINEASM node to know that this register is
4156 OpInfo.AssignedRegs.AddInlineAsmOperands(2 /*REGDEF*/, DAG,
4160 case InlineAsm::isInput: {
4161 SDValue InOperandVal = OpInfo.CallOperand;
4163 if (isdigit(OpInfo.ConstraintCode[0])) { // Matching constraint?
4164 // If this is required to match an output register we have already set,
4165 // just use its register.
4166 unsigned OperandNo = atoi(OpInfo.ConstraintCode.c_str());
4168 // Scan until we find the definition we already emitted of this operand.
4169 // When we find it, create a RegsForValue operand.
4170 unsigned CurOp = 2; // The first operand.
4171 for (; OperandNo; --OperandNo) {
4172 // Advance to the next operand.
4174 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
4175 assert(((NumOps & 7) == 2 /*REGDEF*/ ||
4176 (NumOps & 7) == 4 /*MEM*/) &&
4177 "Skipped past definitions?");
4178 CurOp += (NumOps>>3)+1;
4182 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getValue();
4183 if ((NumOps & 7) == 2 /*REGDEF*/) {
4184 // Add NumOps>>3 registers to MatchedRegs.
4185 RegsForValue MatchedRegs;
4186 MatchedRegs.TLI = &TLI;
4187 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
4188 MatchedRegs.RegVTs.push_back(AsmNodeOperands[CurOp+1].getValueType());
4189 for (unsigned i = 0, e = NumOps>>3; i != e; ++i) {
4191 cast<RegisterSDNode>(AsmNodeOperands[++CurOp])->getReg();
4192 MatchedRegs.Regs.push_back(Reg);
4195 // Use the produced MatchedRegs object to
4196 MatchedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4197 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/, DAG, AsmNodeOperands);
4200 assert((NumOps & 7) == 4/*MEM*/ && "Unknown matching constraint!");
4201 assert((NumOps >> 3) == 1 && "Unexpected number of operands");
4202 // Add information to the INLINEASM node to know about this input.
4203 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4204 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4205 TLI.getPointerTy()));
4206 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
4211 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
4212 assert(!OpInfo.isIndirect &&
4213 "Don't know how to handle indirect other inputs yet!");
4215 std::vector<SDValue> Ops;
4216 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
4219 cerr << "Invalid operand for inline asm constraint '"
4220 << OpInfo.ConstraintCode << "'!\n";
4224 // Add information to the INLINEASM node to know about this input.
4225 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
4226 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4227 TLI.getPointerTy()));
4228 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
4230 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
4231 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
4232 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
4233 "Memory operands expect pointer values");
4235 // Add information to the INLINEASM node to know about this input.
4236 unsigned ResOpType = 4/*MEM*/ | (1 << 3);
4237 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
4238 TLI.getPointerTy()));
4239 AsmNodeOperands.push_back(InOperandVal);
4243 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
4244 OpInfo.ConstraintType == TargetLowering::C_Register) &&
4245 "Unknown constraint type!");
4246 assert(!OpInfo.isIndirect &&
4247 "Don't know how to handle indirect register inputs yet!");
4249 // Copy the input into the appropriate registers.
4250 assert(!OpInfo.AssignedRegs.Regs.empty() &&
4251 "Couldn't allocate input reg!");
4253 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, Chain, &Flag);
4255 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, DAG,
4259 case InlineAsm::isClobber: {
4260 // Add the clobbered value to the operand list, so that the register
4261 // allocator is aware that the physreg got clobbered.
4262 if (!OpInfo.AssignedRegs.Regs.empty())
4263 OpInfo.AssignedRegs.AddInlineAsmOperands(2/*REGDEF*/, DAG,
4270 // Finish up input operands.
4271 AsmNodeOperands[0] = Chain;
4272 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
4274 Chain = DAG.getNode(ISD::INLINEASM,
4275 DAG.getNodeValueTypes(MVT::Other, MVT::Flag), 2,
4276 &AsmNodeOperands[0], AsmNodeOperands.size());
4277 Flag = Chain.getValue(1);
4279 // If this asm returns a register value, copy the result from that register
4280 // and set it as the value of the call.
4281 if (!RetValRegs.Regs.empty()) {
4282 SDValue Val = RetValRegs.getCopyFromRegs(DAG, Chain, &Flag);
4284 // If any of the results of the inline asm is a vector, it may have the
4285 // wrong width/num elts. This can happen for register classes that can
4286 // contain multiple different value types. The preg or vreg allocated may
4287 // not have the same VT as was expected. Convert it to the right type with
4289 if (const StructType *ResSTy = dyn_cast<StructType>(CS.getType())) {
4290 for (unsigned i = 0, e = ResSTy->getNumElements(); i != e; ++i) {
4291 if (Val.getNode()->getValueType(i).isVector())
4292 Val = DAG.getNode(ISD::BIT_CONVERT,
4293 TLI.getValueType(ResSTy->getElementType(i)), Val);
4296 if (Val.getValueType().isVector())
4297 Val = DAG.getNode(ISD::BIT_CONVERT, TLI.getValueType(CS.getType()),
4301 setValue(CS.getInstruction(), Val);
4304 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
4306 // Process indirect outputs, first output all of the flagged copies out of
4308 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
4309 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
4310 Value *Ptr = IndirectStoresToEmit[i].second;
4311 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, Chain, &Flag);
4312 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
4315 // Emit the non-flagged stores from the physregs.
4316 SmallVector<SDValue, 8> OutChains;
4317 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
4318 OutChains.push_back(DAG.getStore(Chain, StoresToEmit[i].first,
4319 getValue(StoresToEmit[i].second),
4320 StoresToEmit[i].second, 0));
4321 if (!OutChains.empty())
4322 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
4323 &OutChains[0], OutChains.size());
4328 void SelectionDAGLowering::visitMalloc(MallocInst &I) {
4329 SDValue Src = getValue(I.getOperand(0));
4331 MVT IntPtr = TLI.getPointerTy();
4333 if (IntPtr.bitsLT(Src.getValueType()))
4334 Src = DAG.getNode(ISD::TRUNCATE, IntPtr, Src);
4335 else if (IntPtr.bitsGT(Src.getValueType()))
4336 Src = DAG.getNode(ISD::ZERO_EXTEND, IntPtr, Src);
4338 // Scale the source by the type size.
4339 uint64_t ElementSize = TD->getABITypeSize(I.getType()->getElementType());
4340 Src = DAG.getNode(ISD::MUL, Src.getValueType(),
4341 Src, DAG.getIntPtrConstant(ElementSize));
4343 TargetLowering::ArgListTy Args;
4344 TargetLowering::ArgListEntry Entry;
4346 Entry.Ty = TLI.getTargetData()->getIntPtrType();
4347 Args.push_back(Entry);
4349 std::pair<SDValue,SDValue> Result =
4350 TLI.LowerCallTo(getRoot(), I.getType(), false, false, false, CallingConv::C,
4351 true, DAG.getExternalSymbol("malloc", IntPtr), Args, DAG);
4352 setValue(&I, Result.first); // Pointers always fit in registers
4353 DAG.setRoot(Result.second);
4356 void SelectionDAGLowering::visitFree(FreeInst &I) {
4357 TargetLowering::ArgListTy Args;
4358 TargetLowering::ArgListEntry Entry;
4359 Entry.Node = getValue(I.getOperand(0));
4360 Entry.Ty = TLI.getTargetData()->getIntPtrType();
4361 Args.push_back(Entry);
4362 MVT IntPtr = TLI.getPointerTy();
4363 std::pair<SDValue,SDValue> Result =
4364 TLI.LowerCallTo(getRoot(), Type::VoidTy, false, false, false,
4365 CallingConv::C, true,
4366 DAG.getExternalSymbol("free", IntPtr), Args, DAG);
4367 DAG.setRoot(Result.second);
4370 void SelectionDAGLowering::visitVAStart(CallInst &I) {
4371 DAG.setRoot(DAG.getNode(ISD::VASTART, MVT::Other, getRoot(),
4372 getValue(I.getOperand(1)),
4373 DAG.getSrcValue(I.getOperand(1))));
4376 void SelectionDAGLowering::visitVAArg(VAArgInst &I) {
4377 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getRoot(),
4378 getValue(I.getOperand(0)),
4379 DAG.getSrcValue(I.getOperand(0)));
4381 DAG.setRoot(V.getValue(1));
4384 void SelectionDAGLowering::visitVAEnd(CallInst &I) {
4385 DAG.setRoot(DAG.getNode(ISD::VAEND, MVT::Other, getRoot(),
4386 getValue(I.getOperand(1)),
4387 DAG.getSrcValue(I.getOperand(1))));
4390 void SelectionDAGLowering::visitVACopy(CallInst &I) {
4391 DAG.setRoot(DAG.getNode(ISD::VACOPY, MVT::Other, getRoot(),
4392 getValue(I.getOperand(1)),
4393 getValue(I.getOperand(2)),
4394 DAG.getSrcValue(I.getOperand(1)),
4395 DAG.getSrcValue(I.getOperand(2))));
4398 /// TargetLowering::LowerArguments - This is the default LowerArguments
4399 /// implementation, which just inserts a FORMAL_ARGUMENTS node. FIXME: When all
4400 /// targets are migrated to using FORMAL_ARGUMENTS, this hook should be
4401 /// integrated into SDISel.
4402 void TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG,
4403 SmallVectorImpl<SDValue> &ArgValues) {
4404 // Add CC# and isVararg as operands to the FORMAL_ARGUMENTS node.
4405 SmallVector<SDValue, 3+16> Ops;
4406 Ops.push_back(DAG.getRoot());
4407 Ops.push_back(DAG.getConstant(F.getCallingConv(), getPointerTy()));
4408 Ops.push_back(DAG.getConstant(F.isVarArg(), getPointerTy()));
4410 // Add one result value for each formal argument.
4411 SmallVector<MVT, 16> RetVals;
4413 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
4415 SmallVector<MVT, 4> ValueVTs;
4416 ComputeValueVTs(*this, I->getType(), ValueVTs);
4417 for (unsigned Value = 0, NumValues = ValueVTs.size();
4418 Value != NumValues; ++Value) {
4419 MVT VT = ValueVTs[Value];
4420 const Type *ArgTy = VT.getTypeForMVT();
4421 ISD::ArgFlagsTy Flags;
4422 unsigned OriginalAlignment =
4423 getTargetData()->getABITypeAlignment(ArgTy);
4425 if (F.paramHasAttr(j, ParamAttr::ZExt))
4427 if (F.paramHasAttr(j, ParamAttr::SExt))
4429 if (F.paramHasAttr(j, ParamAttr::InReg))
4431 if (F.paramHasAttr(j, ParamAttr::StructRet))
4433 if (F.paramHasAttr(j, ParamAttr::ByVal)) {
4435 const PointerType *Ty = cast<PointerType>(I->getType());
4436 const Type *ElementTy = Ty->getElementType();
4437 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4438 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4439 // For ByVal, alignment should be passed from FE. BE will guess if
4440 // this info is not there but there are cases it cannot get right.
4441 if (F.getParamAlignment(j))
4442 FrameAlign = F.getParamAlignment(j);
4443 Flags.setByValAlign(FrameAlign);
4444 Flags.setByValSize(FrameSize);
4446 if (F.paramHasAttr(j, ParamAttr::Nest))
4448 Flags.setOrigAlign(OriginalAlignment);
4450 MVT RegisterVT = getRegisterType(VT);
4451 unsigned NumRegs = getNumRegisters(VT);
4452 for (unsigned i = 0; i != NumRegs; ++i) {
4453 RetVals.push_back(RegisterVT);
4454 ISD::ArgFlagsTy MyFlags = Flags;
4455 if (NumRegs > 1 && i == 0)
4457 // if it isn't first piece, alignment must be 1
4459 MyFlags.setOrigAlign(1);
4460 Ops.push_back(DAG.getArgFlags(MyFlags));
4465 RetVals.push_back(MVT::Other);
4468 SDNode *Result = DAG.getNode(ISD::FORMAL_ARGUMENTS,
4469 DAG.getVTList(&RetVals[0], RetVals.size()),
4470 &Ops[0], Ops.size()).getNode();
4472 // Prelower FORMAL_ARGUMENTS. This isn't required for functionality, but
4473 // allows exposing the loads that may be part of the argument access to the
4474 // first DAGCombiner pass.
4475 SDValue TmpRes = LowerOperation(SDValue(Result, 0), DAG);
4477 // The number of results should match up, except that the lowered one may have
4478 // an extra flag result.
4479 assert((Result->getNumValues() == TmpRes.getNode()->getNumValues() ||
4480 (Result->getNumValues()+1 == TmpRes.getNode()->getNumValues() &&
4481 TmpRes.getValue(Result->getNumValues()).getValueType() == MVT::Flag))
4482 && "Lowering produced unexpected number of results!");
4484 // The FORMAL_ARGUMENTS node itself is likely no longer needed.
4485 if (Result != TmpRes.getNode() && Result->use_empty()) {
4486 HandleSDNode Dummy(DAG.getRoot());
4487 DAG.RemoveDeadNode(Result);
4490 Result = TmpRes.getNode();
4492 unsigned NumArgRegs = Result->getNumValues() - 1;
4493 DAG.setRoot(SDValue(Result, NumArgRegs));
4495 // Set up the return result vector.
4498 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
4500 SmallVector<MVT, 4> ValueVTs;
4501 ComputeValueVTs(*this, I->getType(), ValueVTs);
4502 for (unsigned Value = 0, NumValues = ValueVTs.size();
4503 Value != NumValues; ++Value) {
4504 MVT VT = ValueVTs[Value];
4505 MVT PartVT = getRegisterType(VT);
4507 unsigned NumParts = getNumRegisters(VT);
4508 SmallVector<SDValue, 4> Parts(NumParts);
4509 for (unsigned j = 0; j != NumParts; ++j)
4510 Parts[j] = SDValue(Result, i++);
4512 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4513 if (F.paramHasAttr(Idx, ParamAttr::SExt))
4514 AssertOp = ISD::AssertSext;
4515 else if (F.paramHasAttr(Idx, ParamAttr::ZExt))
4516 AssertOp = ISD::AssertZext;
4518 ArgValues.push_back(getCopyFromParts(DAG, &Parts[0], NumParts, PartVT, VT,
4522 assert(i == NumArgRegs && "Argument register count mismatch!");
4526 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
4527 /// implementation, which just inserts an ISD::CALL node, which is later custom
4528 /// lowered by the target to something concrete. FIXME: When all targets are
4529 /// migrated to using ISD::CALL, this hook should be integrated into SDISel.
4530 std::pair<SDValue, SDValue>
4531 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
4532 bool RetSExt, bool RetZExt, bool isVarArg,
4533 unsigned CallingConv, bool isTailCall,
4535 ArgListTy &Args, SelectionDAG &DAG) {
4536 SmallVector<SDValue, 32> Ops;
4537 Ops.push_back(Chain); // Op#0 - Chain
4538 Ops.push_back(DAG.getConstant(CallingConv, getPointerTy())); // Op#1 - CC
4539 Ops.push_back(DAG.getConstant(isVarArg, getPointerTy())); // Op#2 - VarArg
4540 Ops.push_back(DAG.getConstant(isTailCall, getPointerTy())); // Op#3 - Tail
4541 Ops.push_back(Callee);
4543 // Handle all of the outgoing arguments.
4544 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
4545 SmallVector<MVT, 4> ValueVTs;
4546 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
4547 for (unsigned Value = 0, NumValues = ValueVTs.size();
4548 Value != NumValues; ++Value) {
4549 MVT VT = ValueVTs[Value];
4550 const Type *ArgTy = VT.getTypeForMVT();
4551 SDValue Op = SDValue(Args[i].Node.getNode(), Args[i].Node.getResNo() + Value);
4552 ISD::ArgFlagsTy Flags;
4553 unsigned OriginalAlignment =
4554 getTargetData()->getABITypeAlignment(ArgTy);
4560 if (Args[i].isInReg)
4564 if (Args[i].isByVal) {
4566 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
4567 const Type *ElementTy = Ty->getElementType();
4568 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
4569 unsigned FrameSize = getTargetData()->getABITypeSize(ElementTy);
4570 // For ByVal, alignment should come from FE. BE will guess if this
4571 // info is not there but there are cases it cannot get right.
4572 if (Args[i].Alignment)
4573 FrameAlign = Args[i].Alignment;
4574 Flags.setByValAlign(FrameAlign);
4575 Flags.setByValSize(FrameSize);
4579 Flags.setOrigAlign(OriginalAlignment);
4581 MVT PartVT = getRegisterType(VT);
4582 unsigned NumParts = getNumRegisters(VT);
4583 SmallVector<SDValue, 4> Parts(NumParts);
4584 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
4587 ExtendKind = ISD::SIGN_EXTEND;
4588 else if (Args[i].isZExt)
4589 ExtendKind = ISD::ZERO_EXTEND;
4591 getCopyToParts(DAG, Op, &Parts[0], NumParts, PartVT, ExtendKind);
4593 for (unsigned i = 0; i != NumParts; ++i) {
4594 // if it isn't first piece, alignment must be 1
4595 ISD::ArgFlagsTy MyFlags = Flags;
4596 if (NumParts > 1 && i == 0)
4599 MyFlags.setOrigAlign(1);
4601 Ops.push_back(Parts[i]);
4602 Ops.push_back(DAG.getArgFlags(MyFlags));
4607 // Figure out the result value types. We start by making a list of
4608 // the potentially illegal return value types.
4609 SmallVector<MVT, 4> LoweredRetTys;
4610 SmallVector<MVT, 4> RetTys;
4611 ComputeValueVTs(*this, RetTy, RetTys);
4613 // Then we translate that to a list of legal types.
4614 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4616 MVT RegisterVT = getRegisterType(VT);
4617 unsigned NumRegs = getNumRegisters(VT);
4618 for (unsigned i = 0; i != NumRegs; ++i)
4619 LoweredRetTys.push_back(RegisterVT);
4622 LoweredRetTys.push_back(MVT::Other); // Always has a chain.
4624 // Create the CALL node.
4625 SDValue Res = DAG.getNode(ISD::CALL,
4626 DAG.getVTList(&LoweredRetTys[0],
4627 LoweredRetTys.size()),
4628 &Ops[0], Ops.size());
4629 Chain = Res.getValue(LoweredRetTys.size() - 1);
4631 // Gather up the call result into a single value.
4632 if (RetTy != Type::VoidTy) {
4633 ISD::NodeType AssertOp = ISD::DELETED_NODE;
4636 AssertOp = ISD::AssertSext;
4638 AssertOp = ISD::AssertZext;
4640 SmallVector<SDValue, 4> ReturnValues;
4642 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
4644 MVT RegisterVT = getRegisterType(VT);
4645 unsigned NumRegs = getNumRegisters(VT);
4646 unsigned RegNoEnd = NumRegs + RegNo;
4647 SmallVector<SDValue, 4> Results;
4648 for (; RegNo != RegNoEnd; ++RegNo)
4649 Results.push_back(Res.getValue(RegNo));
4650 SDValue ReturnValue =
4651 getCopyFromParts(DAG, &Results[0], NumRegs, RegisterVT, VT,
4653 ReturnValues.push_back(ReturnValue);
4655 Res = DAG.getMergeValues(DAG.getVTList(&RetTys[0], RetTys.size()),
4656 &ReturnValues[0], ReturnValues.size());
4659 return std::make_pair(Res, Chain);
4662 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
4663 assert(0 && "LowerOperation not implemented for this target!");
4669 void SelectionDAGLowering::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
4670 SDValue Op = getValue(V);
4671 assert((Op.getOpcode() != ISD::CopyFromReg ||
4672 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
4673 "Copy from a reg to the same reg!");
4674 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
4676 RegsForValue RFV(TLI, Reg, V->getType());
4677 SDValue Chain = DAG.getEntryNode();
4678 RFV.getCopyToRegs(Op, DAG, Chain, 0);
4679 PendingExports.push_back(Chain);
4682 #include "llvm/CodeGen/SelectionDAGISel.h"
4684 void SelectionDAGISel::
4685 LowerArguments(BasicBlock *LLVMBB) {
4686 // If this is the entry block, emit arguments.
4687 Function &F = *LLVMBB->getParent();
4688 SDValue OldRoot = SDL->DAG.getRoot();
4689 SmallVector<SDValue, 16> Args;
4690 TLI.LowerArguments(F, SDL->DAG, Args);
4693 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end();
4695 SmallVector<MVT, 4> ValueVTs;
4696 ComputeValueVTs(TLI, AI->getType(), ValueVTs);
4697 unsigned NumValues = ValueVTs.size();
4698 if (!AI->use_empty()) {
4699 SDL->setValue(AI, SDL->DAG.getMergeValues(&Args[a], NumValues));
4700 // If this argument is live outside of the entry block, insert a copy from
4701 // whereever we got it to the vreg that other BB's will reference it as.
4702 DenseMap<const Value*, unsigned>::iterator VMI=FuncInfo->ValueMap.find(AI);
4703 if (VMI != FuncInfo->ValueMap.end()) {
4704 SDL->CopyValueToVirtualRegister(AI, VMI->second);
4710 // Finally, if the target has anything special to do, allow it to do so.
4711 // FIXME: this should insert code into the DAG!
4712 EmitFunctionEntryCode(F, SDL->DAG.getMachineFunction());
4715 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
4716 /// ensure constants are generated when needed. Remember the virtual registers
4717 /// that need to be added to the Machine PHI nodes as input. We cannot just
4718 /// directly add them, because expansion might result in multiple MBB's for one
4719 /// BB. As such, the start of the BB might correspond to a different MBB than
4723 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
4724 TerminatorInst *TI = LLVMBB->getTerminator();
4726 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
4728 // Check successor nodes' PHI nodes that expect a constant to be available
4730 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4731 BasicBlock *SuccBB = TI->getSuccessor(succ);
4732 if (!isa<PHINode>(SuccBB->begin())) continue;
4733 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
4735 // If this terminator has multiple identical successors (common for
4736 // switches), only handle each succ once.
4737 if (!SuccsHandled.insert(SuccMBB)) continue;
4739 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
4742 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4743 // nodes and Machine PHI nodes, but the incoming operands have not been
4745 for (BasicBlock::iterator I = SuccBB->begin();
4746 (PN = dyn_cast<PHINode>(I)); ++I) {
4747 // Ignore dead phi's.
4748 if (PN->use_empty()) continue;
4751 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
4753 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
4754 unsigned &RegOut = SDL->ConstantsOut[C];
4756 RegOut = FuncInfo->CreateRegForValue(C);
4757 SDL->CopyValueToVirtualRegister(C, RegOut);
4761 Reg = FuncInfo->ValueMap[PHIOp];
4763 assert(isa<AllocaInst>(PHIOp) &&
4764 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
4765 "Didn't codegen value into a register!??");
4766 Reg = FuncInfo->CreateRegForValue(PHIOp);
4767 SDL->CopyValueToVirtualRegister(PHIOp, Reg);
4771 // Remember that this register needs to added to the machine PHI node as
4772 // the input for this MBB.
4773 SmallVector<MVT, 4> ValueVTs;
4774 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
4775 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
4776 MVT VT = ValueVTs[vti];
4777 unsigned NumRegisters = TLI.getNumRegisters(VT);
4778 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
4779 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
4780 Reg += NumRegisters;
4784 SDL->ConstantsOut.clear();
4787 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
4788 /// supports legal types, and it emits MachineInstrs directly instead of
4789 /// creating SelectionDAG nodes.
4792 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
4794 TerminatorInst *TI = LLVMBB->getTerminator();
4796 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
4797 unsigned OrigNumPHINodesToUpdate = SDL->PHINodesToUpdate.size();
4799 // Check successor nodes' PHI nodes that expect a constant to be available
4801 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
4802 BasicBlock *SuccBB = TI->getSuccessor(succ);
4803 if (!isa<PHINode>(SuccBB->begin())) continue;
4804 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
4806 // If this terminator has multiple identical successors (common for
4807 // switches), only handle each succ once.
4808 if (!SuccsHandled.insert(SuccMBB)) continue;
4810 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
4813 // At this point we know that there is a 1-1 correspondence between LLVM PHI
4814 // nodes and Machine PHI nodes, but the incoming operands have not been
4816 for (BasicBlock::iterator I = SuccBB->begin();
4817 (PN = dyn_cast<PHINode>(I)); ++I) {
4818 // Ignore dead phi's.
4819 if (PN->use_empty()) continue;
4821 // Only handle legal types. Two interesting things to note here. First,
4822 // by bailing out early, we may leave behind some dead instructions,
4823 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
4824 // own moves. Second, this check is necessary becuase FastISel doesn't
4825 // use CreateRegForValue to create registers, so it always creates
4826 // exactly one register for each non-void instruction.
4827 MVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
4828 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
4829 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
4833 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
4835 unsigned Reg = F->getRegForValue(PHIOp);
4837 SDL->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
4840 SDL->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));