1 //===-- SelectionDAGBuilder.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 "SelectionDAGBuilder.h"
16 #include "FunctionLoweringInfo.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/SmallSet.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Constants.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Function.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/InlineAsm.h"
26 #include "llvm/Instructions.h"
27 #include "llvm/Intrinsics.h"
28 #include "llvm/IntrinsicInst.h"
29 #include "llvm/LLVMContext.h"
30 #include "llvm/Module.h"
31 #include "llvm/CodeGen/FastISel.h"
32 #include "llvm/CodeGen/GCStrategy.h"
33 #include "llvm/CodeGen/GCMetadata.h"
34 #include "llvm/CodeGen/MachineFunction.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineInstrBuilder.h"
37 #include "llvm/CodeGen/MachineJumpTableInfo.h"
38 #include "llvm/CodeGen/MachineModuleInfo.h"
39 #include "llvm/CodeGen/MachineRegisterInfo.h"
40 #include "llvm/CodeGen/PseudoSourceValue.h"
41 #include "llvm/CodeGen/SelectionDAG.h"
42 #include "llvm/CodeGen/DwarfWriter.h"
43 #include "llvm/Analysis/DebugInfo.h"
44 #include "llvm/Target/TargetRegisterInfo.h"
45 #include "llvm/Target/TargetData.h"
46 #include "llvm/Target/TargetFrameInfo.h"
47 #include "llvm/Target/TargetInstrInfo.h"
48 #include "llvm/Target/TargetIntrinsicInfo.h"
49 #include "llvm/Target/TargetLowering.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include "llvm/Support/Compiler.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Debug.h"
54 #include "llvm/Support/ErrorHandling.h"
55 #include "llvm/Support/MathExtras.h"
56 #include "llvm/Support/raw_ostream.h"
60 /// LimitFloatPrecision - Generate low-precision inline sequences for
61 /// some float libcalls (6, 8 or 12 bits).
62 static unsigned LimitFloatPrecision;
64 static cl::opt<unsigned, true>
65 LimitFPPrecision("limit-float-precision",
66 cl::desc("Generate low-precision inline sequences "
67 "for some float libcalls"),
68 cl::location(LimitFloatPrecision),
72 /// RegsForValue - This struct represents the registers (physical or virtual)
73 /// that a particular set of values is assigned, and the type information about
74 /// the value. The most common situation is to represent one value at a time,
75 /// but struct or array values are handled element-wise as multiple values.
76 /// The splitting of aggregates is performed recursively, so that we never
77 /// have aggregate-typed registers. The values at this point do not necessarily
78 /// have legal types, so each value may require one or more registers of some
82 /// TLI - The TargetLowering object.
84 const TargetLowering *TLI;
86 /// ValueVTs - The value types of the values, which may not be legal, and
87 /// may need be promoted or synthesized from one or more registers.
89 SmallVector<EVT, 4> ValueVTs;
91 /// RegVTs - The value types of the registers. This is the same size as
92 /// ValueVTs and it records, for each value, what the type of the assigned
93 /// register or registers are. (Individual values are never synthesized
94 /// from more than one type of register.)
96 /// With virtual registers, the contents of RegVTs is redundant with TLI's
97 /// getRegisterType member function, however when with physical registers
98 /// it is necessary to have a separate record of the types.
100 SmallVector<EVT, 4> RegVTs;
102 /// Regs - This list holds the registers assigned to the values.
103 /// Each legal or promoted value requires one register, and each
104 /// expanded value requires multiple registers.
106 SmallVector<unsigned, 4> Regs;
108 RegsForValue() : TLI(0) {}
110 RegsForValue(const TargetLowering &tli,
111 const SmallVector<unsigned, 4> ®s,
112 EVT regvt, EVT valuevt)
113 : TLI(&tli), ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
114 RegsForValue(const TargetLowering &tli,
115 const SmallVector<unsigned, 4> ®s,
116 const SmallVector<EVT, 4> ®vts,
117 const SmallVector<EVT, 4> &valuevts)
118 : TLI(&tli), ValueVTs(valuevts), RegVTs(regvts), Regs(regs) {}
119 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
120 unsigned Reg, const Type *Ty) : TLI(&tli) {
121 ComputeValueVTs(tli, Ty, ValueVTs);
123 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
124 EVT ValueVT = ValueVTs[Value];
125 unsigned NumRegs = TLI->getNumRegisters(Context, ValueVT);
126 EVT RegisterVT = TLI->getRegisterType(Context, ValueVT);
127 for (unsigned i = 0; i != NumRegs; ++i)
128 Regs.push_back(Reg + i);
129 RegVTs.push_back(RegisterVT);
134 /// append - Add the specified values to this one.
135 void append(const RegsForValue &RHS) {
137 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
138 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
139 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
143 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
144 /// this value and returns the result as a ValueVTs value. This uses
145 /// Chain/Flag as the input and updates them for the output Chain/Flag.
146 /// If the Flag pointer is NULL, no flag is used.
147 SDValue getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
148 SDValue &Chain, SDValue *Flag) const;
150 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
151 /// specified value into the registers specified by this object. This uses
152 /// Chain/Flag as the input and updates them for the output Chain/Flag.
153 /// If the Flag pointer is NULL, no flag is used.
154 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
155 SDValue &Chain, SDValue *Flag) const;
157 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
158 /// operand list. This adds the code marker, matching input operand index
159 /// (if applicable), and includes the number of values added into it.
160 void AddInlineAsmOperands(unsigned Code,
161 bool HasMatching, unsigned MatchingIdx,
162 SelectionDAG &DAG, std::vector<SDValue> &Ops) const;
166 /// getCopyFromParts - Create a value that contains the specified legal parts
167 /// combined into the value they represent. If the parts combine to a type
168 /// larger then ValueVT then AssertOp can be used to specify whether the extra
169 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
170 /// (ISD::AssertSext).
171 static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc dl,
172 const SDValue *Parts,
173 unsigned NumParts, EVT PartVT, EVT ValueVT,
174 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
175 assert(NumParts > 0 && "No parts to assemble!");
176 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
177 SDValue Val = Parts[0];
180 // Assemble the value from multiple parts.
181 if (!ValueVT.isVector() && ValueVT.isInteger()) {
182 unsigned PartBits = PartVT.getSizeInBits();
183 unsigned ValueBits = ValueVT.getSizeInBits();
185 // Assemble the power of 2 part.
186 unsigned RoundParts = NumParts & (NumParts - 1) ?
187 1 << Log2_32(NumParts) : NumParts;
188 unsigned RoundBits = PartBits * RoundParts;
189 EVT RoundVT = RoundBits == ValueBits ?
190 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
193 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
195 if (RoundParts > 2) {
196 Lo = getCopyFromParts(DAG, dl, Parts, RoundParts/2, PartVT, HalfVT);
197 Hi = getCopyFromParts(DAG, dl, Parts+RoundParts/2, RoundParts/2,
200 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[0]);
201 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, HalfVT, Parts[1]);
203 if (TLI.isBigEndian())
205 Val = DAG.getNode(ISD::BUILD_PAIR, dl, RoundVT, Lo, Hi);
207 if (RoundParts < NumParts) {
208 // Assemble the trailing non-power-of-2 part.
209 unsigned OddParts = NumParts - RoundParts;
210 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
211 Hi = getCopyFromParts(DAG, dl,
212 Parts+RoundParts, OddParts, PartVT, OddVT);
214 // Combine the round and odd parts.
216 if (TLI.isBigEndian())
218 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
219 Hi = DAG.getNode(ISD::ANY_EXTEND, dl, TotalVT, Hi);
220 Hi = DAG.getNode(ISD::SHL, dl, TotalVT, Hi,
221 DAG.getConstant(Lo.getValueType().getSizeInBits(),
222 TLI.getPointerTy()));
223 Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, TotalVT, Lo);
224 Val = DAG.getNode(ISD::OR, dl, TotalVT, Lo, Hi);
226 } else if (ValueVT.isVector()) {
227 // Handle a multi-element vector.
228 EVT IntermediateVT, RegisterVT;
229 unsigned NumIntermediates;
231 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
232 NumIntermediates, RegisterVT);
233 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
234 NumParts = NumRegs; // Silence a compiler warning.
235 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
236 assert(RegisterVT == Parts[0].getValueType() &&
237 "Part type doesn't match part!");
239 // Assemble the parts into intermediate operands.
240 SmallVector<SDValue, 8> Ops(NumIntermediates);
241 if (NumIntermediates == NumParts) {
242 // If the register was not expanded, truncate or copy the value,
244 for (unsigned i = 0; i != NumParts; ++i)
245 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i], 1,
246 PartVT, IntermediateVT);
247 } else if (NumParts > 0) {
248 // If the intermediate type was expanded, build the intermediate operands
250 assert(NumParts % NumIntermediates == 0 &&
251 "Must expand into a divisible number of parts!");
252 unsigned Factor = NumParts / NumIntermediates;
253 for (unsigned i = 0; i != NumIntermediates; ++i)
254 Ops[i] = getCopyFromParts(DAG, dl, &Parts[i * Factor], Factor,
255 PartVT, IntermediateVT);
258 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the intermediate
260 Val = DAG.getNode(IntermediateVT.isVector() ?
261 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, dl,
262 ValueVT, &Ops[0], NumIntermediates);
263 } else if (PartVT.isFloatingPoint()) {
264 // FP split into multiple FP parts (for ppcf128)
265 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
268 Lo = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[0]);
269 Hi = DAG.getNode(ISD::BIT_CONVERT, dl, EVT(MVT::f64), Parts[1]);
270 if (TLI.isBigEndian())
272 Val = DAG.getNode(ISD::BUILD_PAIR, dl, ValueVT, Lo, Hi);
274 // FP split into integer parts (soft fp)
275 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
276 !PartVT.isVector() && "Unexpected split");
277 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
278 Val = getCopyFromParts(DAG, dl, Parts, NumParts, PartVT, IntVT);
282 // There is now one part, held in Val. Correct it to match ValueVT.
283 PartVT = Val.getValueType();
285 if (PartVT == ValueVT)
288 if (PartVT.isVector()) {
289 assert(ValueVT.isVector() && "Unknown vector conversion!");
290 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
293 if (ValueVT.isVector()) {
294 assert(ValueVT.getVectorElementType() == PartVT &&
295 ValueVT.getVectorNumElements() == 1 &&
296 "Only trivial scalar-to-vector conversions should get here!");
297 return DAG.getNode(ISD::BUILD_VECTOR, dl, ValueVT, Val);
300 if (PartVT.isInteger() &&
301 ValueVT.isInteger()) {
302 if (ValueVT.bitsLT(PartVT)) {
303 // For a truncate, see if we have any information to
304 // indicate whether the truncated bits will always be
305 // zero or sign-extension.
306 if (AssertOp != ISD::DELETED_NODE)
307 Val = DAG.getNode(AssertOp, dl, PartVT, Val,
308 DAG.getValueType(ValueVT));
309 return DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
311 return DAG.getNode(ISD::ANY_EXTEND, dl, ValueVT, Val);
315 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
316 if (ValueVT.bitsLT(Val.getValueType()))
317 // FP_ROUND's are always exact here.
318 return DAG.getNode(ISD::FP_ROUND, dl, ValueVT, Val,
319 DAG.getIntPtrConstant(1));
320 return DAG.getNode(ISD::FP_EXTEND, dl, ValueVT, Val);
323 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
324 return DAG.getNode(ISD::BIT_CONVERT, dl, ValueVT, Val);
326 llvm_unreachable("Unknown mismatch!");
330 /// getCopyToParts - Create a series of nodes that contain the specified value
331 /// split into legal parts. If the parts contain more bits than Val, then, for
332 /// integers, ExtendKind can be used to specify how to generate the extra bits.
333 static void getCopyToParts(SelectionDAG &DAG, DebugLoc dl, SDValue Val,
334 SDValue *Parts, unsigned NumParts, EVT PartVT,
335 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
336 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
337 EVT PtrVT = TLI.getPointerTy();
338 EVT ValueVT = Val.getValueType();
339 unsigned PartBits = PartVT.getSizeInBits();
340 unsigned OrigNumParts = NumParts;
341 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
346 if (!ValueVT.isVector()) {
347 if (PartVT == ValueVT) {
348 assert(NumParts == 1 && "No-op copy with multiple parts!");
353 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
354 // If the parts cover more bits than the value has, promote the value.
355 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
356 assert(NumParts == 1 && "Do not know what to promote to!");
357 Val = DAG.getNode(ISD::FP_EXTEND, dl, PartVT, Val);
358 } else if (PartVT.isInteger() && ValueVT.isInteger()) {
359 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
360 Val = DAG.getNode(ExtendKind, dl, ValueVT, Val);
362 llvm_unreachable("Unknown mismatch!");
364 } else if (PartBits == ValueVT.getSizeInBits()) {
365 // Different types of the same size.
366 assert(NumParts == 1 && PartVT != ValueVT);
367 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
368 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
369 // If the parts cover less bits than value has, truncate the value.
370 if (PartVT.isInteger() && ValueVT.isInteger()) {
371 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
372 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
374 llvm_unreachable("Unknown mismatch!");
378 // The value may have changed - recompute ValueVT.
379 ValueVT = Val.getValueType();
380 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
381 "Failed to tile the value with PartVT!");
384 assert(PartVT == ValueVT && "Type conversion failed!");
389 // Expand the value into multiple parts.
390 if (NumParts & (NumParts - 1)) {
391 // The number of parts is not a power of 2. Split off and copy the tail.
392 assert(PartVT.isInteger() && ValueVT.isInteger() &&
393 "Do not know what to expand to!");
394 unsigned RoundParts = 1 << Log2_32(NumParts);
395 unsigned RoundBits = RoundParts * PartBits;
396 unsigned OddParts = NumParts - RoundParts;
397 SDValue OddVal = DAG.getNode(ISD::SRL, dl, ValueVT, Val,
398 DAG.getConstant(RoundBits,
399 TLI.getPointerTy()));
400 getCopyToParts(DAG, dl, OddVal, Parts + RoundParts, OddParts, PartVT);
401 if (TLI.isBigEndian())
402 // The odd parts were reversed by getCopyToParts - unreverse them.
403 std::reverse(Parts + RoundParts, Parts + NumParts);
404 NumParts = RoundParts;
405 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
406 Val = DAG.getNode(ISD::TRUNCATE, dl, ValueVT, Val);
409 // The number of parts is a power of 2. Repeatedly bisect the value using
411 Parts[0] = DAG.getNode(ISD::BIT_CONVERT, dl,
412 EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits()),
414 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
415 for (unsigned i = 0; i < NumParts; i += StepSize) {
416 unsigned ThisBits = StepSize * PartBits / 2;
417 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
418 SDValue &Part0 = Parts[i];
419 SDValue &Part1 = Parts[i+StepSize/2];
421 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
423 DAG.getConstant(1, PtrVT));
424 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, dl,
426 DAG.getConstant(0, PtrVT));
428 if (ThisBits == PartBits && ThisVT != PartVT) {
429 Part0 = DAG.getNode(ISD::BIT_CONVERT, dl,
431 Part1 = DAG.getNode(ISD::BIT_CONVERT, dl,
437 if (TLI.isBigEndian())
438 std::reverse(Parts, Parts + OrigNumParts);
445 if (PartVT != ValueVT) {
446 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
447 Val = DAG.getNode(ISD::BIT_CONVERT, dl, PartVT, Val);
449 assert(ValueVT.getVectorElementType() == PartVT &&
450 ValueVT.getVectorNumElements() == 1 &&
451 "Only trivial vector-to-scalar conversions should get here!");
452 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
454 DAG.getConstant(0, PtrVT));
462 // Handle a multi-element vector.
463 EVT IntermediateVT, RegisterVT;
464 unsigned NumIntermediates;
465 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
466 IntermediateVT, NumIntermediates, RegisterVT);
467 unsigned NumElements = ValueVT.getVectorNumElements();
469 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
470 NumParts = NumRegs; // Silence a compiler warning.
471 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
473 // Split the vector into intermediate operands.
474 SmallVector<SDValue, 8> Ops(NumIntermediates);
475 for (unsigned i = 0; i != NumIntermediates; ++i)
476 if (IntermediateVT.isVector())
477 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl,
479 DAG.getConstant(i * (NumElements / NumIntermediates),
482 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
484 DAG.getConstant(i, PtrVT));
486 // Split the intermediate operands into legal parts.
487 if (NumParts == NumIntermediates) {
488 // If the register was not expanded, promote or copy the value,
490 for (unsigned i = 0; i != NumParts; ++i)
491 getCopyToParts(DAG, dl, Ops[i], &Parts[i], 1, PartVT);
492 } else if (NumParts > 0) {
493 // If the intermediate type was expanded, split each the value into
495 assert(NumParts % NumIntermediates == 0 &&
496 "Must expand into a divisible number of parts!");
497 unsigned Factor = NumParts / NumIntermediates;
498 for (unsigned i = 0; i != NumIntermediates; ++i)
499 getCopyToParts(DAG, dl, Ops[i], &Parts[i * Factor], Factor, PartVT);
504 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
507 TD = DAG.getTarget().getTargetData();
510 /// clear - Clear out the curret SelectionDAG and the associated
511 /// state and prepare this SelectionDAGBuilder object to be used
512 /// for a new block. This doesn't clear out information about
513 /// additional blocks that are needed to complete switch lowering
514 /// or PHI node updating; that information is cleared out as it is
516 void SelectionDAGBuilder::clear() {
518 PendingLoads.clear();
519 PendingExports.clear();
522 CurDebugLoc = DebugLoc::getUnknownLoc();
526 /// getRoot - Return the current virtual root of the Selection DAG,
527 /// flushing any PendingLoad items. This must be done before emitting
528 /// a store or any other node that may need to be ordered after any
529 /// prior load instructions.
531 SDValue SelectionDAGBuilder::getRoot() {
532 if (PendingLoads.empty())
533 return DAG.getRoot();
535 if (PendingLoads.size() == 1) {
536 SDValue Root = PendingLoads[0];
538 PendingLoads.clear();
542 // Otherwise, we have to make a token factor node.
543 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
544 &PendingLoads[0], PendingLoads.size());
545 PendingLoads.clear();
550 /// getControlRoot - Similar to getRoot, but instead of flushing all the
551 /// PendingLoad items, flush all the PendingExports items. It is necessary
552 /// to do this before emitting a terminator instruction.
554 SDValue SelectionDAGBuilder::getControlRoot() {
555 SDValue Root = DAG.getRoot();
557 if (PendingExports.empty())
560 // Turn all of the CopyToReg chains into one factored node.
561 if (Root.getOpcode() != ISD::EntryToken) {
562 unsigned i = 0, e = PendingExports.size();
563 for (; i != e; ++i) {
564 assert(PendingExports[i].getNode()->getNumOperands() > 1);
565 if (PendingExports[i].getNode()->getOperand(0) == Root)
566 break; // Don't add the root if we already indirectly depend on it.
570 PendingExports.push_back(Root);
573 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
575 PendingExports.size());
576 PendingExports.clear();
581 void SelectionDAGBuilder::visit(Instruction &I) {
582 visit(I.getOpcode(), I);
585 void SelectionDAGBuilder::visit(unsigned Opcode, User &I) {
586 // We're processing a new instruction.
589 // Note: this doesn't use InstVisitor, because it has to work with
590 // ConstantExpr's in addition to instructions.
592 default: llvm_unreachable("Unknown instruction type encountered!");
593 // Build the switch statement using the Instruction.def file.
594 #define HANDLE_INST(NUM, OPCODE, CLASS) \
595 case Instruction::OPCODE: return visit##OPCODE((CLASS&)I);
596 #include "llvm/Instruction.def"
600 SDValue SelectionDAGBuilder::getValue(const Value *V) {
601 SDValue &N = NodeMap[V];
602 if (N.getNode()) return N;
604 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V))) {
605 EVT VT = TLI.getValueType(V->getType(), true);
607 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
608 return N = DAG.getConstant(*CI, VT);
610 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
611 return N = DAG.getGlobalAddress(GV, VT);
613 if (isa<ConstantPointerNull>(C))
614 return N = DAG.getConstant(0, TLI.getPointerTy());
616 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C))
617 return N = DAG.getConstantFP(*CFP, VT);
619 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
620 return N = DAG.getUNDEF(VT);
622 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
623 visit(CE->getOpcode(), *CE);
624 SDValue N1 = NodeMap[V];
625 assert(N1.getNode() && "visit didn't populate the ValueMap!");
629 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
630 SmallVector<SDValue, 4> Constants;
631 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
633 SDNode *Val = getValue(*OI).getNode();
634 // If the operand is an empty aggregate, there are no values.
636 // Add each leaf value from the operand to the Constants list
637 // to form a flattened list of all the values.
638 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
639 Constants.push_back(SDValue(Val, i));
641 return DAG.getMergeValues(&Constants[0], Constants.size(),
645 if (isa<StructType>(C->getType()) || isa<ArrayType>(C->getType())) {
646 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
647 "Unknown struct or array constant!");
649 SmallVector<EVT, 4> ValueVTs;
650 ComputeValueVTs(TLI, C->getType(), ValueVTs);
651 unsigned NumElts = ValueVTs.size();
653 return SDValue(); // empty struct
654 SmallVector<SDValue, 4> Constants(NumElts);
655 for (unsigned i = 0; i != NumElts; ++i) {
656 EVT EltVT = ValueVTs[i];
657 if (isa<UndefValue>(C))
658 Constants[i] = DAG.getUNDEF(EltVT);
659 else if (EltVT.isFloatingPoint())
660 Constants[i] = DAG.getConstantFP(0, EltVT);
662 Constants[i] = DAG.getConstant(0, EltVT);
664 return DAG.getMergeValues(&Constants[0], NumElts, getCurDebugLoc());
667 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
668 return DAG.getBlockAddress(BA, VT);
670 const VectorType *VecTy = cast<VectorType>(V->getType());
671 unsigned NumElements = VecTy->getNumElements();
673 // Now that we know the number and type of the elements, get that number of
674 // elements into the Ops array based on what kind of constant it is.
675 SmallVector<SDValue, 16> Ops;
676 if (ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
677 for (unsigned i = 0; i != NumElements; ++i)
678 Ops.push_back(getValue(CP->getOperand(i)));
680 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
681 EVT EltVT = TLI.getValueType(VecTy->getElementType());
684 if (EltVT.isFloatingPoint())
685 Op = DAG.getConstantFP(0, EltVT);
687 Op = DAG.getConstant(0, EltVT);
688 Ops.assign(NumElements, Op);
691 // Create a BUILD_VECTOR node.
692 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
693 VT, &Ops[0], Ops.size());
696 // If this is a static alloca, generate it as the frameindex instead of
698 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
699 DenseMap<const AllocaInst*, int>::iterator SI =
700 FuncInfo.StaticAllocaMap.find(AI);
701 if (SI != FuncInfo.StaticAllocaMap.end())
702 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
705 unsigned InReg = FuncInfo.ValueMap[V];
706 assert(InReg && "Value not in map!");
708 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
709 SDValue Chain = DAG.getEntryNode();
710 return RFV.getCopyFromRegs(DAG, getCurDebugLoc(), Chain, NULL);
713 /// Get the EVTs and ArgFlags collections that represent the return type
714 /// of the given function. This does not require a DAG or a return value, and
715 /// is suitable for use before any DAGs for the function are constructed.
716 static void getReturnInfo(const Type* ReturnType,
717 Attributes attr, SmallVectorImpl<EVT> &OutVTs,
718 SmallVectorImpl<ISD::ArgFlagsTy> &OutFlags,
720 SmallVectorImpl<uint64_t> *Offsets = 0) {
721 SmallVector<EVT, 4> ValueVTs;
722 ComputeValueVTs(TLI, ReturnType, ValueVTs, Offsets);
723 unsigned NumValues = ValueVTs.size();
724 if ( NumValues == 0 ) return;
726 for (unsigned j = 0, f = NumValues; j != f; ++j) {
727 EVT VT = ValueVTs[j];
728 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
730 if (attr & Attribute::SExt)
731 ExtendKind = ISD::SIGN_EXTEND;
732 else if (attr & Attribute::ZExt)
733 ExtendKind = ISD::ZERO_EXTEND;
735 // FIXME: C calling convention requires the return type to be promoted to
736 // at least 32-bit. But this is not necessary for non-C calling
737 // conventions. The frontend should mark functions whose return values
738 // require promoting with signext or zeroext attributes.
739 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
740 EVT MinVT = TLI.getRegisterType(ReturnType->getContext(), MVT::i32);
741 if (VT.bitsLT(MinVT))
745 unsigned NumParts = TLI.getNumRegisters(ReturnType->getContext(), VT);
746 EVT PartVT = TLI.getRegisterType(ReturnType->getContext(), VT);
747 // 'inreg' on function refers to return value
748 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
749 if (attr & Attribute::InReg)
752 // Propagate extension type if any
753 if (attr & Attribute::SExt)
755 else if (attr & Attribute::ZExt)
758 for (unsigned i = 0; i < NumParts; ++i) {
759 OutVTs.push_back(PartVT);
760 OutFlags.push_back(Flags);
765 void SelectionDAGBuilder::visitRet(ReturnInst &I) {
766 SDValue Chain = getControlRoot();
767 SmallVector<ISD::OutputArg, 8> Outs;
768 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
770 if (!FLI.CanLowerReturn) {
771 unsigned DemoteReg = FLI.DemoteRegister;
772 const Function *F = I.getParent()->getParent();
774 // Emit a store of the return value through the virtual register.
775 // Leave Outs empty so that LowerReturn won't try to load return
776 // registers the usual way.
777 SmallVector<EVT, 1> PtrValueVTs;
778 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
781 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
782 SDValue RetOp = getValue(I.getOperand(0));
784 SmallVector<EVT, 4> ValueVTs;
785 SmallVector<uint64_t, 4> Offsets;
786 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
787 unsigned NumValues = ValueVTs.size();
789 SmallVector<SDValue, 4> Chains(NumValues);
790 EVT PtrVT = PtrValueVTs[0];
791 for (unsigned i = 0; i != NumValues; ++i)
792 Chains[i] = DAG.getStore(Chain, getCurDebugLoc(),
793 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
794 DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, RetPtr,
795 DAG.getConstant(Offsets[i], PtrVT)),
796 NULL, Offsets[i], false, 0);
797 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
798 MVT::Other, &Chains[0], NumValues);
801 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
802 SmallVector<EVT, 4> ValueVTs;
803 ComputeValueVTs(TLI, I.getOperand(i)->getType(), ValueVTs);
804 unsigned NumValues = ValueVTs.size();
805 if (NumValues == 0) continue;
807 SDValue RetOp = getValue(I.getOperand(i));
808 for (unsigned j = 0, f = NumValues; j != f; ++j) {
809 EVT VT = ValueVTs[j];
811 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
813 const Function *F = I.getParent()->getParent();
814 if (F->paramHasAttr(0, Attribute::SExt))
815 ExtendKind = ISD::SIGN_EXTEND;
816 else if (F->paramHasAttr(0, Attribute::ZExt))
817 ExtendKind = ISD::ZERO_EXTEND;
819 // FIXME: C calling convention requires the return type to be promoted to
820 // at least 32-bit. But this is not necessary for non-C calling
821 // conventions. The frontend should mark functions whose return values
822 // require promoting with signext or zeroext attributes.
823 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger()) {
824 EVT MinVT = TLI.getRegisterType(*DAG.getContext(), MVT::i32);
825 if (VT.bitsLT(MinVT))
829 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
830 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
831 SmallVector<SDValue, 4> Parts(NumParts);
832 getCopyToParts(DAG, getCurDebugLoc(),
833 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
834 &Parts[0], NumParts, PartVT, ExtendKind);
836 // 'inreg' on function refers to return value
837 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
838 if (F->paramHasAttr(0, Attribute::InReg))
841 // Propagate extension type if any
842 if (F->paramHasAttr(0, Attribute::SExt))
844 else if (F->paramHasAttr(0, Attribute::ZExt))
847 for (unsigned i = 0; i < NumParts; ++i)
848 Outs.push_back(ISD::OutputArg(Flags, Parts[i], /*isfixed=*/true));
853 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
854 CallingConv::ID CallConv =
855 DAG.getMachineFunction().getFunction()->getCallingConv();
856 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
857 Outs, getCurDebugLoc(), DAG);
859 // Verify that the target's LowerReturn behaved as expected.
860 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
861 "LowerReturn didn't return a valid chain!");
863 // Update the DAG with the new chain value resulting from return lowering.
867 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
868 /// created for it, emit nodes to copy the value into the virtual
870 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(Value *V) {
871 if (!V->use_empty()) {
872 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
873 if (VMI != FuncInfo.ValueMap.end())
874 CopyValueToVirtualRegister(V, VMI->second);
878 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
879 /// the current basic block, add it to ValueMap now so that we'll get a
881 void SelectionDAGBuilder::ExportFromCurrentBlock(Value *V) {
882 // No need to export constants.
883 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
886 if (FuncInfo.isExportedInst(V)) return;
888 unsigned Reg = FuncInfo.InitializeRegForValue(V);
889 CopyValueToVirtualRegister(V, Reg);
892 bool SelectionDAGBuilder::isExportableFromCurrentBlock(Value *V,
893 const BasicBlock *FromBB) {
894 // The operands of the setcc have to be in this block. We don't know
895 // how to export them from some other block.
896 if (Instruction *VI = dyn_cast<Instruction>(V)) {
897 // Can export from current BB.
898 if (VI->getParent() == FromBB)
901 // Is already exported, noop.
902 return FuncInfo.isExportedInst(V);
905 // If this is an argument, we can export it if the BB is the entry block or
906 // if it is already exported.
907 if (isa<Argument>(V)) {
908 if (FromBB == &FromBB->getParent()->getEntryBlock())
911 // Otherwise, can only export this if it is already exported.
912 return FuncInfo.isExportedInst(V);
915 // Otherwise, constants can always be exported.
919 static bool InBlock(const Value *V, const BasicBlock *BB) {
920 if (const Instruction *I = dyn_cast<Instruction>(V))
921 return I->getParent() == BB;
925 /// getFCmpCondCode - Return the ISD condition code corresponding to
926 /// the given LLVM IR floating-point condition code. This includes
927 /// consideration of global floating-point math flags.
929 static ISD::CondCode getFCmpCondCode(FCmpInst::Predicate Pred) {
930 ISD::CondCode FPC, FOC;
932 case FCmpInst::FCMP_FALSE: FOC = FPC = ISD::SETFALSE; break;
933 case FCmpInst::FCMP_OEQ: FOC = ISD::SETEQ; FPC = ISD::SETOEQ; break;
934 case FCmpInst::FCMP_OGT: FOC = ISD::SETGT; FPC = ISD::SETOGT; break;
935 case FCmpInst::FCMP_OGE: FOC = ISD::SETGE; FPC = ISD::SETOGE; break;
936 case FCmpInst::FCMP_OLT: FOC = ISD::SETLT; FPC = ISD::SETOLT; break;
937 case FCmpInst::FCMP_OLE: FOC = ISD::SETLE; FPC = ISD::SETOLE; break;
938 case FCmpInst::FCMP_ONE: FOC = ISD::SETNE; FPC = ISD::SETONE; break;
939 case FCmpInst::FCMP_ORD: FOC = FPC = ISD::SETO; break;
940 case FCmpInst::FCMP_UNO: FOC = FPC = ISD::SETUO; break;
941 case FCmpInst::FCMP_UEQ: FOC = ISD::SETEQ; FPC = ISD::SETUEQ; break;
942 case FCmpInst::FCMP_UGT: FOC = ISD::SETGT; FPC = ISD::SETUGT; break;
943 case FCmpInst::FCMP_UGE: FOC = ISD::SETGE; FPC = ISD::SETUGE; break;
944 case FCmpInst::FCMP_ULT: FOC = ISD::SETLT; FPC = ISD::SETULT; break;
945 case FCmpInst::FCMP_ULE: FOC = ISD::SETLE; FPC = ISD::SETULE; break;
946 case FCmpInst::FCMP_UNE: FOC = ISD::SETNE; FPC = ISD::SETUNE; break;
947 case FCmpInst::FCMP_TRUE: FOC = FPC = ISD::SETTRUE; break;
949 llvm_unreachable("Invalid FCmp predicate opcode!");
950 FOC = FPC = ISD::SETFALSE;
953 if (FiniteOnlyFPMath())
959 /// getICmpCondCode - Return the ISD condition code corresponding to
960 /// the given LLVM IR integer condition code.
962 static ISD::CondCode getICmpCondCode(ICmpInst::Predicate Pred) {
964 case ICmpInst::ICMP_EQ: return ISD::SETEQ;
965 case ICmpInst::ICMP_NE: return ISD::SETNE;
966 case ICmpInst::ICMP_SLE: return ISD::SETLE;
967 case ICmpInst::ICMP_ULE: return ISD::SETULE;
968 case ICmpInst::ICMP_SGE: return ISD::SETGE;
969 case ICmpInst::ICMP_UGE: return ISD::SETUGE;
970 case ICmpInst::ICMP_SLT: return ISD::SETLT;
971 case ICmpInst::ICMP_ULT: return ISD::SETULT;
972 case ICmpInst::ICMP_SGT: return ISD::SETGT;
973 case ICmpInst::ICMP_UGT: return ISD::SETUGT;
975 llvm_unreachable("Invalid ICmp predicate opcode!");
980 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
981 /// This function emits a branch and is used at the leaves of an OR or an
982 /// AND operator tree.
985 SelectionDAGBuilder::EmitBranchForMergedCondition(Value *Cond,
986 MachineBasicBlock *TBB,
987 MachineBasicBlock *FBB,
988 MachineBasicBlock *CurBB) {
989 const BasicBlock *BB = CurBB->getBasicBlock();
991 // If the leaf of the tree is a comparison, merge the condition into
993 if (CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
994 // The operands of the cmp have to be in this block. We don't know
995 // how to export them from some other block. If this is the first block
996 // of the sequence, no exporting is needed.
997 if (CurBB == CurMBB ||
998 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
999 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1000 ISD::CondCode Condition;
1001 if (ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1002 Condition = getICmpCondCode(IC->getPredicate());
1003 } else if (FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1004 Condition = getFCmpCondCode(FC->getPredicate());
1006 Condition = ISD::SETEQ; // silence warning.
1007 llvm_unreachable("Unknown compare instruction");
1010 CaseBlock CB(Condition, BOp->getOperand(0),
1011 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1012 SwitchCases.push_back(CB);
1017 // Create a CaseBlock record representing this branch.
1018 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1019 NULL, TBB, FBB, CurBB);
1020 SwitchCases.push_back(CB);
1023 /// FindMergedConditions - If Cond is an expression like
1024 void SelectionDAGBuilder::FindMergedConditions(Value *Cond,
1025 MachineBasicBlock *TBB,
1026 MachineBasicBlock *FBB,
1027 MachineBasicBlock *CurBB,
1029 // If this node is not part of the or/and tree, emit it as a branch.
1030 Instruction *BOp = dyn_cast<Instruction>(Cond);
1031 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1032 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1033 BOp->getParent() != CurBB->getBasicBlock() ||
1034 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1035 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1036 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB);
1040 // Create TmpBB after CurBB.
1041 MachineFunction::iterator BBI = CurBB;
1042 MachineFunction &MF = DAG.getMachineFunction();
1043 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1044 CurBB->getParent()->insert(++BBI, TmpBB);
1046 if (Opc == Instruction::Or) {
1047 // Codegen X | Y as:
1055 // Emit the LHS condition.
1056 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, Opc);
1058 // Emit the RHS condition into TmpBB.
1059 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1061 assert(Opc == Instruction::And && "Unknown merge op!");
1062 // Codegen X & Y as:
1069 // This requires creation of TmpBB after CurBB.
1071 // Emit the LHS condition.
1072 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, Opc);
1074 // Emit the RHS condition into TmpBB.
1075 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, Opc);
1079 /// If the set of cases should be emitted as a series of branches, return true.
1080 /// If we should emit this as a bunch of and/or'd together conditions, return
1083 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1084 if (Cases.size() != 2) return true;
1086 // If this is two comparisons of the same values or'd or and'd together, they
1087 // will get folded into a single comparison, so don't emit two blocks.
1088 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1089 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1090 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1091 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1098 void SelectionDAGBuilder::visitBr(BranchInst &I) {
1099 // Update machine-CFG edges.
1100 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1102 // Figure out which block is immediately after the current one.
1103 MachineBasicBlock *NextBlock = 0;
1104 MachineFunction::iterator BBI = CurMBB;
1105 if (++BBI != FuncInfo.MF->end())
1108 if (I.isUnconditional()) {
1109 // Update machine-CFG edges.
1110 CurMBB->addSuccessor(Succ0MBB);
1112 // If this is not a fall-through branch, emit the branch.
1113 if (Succ0MBB != NextBlock) {
1114 SDValue V = DAG.getNode(ISD::BR, getCurDebugLoc(),
1115 MVT::Other, getControlRoot(),
1116 DAG.getBasicBlock(Succ0MBB));
1119 if (DisableScheduling)
1120 DAG.AssignOrdering(V.getNode(), SDNodeOrder);
1126 // If this condition is one of the special cases we handle, do special stuff
1128 Value *CondVal = I.getCondition();
1129 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1131 // If this is a series of conditions that are or'd or and'd together, emit
1132 // this as a sequence of branches instead of setcc's with and/or operations.
1133 // For example, instead of something like:
1146 if (BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1147 if (BOp->hasOneUse() &&
1148 (BOp->getOpcode() == Instruction::And ||
1149 BOp->getOpcode() == Instruction::Or)) {
1150 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, CurMBB, BOp->getOpcode());
1151 // If the compares in later blocks need to use values not currently
1152 // exported from this block, export them now. This block should always
1153 // be the first entry.
1154 assert(SwitchCases[0].ThisBB == CurMBB && "Unexpected lowering!");
1156 // Allow some cases to be rejected.
1157 if (ShouldEmitAsBranches(SwitchCases)) {
1158 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1159 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1160 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1163 // Emit the branch for this block.
1164 visitSwitchCase(SwitchCases[0]);
1165 SwitchCases.erase(SwitchCases.begin());
1169 // Okay, we decided not to do this, remove any inserted MBB's and clear
1171 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1172 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1174 SwitchCases.clear();
1178 // Create a CaseBlock record representing this branch.
1179 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1180 NULL, Succ0MBB, Succ1MBB, CurMBB);
1182 // Use visitSwitchCase to actually insert the fast branch sequence for this
1184 visitSwitchCase(CB);
1187 /// visitSwitchCase - Emits the necessary code to represent a single node in
1188 /// the binary search tree resulting from lowering a switch instruction.
1189 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB) {
1191 SDValue CondLHS = getValue(CB.CmpLHS);
1192 DebugLoc dl = getCurDebugLoc();
1194 // Build the setcc now.
1195 if (CB.CmpMHS == NULL) {
1196 // Fold "(X == true)" to X and "(X == false)" to !X to
1197 // handle common cases produced by branch lowering.
1198 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1199 CB.CC == ISD::SETEQ)
1201 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1202 CB.CC == ISD::SETEQ) {
1203 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1204 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1206 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1208 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1210 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1211 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1213 SDValue CmpOp = getValue(CB.CmpMHS);
1214 EVT VT = CmpOp.getValueType();
1216 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1217 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1220 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1221 VT, CmpOp, DAG.getConstant(Low, VT));
1222 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1223 DAG.getConstant(High-Low, VT), ISD::SETULE);
1227 // Update successor info
1228 CurMBB->addSuccessor(CB.TrueBB);
1229 CurMBB->addSuccessor(CB.FalseBB);
1231 // Set NextBlock to be the MBB immediately after the current one, if any.
1232 // This is used to avoid emitting unnecessary branches to the next block.
1233 MachineBasicBlock *NextBlock = 0;
1234 MachineFunction::iterator BBI = CurMBB;
1235 if (++BBI != FuncInfo.MF->end())
1238 // If the lhs block is the next block, invert the condition so that we can
1239 // fall through to the lhs instead of the rhs block.
1240 if (CB.TrueBB == NextBlock) {
1241 std::swap(CB.TrueBB, CB.FalseBB);
1242 SDValue True = DAG.getConstant(1, Cond.getValueType());
1243 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1246 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1247 MVT::Other, getControlRoot(), Cond,
1248 DAG.getBasicBlock(CB.TrueBB));
1250 // If the branch was constant folded, fix up the CFG.
1251 if (BrCond.getOpcode() == ISD::BR) {
1252 CurMBB->removeSuccessor(CB.FalseBB);
1254 // Otherwise, go ahead and insert the false branch.
1255 if (BrCond == getControlRoot())
1256 CurMBB->removeSuccessor(CB.TrueBB);
1258 if (CB.FalseBB != NextBlock)
1259 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1260 DAG.getBasicBlock(CB.FalseBB));
1263 DAG.setRoot(BrCond);
1265 if (DisableScheduling)
1266 DAG.AssignOrdering(BrCond.getNode(), SDNodeOrder);
1269 /// visitJumpTable - Emit JumpTable node in the current MBB
1270 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1271 // Emit the code for the jump table
1272 assert(JT.Reg != -1U && "Should lower JT Header first!");
1273 EVT PTy = TLI.getPointerTy();
1274 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1276 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1277 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1278 MVT::Other, Index.getValue(1),
1280 DAG.setRoot(BrJumpTable);
1282 if (DisableScheduling)
1283 DAG.AssignOrdering(BrJumpTable.getNode(), SDNodeOrder);
1286 /// visitJumpTableHeader - This function emits necessary code to produce index
1287 /// in the JumpTable from switch case.
1288 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1289 JumpTableHeader &JTH) {
1290 // Subtract the lowest switch case value from the value being switched on and
1291 // conditional branch to default mbb if the result is greater than the
1292 // difference between smallest and largest cases.
1293 SDValue SwitchOp = getValue(JTH.SValue);
1294 EVT VT = SwitchOp.getValueType();
1295 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1296 DAG.getConstant(JTH.First, VT));
1298 // The SDNode we just created, which holds the value being switched on minus
1299 // the the smallest case value, needs to be copied to a virtual register so it
1300 // can be used as an index into the jump table in a subsequent basic block.
1301 // This value may be smaller or larger than the target's pointer type, and
1302 // therefore require extension or truncating.
1303 SwitchOp = DAG.getZExtOrTrunc(SUB, getCurDebugLoc(), TLI.getPointerTy());
1305 unsigned JumpTableReg = FuncInfo.MakeReg(TLI.getPointerTy());
1306 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1307 JumpTableReg, SwitchOp);
1308 JT.Reg = JumpTableReg;
1310 // Emit the range check for the jump table, and branch to the default block
1311 // for the switch statement if the value being switched on exceeds the largest
1312 // case in the switch.
1313 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1314 TLI.getSetCCResultType(SUB.getValueType()), SUB,
1315 DAG.getConstant(JTH.Last-JTH.First,VT),
1318 // Set NextBlock to be the MBB immediately after the current one, if any.
1319 // This is used to avoid emitting unnecessary branches to the next block.
1320 MachineBasicBlock *NextBlock = 0;
1321 MachineFunction::iterator BBI = CurMBB;
1322 if (++BBI != FuncInfo.MF->end())
1325 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1326 MVT::Other, CopyTo, CMP,
1327 DAG.getBasicBlock(JT.Default));
1329 if (JT.MBB != NextBlock)
1330 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1331 DAG.getBasicBlock(JT.MBB));
1333 DAG.setRoot(BrCond);
1335 if (DisableScheduling)
1336 DAG.AssignOrdering(BrCond.getNode(), SDNodeOrder);
1339 /// visitBitTestHeader - This function emits necessary code to produce value
1340 /// suitable for "bit tests"
1341 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B) {
1342 // Subtract the minimum value
1343 SDValue SwitchOp = getValue(B.SValue);
1344 EVT VT = SwitchOp.getValueType();
1345 SDValue SUB = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1346 DAG.getConstant(B.First, VT));
1349 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1350 TLI.getSetCCResultType(SUB.getValueType()),
1351 SUB, DAG.getConstant(B.Range, VT),
1354 SDValue ShiftOp = DAG.getZExtOrTrunc(SUB, getCurDebugLoc(), TLI.getPointerTy());
1356 B.Reg = FuncInfo.MakeReg(TLI.getPointerTy());
1357 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1360 // Set NextBlock to be the MBB immediately after the current one, if any.
1361 // This is used to avoid emitting unnecessary branches to the next block.
1362 MachineBasicBlock *NextBlock = 0;
1363 MachineFunction::iterator BBI = CurMBB;
1364 if (++BBI != FuncInfo.MF->end())
1367 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1369 CurMBB->addSuccessor(B.Default);
1370 CurMBB->addSuccessor(MBB);
1372 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1373 MVT::Other, CopyTo, RangeCmp,
1374 DAG.getBasicBlock(B.Default));
1376 if (MBB != NextBlock)
1377 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1378 DAG.getBasicBlock(MBB));
1380 DAG.setRoot(BrRange);
1382 if (DisableScheduling)
1383 DAG.AssignOrdering(BrRange.getNode(), SDNodeOrder);
1386 /// visitBitTestCase - this function produces one "bit test"
1387 void SelectionDAGBuilder::visitBitTestCase(MachineBasicBlock* NextMBB,
1390 // Make desired shift
1391 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(), Reg,
1392 TLI.getPointerTy());
1393 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(),
1395 DAG.getConstant(1, TLI.getPointerTy()),
1398 // Emit bit tests and jumps
1399 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
1400 TLI.getPointerTy(), SwitchVal,
1401 DAG.getConstant(B.Mask, TLI.getPointerTy()));
1402 SDValue AndCmp = DAG.getSetCC(getCurDebugLoc(),
1403 TLI.getSetCCResultType(AndOp.getValueType()),
1404 AndOp, DAG.getConstant(0, TLI.getPointerTy()),
1407 CurMBB->addSuccessor(B.TargetBB);
1408 CurMBB->addSuccessor(NextMBB);
1410 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1411 MVT::Other, getControlRoot(),
1412 AndCmp, DAG.getBasicBlock(B.TargetBB));
1414 // Set NextBlock to be the MBB immediately after the current one, if any.
1415 // This is used to avoid emitting unnecessary branches to the next block.
1416 MachineBasicBlock *NextBlock = 0;
1417 MachineFunction::iterator BBI = CurMBB;
1418 if (++BBI != FuncInfo.MF->end())
1421 if (NextMBB != NextBlock)
1422 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1423 DAG.getBasicBlock(NextMBB));
1427 if (DisableScheduling)
1428 DAG.AssignOrdering(BrAnd.getNode(), SDNodeOrder);
1431 void SelectionDAGBuilder::visitInvoke(InvokeInst &I) {
1432 // Retrieve successors.
1433 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1434 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1436 const Value *Callee(I.getCalledValue());
1437 if (isa<InlineAsm>(Callee))
1440 LowerCallTo(&I, getValue(Callee), false, LandingPad);
1442 // If the value of the invoke is used outside of its defining block, make it
1443 // available as a virtual register.
1444 CopyToExportRegsIfNeeded(&I);
1446 // Update successor info
1447 CurMBB->addSuccessor(Return);
1448 CurMBB->addSuccessor(LandingPad);
1450 // Drop into normal successor.
1451 SDValue Branch = DAG.getNode(ISD::BR, getCurDebugLoc(),
1452 MVT::Other, getControlRoot(),
1453 DAG.getBasicBlock(Return));
1454 DAG.setRoot(Branch);
1456 if (DisableScheduling)
1457 DAG.AssignOrdering(Branch.getNode(), SDNodeOrder);
1460 void SelectionDAGBuilder::visitUnwind(UnwindInst &I) {
1463 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1464 /// small case ranges).
1465 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
1466 CaseRecVector& WorkList,
1468 MachineBasicBlock* Default) {
1469 Case& BackCase = *(CR.Range.second-1);
1471 // Size is the number of Cases represented by this range.
1472 size_t Size = CR.Range.second - CR.Range.first;
1476 // Get the MachineFunction which holds the current MBB. This is used when
1477 // inserting any additional MBBs necessary to represent the switch.
1478 MachineFunction *CurMF = FuncInfo.MF;
1480 // Figure out which block is immediately after the current one.
1481 MachineBasicBlock *NextBlock = 0;
1482 MachineFunction::iterator BBI = CR.CaseBB;
1484 if (++BBI != FuncInfo.MF->end())
1487 // TODO: If any two of the cases has the same destination, and if one value
1488 // is the same as the other, but has one bit unset that the other has set,
1489 // use bit manipulation to do two compares at once. For example:
1490 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1492 // Rearrange the case blocks so that the last one falls through if possible.
1493 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1494 // The last case block won't fall through into 'NextBlock' if we emit the
1495 // branches in this order. See if rearranging a case value would help.
1496 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1497 if (I->BB == NextBlock) {
1498 std::swap(*I, BackCase);
1504 // Create a CaseBlock record representing a conditional branch to
1505 // the Case's target mbb if the value being switched on SV is equal
1507 MachineBasicBlock *CurBlock = CR.CaseBB;
1508 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1509 MachineBasicBlock *FallThrough;
1511 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1512 CurMF->insert(BBI, FallThrough);
1514 // Put SV in a virtual register to make it available from the new blocks.
1515 ExportFromCurrentBlock(SV);
1517 // If the last case doesn't match, go to the default block.
1518 FallThrough = Default;
1521 Value *RHS, *LHS, *MHS;
1523 if (I->High == I->Low) {
1524 // This is just small small case range :) containing exactly 1 case
1526 LHS = SV; RHS = I->High; MHS = NULL;
1529 LHS = I->Low; MHS = SV; RHS = I->High;
1531 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1533 // If emitting the first comparison, just call visitSwitchCase to emit the
1534 // code into the current block. Otherwise, push the CaseBlock onto the
1535 // vector to be later processed by SDISel, and insert the node's MBB
1536 // before the next MBB.
1537 if (CurBlock == CurMBB)
1538 visitSwitchCase(CB);
1540 SwitchCases.push_back(CB);
1542 CurBlock = FallThrough;
1548 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1549 return !DisableJumpTables &&
1550 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1551 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1554 static APInt ComputeRange(const APInt &First, const APInt &Last) {
1555 APInt LastExt(Last), FirstExt(First);
1556 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1557 LastExt.sext(BitWidth); FirstExt.sext(BitWidth);
1558 return (LastExt - FirstExt + 1ULL);
1561 /// handleJTSwitchCase - Emit jumptable for current switch case range
1562 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR,
1563 CaseRecVector& WorkList,
1565 MachineBasicBlock* Default) {
1566 Case& FrontCase = *CR.Range.first;
1567 Case& BackCase = *(CR.Range.second-1);
1569 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1570 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1572 APInt TSize(First.getBitWidth(), 0);
1573 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1577 if (!areJTsAllowed(TLI) || TSize.ult(APInt(First.getBitWidth(), 4)))
1580 APInt Range = ComputeRange(First, Last);
1581 double Density = TSize.roundToDouble() / Range.roundToDouble();
1585 DEBUG(errs() << "Lowering jump table\n"
1586 << "First entry: " << First << ". Last entry: " << Last << '\n'
1587 << "Range: " << Range
1588 << "Size: " << TSize << ". Density: " << Density << "\n\n");
1590 // Get the MachineFunction which holds the current MBB. This is used when
1591 // inserting any additional MBBs necessary to represent the switch.
1592 MachineFunction *CurMF = FuncInfo.MF;
1594 // Figure out which block is immediately after the current one.
1595 MachineFunction::iterator BBI = CR.CaseBB;
1598 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1600 // Create a new basic block to hold the code for loading the address
1601 // of the jump table, and jumping to it. Update successor information;
1602 // we will either branch to the default case for the switch, or the jump
1604 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1605 CurMF->insert(BBI, JumpTableBB);
1606 CR.CaseBB->addSuccessor(Default);
1607 CR.CaseBB->addSuccessor(JumpTableBB);
1609 // Build a vector of destination BBs, corresponding to each target
1610 // of the jump table. If the value of the jump table slot corresponds to
1611 // a case statement, push the case's BB onto the vector, otherwise, push
1613 std::vector<MachineBasicBlock*> DestBBs;
1615 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1616 const APInt& Low = cast<ConstantInt>(I->Low)->getValue();
1617 const APInt& High = cast<ConstantInt>(I->High)->getValue();
1619 if (Low.sle(TEI) && TEI.sle(High)) {
1620 DestBBs.push_back(I->BB);
1624 DestBBs.push_back(Default);
1628 // Update successor info. Add one edge to each unique successor.
1629 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
1630 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
1631 E = DestBBs.end(); I != E; ++I) {
1632 if (!SuccsHandled[(*I)->getNumber()]) {
1633 SuccsHandled[(*I)->getNumber()] = true;
1634 JumpTableBB->addSuccessor(*I);
1638 // Create a jump table index for this jump table, or return an existing
1640 unsigned JTI = CurMF->getJumpTableInfo()->getJumpTableIndex(DestBBs);
1642 // Set the jump table information so that we can codegen it as a second
1643 // MachineBasicBlock
1644 JumpTable JT(-1U, JTI, JumpTableBB, Default);
1645 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == CurMBB));
1646 if (CR.CaseBB == CurMBB)
1647 visitJumpTableHeader(JT, JTH);
1649 JTCases.push_back(JumpTableBlock(JTH, JT));
1654 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
1656 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
1657 CaseRecVector& WorkList,
1659 MachineBasicBlock* Default) {
1660 // Get the MachineFunction which holds the current MBB. This is used when
1661 // inserting any additional MBBs necessary to represent the switch.
1662 MachineFunction *CurMF = FuncInfo.MF;
1664 // Figure out which block is immediately after the current one.
1665 MachineFunction::iterator BBI = CR.CaseBB;
1668 Case& FrontCase = *CR.Range.first;
1669 Case& BackCase = *(CR.Range.second-1);
1670 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1672 // Size is the number of Cases represented by this range.
1673 unsigned Size = CR.Range.second - CR.Range.first;
1675 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1676 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1678 CaseItr Pivot = CR.Range.first + Size/2;
1680 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
1681 // (heuristically) allow us to emit JumpTable's later.
1682 APInt TSize(First.getBitWidth(), 0);
1683 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1687 APInt LSize = FrontCase.size();
1688 APInt RSize = TSize-LSize;
1689 DEBUG(errs() << "Selecting best pivot: \n"
1690 << "First: " << First << ", Last: " << Last <<'\n'
1691 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
1692 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
1694 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
1695 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
1696 APInt Range = ComputeRange(LEnd, RBegin);
1697 assert((Range - 2ULL).isNonNegative() &&
1698 "Invalid case distance");
1699 double LDensity = (double)LSize.roundToDouble() /
1700 (LEnd - First + 1ULL).roundToDouble();
1701 double RDensity = (double)RSize.roundToDouble() /
1702 (Last - RBegin + 1ULL).roundToDouble();
1703 double Metric = Range.logBase2()*(LDensity+RDensity);
1704 // Should always split in some non-trivial place
1705 DEBUG(errs() <<"=>Step\n"
1706 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
1707 << "LDensity: " << LDensity
1708 << ", RDensity: " << RDensity << '\n'
1709 << "Metric: " << Metric << '\n');
1710 if (FMetric < Metric) {
1713 DEBUG(errs() << "Current metric set to: " << FMetric << '\n');
1719 if (areJTsAllowed(TLI)) {
1720 // If our case is dense we *really* should handle it earlier!
1721 assert((FMetric > 0) && "Should handle dense range earlier!");
1723 Pivot = CR.Range.first + Size/2;
1726 CaseRange LHSR(CR.Range.first, Pivot);
1727 CaseRange RHSR(Pivot, CR.Range.second);
1728 Constant *C = Pivot->Low;
1729 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
1731 // We know that we branch to the LHS if the Value being switched on is
1732 // less than the Pivot value, C. We use this to optimize our binary
1733 // tree a bit, by recognizing that if SV is greater than or equal to the
1734 // LHS's Case Value, and that Case Value is exactly one less than the
1735 // Pivot's Value, then we can branch directly to the LHS's Target,
1736 // rather than creating a leaf node for it.
1737 if ((LHSR.second - LHSR.first) == 1 &&
1738 LHSR.first->High == CR.GE &&
1739 cast<ConstantInt>(C)->getValue() ==
1740 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
1741 TrueBB = LHSR.first->BB;
1743 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1744 CurMF->insert(BBI, TrueBB);
1745 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
1747 // Put SV in a virtual register to make it available from the new blocks.
1748 ExportFromCurrentBlock(SV);
1751 // Similar to the optimization above, if the Value being switched on is
1752 // known to be less than the Constant CR.LT, and the current Case Value
1753 // is CR.LT - 1, then we can branch directly to the target block for
1754 // the current Case Value, rather than emitting a RHS leaf node for it.
1755 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
1756 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
1757 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
1758 FalseBB = RHSR.first->BB;
1760 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1761 CurMF->insert(BBI, FalseBB);
1762 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
1764 // Put SV in a virtual register to make it available from the new blocks.
1765 ExportFromCurrentBlock(SV);
1768 // Create a CaseBlock record representing a conditional branch to
1769 // the LHS node if the value being switched on SV is less than C.
1770 // Otherwise, branch to LHS.
1771 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
1773 if (CR.CaseBB == CurMBB)
1774 visitSwitchCase(CB);
1776 SwitchCases.push_back(CB);
1781 /// handleBitTestsSwitchCase - if current case range has few destination and
1782 /// range span less, than machine word bitwidth, encode case range into series
1783 /// of masks and emit bit tests with these masks.
1784 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
1785 CaseRecVector& WorkList,
1787 MachineBasicBlock* Default){
1788 EVT PTy = TLI.getPointerTy();
1789 unsigned IntPtrBits = PTy.getSizeInBits();
1791 Case& FrontCase = *CR.Range.first;
1792 Case& BackCase = *(CR.Range.second-1);
1794 // Get the MachineFunction which holds the current MBB. This is used when
1795 // inserting any additional MBBs necessary to represent the switch.
1796 MachineFunction *CurMF = FuncInfo.MF;
1798 // If target does not have legal shift left, do not emit bit tests at all.
1799 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
1803 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1805 // Single case counts one, case range - two.
1806 numCmps += (I->Low == I->High ? 1 : 2);
1809 // Count unique destinations
1810 SmallSet<MachineBasicBlock*, 4> Dests;
1811 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1812 Dests.insert(I->BB);
1813 if (Dests.size() > 3)
1814 // Don't bother the code below, if there are too much unique destinations
1817 DEBUG(errs() << "Total number of unique destinations: " << Dests.size() << '\n'
1818 << "Total number of comparisons: " << numCmps << '\n');
1820 // Compute span of values.
1821 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
1822 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
1823 APInt cmpRange = maxValue - minValue;
1825 DEBUG(errs() << "Compare range: " << cmpRange << '\n'
1826 << "Low bound: " << minValue << '\n'
1827 << "High bound: " << maxValue << '\n');
1829 if (cmpRange.uge(APInt(cmpRange.getBitWidth(), IntPtrBits)) ||
1830 (!(Dests.size() == 1 && numCmps >= 3) &&
1831 !(Dests.size() == 2 && numCmps >= 5) &&
1832 !(Dests.size() >= 3 && numCmps >= 6)))
1835 DEBUG(errs() << "Emitting bit tests\n");
1836 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
1838 // Optimize the case where all the case values fit in a
1839 // word without having to subtract minValue. In this case,
1840 // we can optimize away the subtraction.
1841 if (minValue.isNonNegative() &&
1842 maxValue.slt(APInt(maxValue.getBitWidth(), IntPtrBits))) {
1843 cmpRange = maxValue;
1845 lowBound = minValue;
1848 CaseBitsVector CasesBits;
1849 unsigned i, count = 0;
1851 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
1852 MachineBasicBlock* Dest = I->BB;
1853 for (i = 0; i < count; ++i)
1854 if (Dest == CasesBits[i].BB)
1858 assert((count < 3) && "Too much destinations to test!");
1859 CasesBits.push_back(CaseBits(0, Dest, 0));
1863 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
1864 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
1866 uint64_t lo = (lowValue - lowBound).getZExtValue();
1867 uint64_t hi = (highValue - lowBound).getZExtValue();
1869 for (uint64_t j = lo; j <= hi; j++) {
1870 CasesBits[i].Mask |= 1ULL << j;
1871 CasesBits[i].Bits++;
1875 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
1879 // Figure out which block is immediately after the current one.
1880 MachineFunction::iterator BBI = CR.CaseBB;
1883 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1885 DEBUG(errs() << "Cases:\n");
1886 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
1887 DEBUG(errs() << "Mask: " << CasesBits[i].Mask
1888 << ", Bits: " << CasesBits[i].Bits
1889 << ", BB: " << CasesBits[i].BB << '\n');
1891 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1892 CurMF->insert(BBI, CaseBB);
1893 BTC.push_back(BitTestCase(CasesBits[i].Mask,
1897 // Put SV in a virtual register to make it available from the new blocks.
1898 ExportFromCurrentBlock(SV);
1901 BitTestBlock BTB(lowBound, cmpRange, SV,
1902 -1U, (CR.CaseBB == CurMBB),
1903 CR.CaseBB, Default, BTC);
1905 if (CR.CaseBB == CurMBB)
1906 visitBitTestHeader(BTB);
1908 BitTestCases.push_back(BTB);
1914 /// Clusterify - Transform simple list of Cases into list of CaseRange's
1915 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
1916 const SwitchInst& SI) {
1919 // Start with "simple" cases
1920 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
1921 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
1922 Cases.push_back(Case(SI.getSuccessorValue(i),
1923 SI.getSuccessorValue(i),
1926 std::sort(Cases.begin(), Cases.end(), CaseCmp());
1928 // Merge case into clusters
1929 if (Cases.size() >= 2)
1930 // Must recompute end() each iteration because it may be
1931 // invalidated by erase if we hold on to it
1932 for (CaseItr I = Cases.begin(), J = ++(Cases.begin()); J != Cases.end(); ) {
1933 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
1934 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
1935 MachineBasicBlock* nextBB = J->BB;
1936 MachineBasicBlock* currentBB = I->BB;
1938 // If the two neighboring cases go to the same destination, merge them
1939 // into a single case.
1940 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
1948 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
1949 if (I->Low != I->High)
1950 // A range counts double, since it requires two compares.
1957 void SelectionDAGBuilder::visitSwitch(SwitchInst &SI) {
1958 // Figure out which block is immediately after the current one.
1959 MachineBasicBlock *NextBlock = 0;
1961 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
1963 // If there is only the default destination, branch to it if it is not the
1964 // next basic block. Otherwise, just fall through.
1965 if (SI.getNumOperands() == 2) {
1966 // Update machine-CFG edges.
1968 // If this is not a fall-through branch, emit the branch.
1969 CurMBB->addSuccessor(Default);
1970 if (Default != NextBlock) {
1971 SDValue Val = DAG.getNode(ISD::BR, getCurDebugLoc(),
1972 MVT::Other, getControlRoot(),
1973 DAG.getBasicBlock(Default));
1976 if (DisableScheduling)
1977 DAG.AssignOrdering(Val.getNode(), SDNodeOrder);
1983 // If there are any non-default case statements, create a vector of Cases
1984 // representing each one, and sort the vector so that we can efficiently
1985 // create a binary search tree from them.
1987 size_t numCmps = Clusterify(Cases, SI);
1988 DEBUG(errs() << "Clusterify finished. Total clusters: " << Cases.size()
1989 << ". Total compares: " << numCmps << '\n');
1992 // Get the Value to be switched on and default basic blocks, which will be
1993 // inserted into CaseBlock records, representing basic blocks in the binary
1995 Value *SV = SI.getOperand(0);
1997 // Push the initial CaseRec onto the worklist
1998 CaseRecVector WorkList;
1999 WorkList.push_back(CaseRec(CurMBB,0,0,CaseRange(Cases.begin(),Cases.end())));
2001 while (!WorkList.empty()) {
2002 // Grab a record representing a case range to process off the worklist
2003 CaseRec CR = WorkList.back();
2004 WorkList.pop_back();
2006 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default))
2009 // If the range has few cases (two or less) emit a series of specific
2011 if (handleSmallSwitchRange(CR, WorkList, SV, Default))
2014 // If the switch has more than 5 blocks, and at least 40% dense, and the
2015 // target supports indirect branches, then emit a jump table rather than
2016 // lowering the switch to a binary tree of conditional branches.
2017 if (handleJTSwitchCase(CR, WorkList, SV, Default))
2020 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2021 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2022 handleBTSplitSwitchCase(CR, WorkList, SV, Default);
2026 void SelectionDAGBuilder::visitIndirectBr(IndirectBrInst &I) {
2027 // Update machine-CFG edges.
2028 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
2029 CurMBB->addSuccessor(FuncInfo.MBBMap[I.getSuccessor(i)]);
2031 SDValue Res = DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2032 MVT::Other, getControlRoot(),
2033 getValue(I.getAddress()));
2036 if (DisableScheduling)
2037 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2040 void SelectionDAGBuilder::visitFSub(User &I) {
2041 // -0.0 - X --> fneg
2042 const Type *Ty = I.getType();
2043 if (isa<VectorType>(Ty)) {
2044 if (ConstantVector *CV = dyn_cast<ConstantVector>(I.getOperand(0))) {
2045 const VectorType *DestTy = cast<VectorType>(I.getType());
2046 const Type *ElTy = DestTy->getElementType();
2047 unsigned VL = DestTy->getNumElements();
2048 std::vector<Constant*> NZ(VL, ConstantFP::getNegativeZero(ElTy));
2049 Constant *CNZ = ConstantVector::get(&NZ[0], NZ.size());
2051 SDValue Op2 = getValue(I.getOperand(1));
2052 SDValue Res = DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2053 Op2.getValueType(), Op2);
2056 if (DisableScheduling)
2057 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2064 if (ConstantFP *CFP = dyn_cast<ConstantFP>(I.getOperand(0)))
2065 if (CFP->isExactlyValue(ConstantFP::getNegativeZero(Ty)->getValueAPF())) {
2066 SDValue Op2 = getValue(I.getOperand(1));
2067 SDValue Res = DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2068 Op2.getValueType(), Op2);
2071 if (DisableScheduling)
2072 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2077 visitBinary(I, ISD::FSUB);
2080 void SelectionDAGBuilder::visitBinary(User &I, unsigned OpCode) {
2081 SDValue Op1 = getValue(I.getOperand(0));
2082 SDValue Op2 = getValue(I.getOperand(1));
2083 SDValue Res = DAG.getNode(OpCode, getCurDebugLoc(),
2084 Op1.getValueType(), Op1, Op2);
2087 if (DisableScheduling)
2088 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2091 void SelectionDAGBuilder::visitShift(User &I, unsigned Opcode) {
2092 SDValue Op1 = getValue(I.getOperand(0));
2093 SDValue Op2 = getValue(I.getOperand(1));
2094 if (!isa<VectorType>(I.getType()) &&
2095 Op2.getValueType() != TLI.getShiftAmountTy()) {
2096 // If the operand is smaller than the shift count type, promote it.
2097 EVT PTy = TLI.getPointerTy();
2098 EVT STy = TLI.getShiftAmountTy();
2099 if (STy.bitsGT(Op2.getValueType()))
2100 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2101 TLI.getShiftAmountTy(), Op2);
2102 // If the operand is larger than the shift count type but the shift
2103 // count type has enough bits to represent any shift value, truncate
2104 // it now. This is a common case and it exposes the truncate to
2105 // optimization early.
2106 else if (STy.getSizeInBits() >=
2107 Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2108 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2109 TLI.getShiftAmountTy(), Op2);
2110 // Otherwise we'll need to temporarily settle for some other
2111 // convenient type; type legalization will make adjustments as
2113 else if (PTy.bitsLT(Op2.getValueType()))
2114 Op2 = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2115 TLI.getPointerTy(), Op2);
2116 else if (PTy.bitsGT(Op2.getValueType()))
2117 Op2 = DAG.getNode(ISD::ANY_EXTEND, getCurDebugLoc(),
2118 TLI.getPointerTy(), Op2);
2121 SDValue Res = DAG.getNode(Opcode, getCurDebugLoc(),
2122 Op1.getValueType(), Op1, Op2);
2125 if (DisableScheduling)
2126 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2129 void SelectionDAGBuilder::visitICmp(User &I) {
2130 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2131 if (ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2132 predicate = IC->getPredicate();
2133 else if (ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2134 predicate = ICmpInst::Predicate(IC->getPredicate());
2135 SDValue Op1 = getValue(I.getOperand(0));
2136 SDValue Op2 = getValue(I.getOperand(1));
2137 ISD::CondCode Opcode = getICmpCondCode(predicate);
2139 EVT DestVT = TLI.getValueType(I.getType());
2140 SDValue Res = DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode);
2143 if (DisableScheduling)
2144 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2147 void SelectionDAGBuilder::visitFCmp(User &I) {
2148 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2149 if (FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2150 predicate = FC->getPredicate();
2151 else if (ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2152 predicate = FCmpInst::Predicate(FC->getPredicate());
2153 SDValue Op1 = getValue(I.getOperand(0));
2154 SDValue Op2 = getValue(I.getOperand(1));
2155 ISD::CondCode Condition = getFCmpCondCode(predicate);
2156 EVT DestVT = TLI.getValueType(I.getType());
2157 SDValue Res = DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition);
2160 if (DisableScheduling)
2161 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2164 void SelectionDAGBuilder::visitSelect(User &I) {
2165 SmallVector<EVT, 4> ValueVTs;
2166 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2167 unsigned NumValues = ValueVTs.size();
2168 if (NumValues == 0) return;
2170 SmallVector<SDValue, 4> Values(NumValues);
2171 SDValue Cond = getValue(I.getOperand(0));
2172 SDValue TrueVal = getValue(I.getOperand(1));
2173 SDValue FalseVal = getValue(I.getOperand(2));
2175 for (unsigned i = 0; i != NumValues; ++i) {
2176 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2177 TrueVal.getNode()->getValueType(i), Cond,
2178 SDValue(TrueVal.getNode(),
2179 TrueVal.getResNo() + i),
2180 SDValue(FalseVal.getNode(),
2181 FalseVal.getResNo() + i));
2183 if (DisableScheduling)
2184 DAG.AssignOrdering(Values[i].getNode(), SDNodeOrder);
2187 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2188 DAG.getVTList(&ValueVTs[0], NumValues),
2189 &Values[0], NumValues);
2192 if (DisableScheduling)
2193 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2196 void SelectionDAGBuilder::visitTrunc(User &I) {
2197 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2198 SDValue N = getValue(I.getOperand(0));
2199 EVT DestVT = TLI.getValueType(I.getType());
2200 SDValue Res = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N);
2203 if (DisableScheduling)
2204 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2207 void SelectionDAGBuilder::visitZExt(User &I) {
2208 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2209 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2210 SDValue N = getValue(I.getOperand(0));
2211 EVT DestVT = TLI.getValueType(I.getType());
2212 SDValue Res = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N);
2215 if (DisableScheduling)
2216 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2219 void SelectionDAGBuilder::visitSExt(User &I) {
2220 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2221 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2222 SDValue N = getValue(I.getOperand(0));
2223 EVT DestVT = TLI.getValueType(I.getType());
2224 SDValue Res = DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N);
2227 if (DisableScheduling)
2228 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2231 void SelectionDAGBuilder::visitFPTrunc(User &I) {
2232 // FPTrunc is never a no-op cast, no need to check
2233 SDValue N = getValue(I.getOperand(0));
2234 EVT DestVT = TLI.getValueType(I.getType());
2235 SDValue Res = DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2236 DestVT, N, DAG.getIntPtrConstant(0));
2239 if (DisableScheduling)
2240 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2243 void SelectionDAGBuilder::visitFPExt(User &I){
2244 // FPTrunc is never a no-op cast, no need to check
2245 SDValue N = getValue(I.getOperand(0));
2246 EVT DestVT = TLI.getValueType(I.getType());
2247 SDValue Res = DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N);
2250 if (DisableScheduling)
2251 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2254 void SelectionDAGBuilder::visitFPToUI(User &I) {
2255 // FPToUI is never a no-op cast, no need to check
2256 SDValue N = getValue(I.getOperand(0));
2257 EVT DestVT = TLI.getValueType(I.getType());
2258 SDValue Res = DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N);
2261 if (DisableScheduling)
2262 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2265 void SelectionDAGBuilder::visitFPToSI(User &I) {
2266 // FPToSI is never a no-op cast, no need to check
2267 SDValue N = getValue(I.getOperand(0));
2268 EVT DestVT = TLI.getValueType(I.getType());
2269 SDValue Res = DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N);
2272 if (DisableScheduling)
2273 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2276 void SelectionDAGBuilder::visitUIToFP(User &I) {
2277 // UIToFP is never a no-op cast, no need to check
2278 SDValue N = getValue(I.getOperand(0));
2279 EVT DestVT = TLI.getValueType(I.getType());
2280 SDValue Res = DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N);
2283 if (DisableScheduling)
2284 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2287 void SelectionDAGBuilder::visitSIToFP(User &I){
2288 // SIToFP is never a no-op cast, no need to check
2289 SDValue N = getValue(I.getOperand(0));
2290 EVT DestVT = TLI.getValueType(I.getType());
2291 SDValue Res = DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N);
2294 if (DisableScheduling)
2295 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2298 void SelectionDAGBuilder::visitPtrToInt(User &I) {
2299 // What to do depends on the size of the integer and the size of the pointer.
2300 // We can either truncate, zero extend, or no-op, accordingly.
2301 SDValue N = getValue(I.getOperand(0));
2302 EVT SrcVT = N.getValueType();
2303 EVT DestVT = TLI.getValueType(I.getType());
2304 SDValue Res = DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT);
2307 if (DisableScheduling)
2308 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2311 void SelectionDAGBuilder::visitIntToPtr(User &I) {
2312 // What to do depends on the size of the integer and the size of the pointer.
2313 // We can either truncate, zero extend, or no-op, accordingly.
2314 SDValue N = getValue(I.getOperand(0));
2315 EVT SrcVT = N.getValueType();
2316 EVT DestVT = TLI.getValueType(I.getType());
2317 SDValue Res = DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT);
2320 if (DisableScheduling)
2321 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2324 void SelectionDAGBuilder::visitBitCast(User &I) {
2325 SDValue N = getValue(I.getOperand(0));
2326 EVT DestVT = TLI.getValueType(I.getType());
2328 // BitCast assures us that source and destination are the same size so this is
2329 // either a BIT_CONVERT or a no-op.
2330 if (DestVT != N.getValueType()) {
2331 SDValue Res = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
2332 DestVT, N); // convert types.
2335 if (DisableScheduling)
2336 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2338 setValue(&I, N); // noop cast.
2342 void SelectionDAGBuilder::visitInsertElement(User &I) {
2343 SDValue InVec = getValue(I.getOperand(0));
2344 SDValue InVal = getValue(I.getOperand(1));
2345 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2347 getValue(I.getOperand(2)));
2348 SDValue Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2349 TLI.getValueType(I.getType()),
2350 InVec, InVal, InIdx);
2353 if (DisableScheduling)
2354 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2357 void SelectionDAGBuilder::visitExtractElement(User &I) {
2358 SDValue InVec = getValue(I.getOperand(0));
2359 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2361 getValue(I.getOperand(1)));
2362 SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2363 TLI.getValueType(I.getType()), InVec, InIdx);
2366 if (DisableScheduling)
2367 DAG.AssignOrdering(Res.getNode(), SDNodeOrder);
2371 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2372 // from SIndx and increasing to the element length (undefs are allowed).
2373 static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2374 unsigned MaskNumElts = Mask.size();
2375 for (unsigned i = 0; i != MaskNumElts; ++i)
2376 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
2381 void SelectionDAGBuilder::visitShuffleVector(User &I) {
2382 SmallVector<int, 8> Mask;
2383 SDValue Src1 = getValue(I.getOperand(0));
2384 SDValue Src2 = getValue(I.getOperand(1));
2386 // Convert the ConstantVector mask operand into an array of ints, with -1
2387 // representing undef values.
2388 SmallVector<Constant*, 8> MaskElts;
2389 cast<Constant>(I.getOperand(2))->getVectorElements(*DAG.getContext(),
2391 unsigned MaskNumElts = MaskElts.size();
2392 for (unsigned i = 0; i != MaskNumElts; ++i) {
2393 if (isa<UndefValue>(MaskElts[i]))
2396 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2399 EVT VT = TLI.getValueType(I.getType());
2400 EVT SrcVT = Src1.getValueType();
2401 unsigned SrcNumElts = SrcVT.getVectorNumElements();
2403 if (SrcNumElts == MaskNumElts) {
2404 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2409 // Normalize the shuffle vector since mask and vector length don't match.
2410 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2411 // Mask is longer than the source vectors and is a multiple of the source
2412 // vectors. We can use concatenate vector to make the mask and vectors
2414 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2415 // The shuffle is concatenating two vectors together.
2416 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2421 // Pad both vectors with undefs to make them the same length as the mask.
2422 unsigned NumConcat = MaskNumElts / SrcNumElts;
2423 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2424 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
2425 SDValue UndefVal = DAG.getUNDEF(SrcVT);
2427 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2428 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2432 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2433 getCurDebugLoc(), VT,
2434 &MOps1[0], NumConcat);
2435 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2436 getCurDebugLoc(), VT,
2437 &MOps2[0], NumConcat);
2439 // Readjust mask for new input vector length.
2440 SmallVector<int, 8> MappedOps;
2441 for (unsigned i = 0; i != MaskNumElts; ++i) {
2443 if (Idx < (int)SrcNumElts)
2444 MappedOps.push_back(Idx);
2446 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
2448 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2453 if (SrcNumElts > MaskNumElts) {
2454 // Analyze the access pattern of the vector to see if we can extract
2455 // two subvectors and do the shuffle. The analysis is done by calculating
2456 // the range of elements the mask access on both vectors.
2457 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2458 int MaxRange[2] = {-1, -1};
2460 for (unsigned i = 0; i != MaskNumElts; ++i) {
2466 if (Idx >= (int)SrcNumElts) {
2470 if (Idx > MaxRange[Input])
2471 MaxRange[Input] = Idx;
2472 if (Idx < MinRange[Input])
2473 MinRange[Input] = Idx;
2476 // Check if the access is smaller than the vector size and can we find
2477 // a reasonable extract index.
2478 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not Extract.
2479 int StartIdx[2]; // StartIdx to extract from
2480 for (int Input=0; Input < 2; ++Input) {
2481 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
2482 RangeUse[Input] = 0; // Unused
2483 StartIdx[Input] = 0;
2484 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
2485 // Fits within range but we should see if we can find a good
2486 // start index that is a multiple of the mask length.
2487 if (MaxRange[Input] < (int)MaskNumElts) {
2488 RangeUse[Input] = 1; // Extract from beginning of the vector
2489 StartIdx[Input] = 0;
2491 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2492 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2493 StartIdx[Input] + MaskNumElts < SrcNumElts)
2494 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2499 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
2500 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
2503 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2504 // Extract appropriate subvector and generate a vector shuffle
2505 for (int Input=0; Input < 2; ++Input) {
2506 SDValue& Src = Input == 0 ? Src1 : Src2;
2507 if (RangeUse[Input] == 0) {
2508 Src = DAG.getUNDEF(VT);
2510 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
2511 Src, DAG.getIntPtrConstant(StartIdx[Input]));
2514 // Calculate new mask.
2515 SmallVector<int, 8> MappedOps;
2516 for (unsigned i = 0; i != MaskNumElts; ++i) {
2519 MappedOps.push_back(Idx);
2520 else if (Idx < (int)SrcNumElts)
2521 MappedOps.push_back(Idx - StartIdx[0]);
2523 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
2525 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2531 // We can't use either concat vectors or extract subvectors so fall back to
2532 // replacing the shuffle with extract and build vector.
2533 // to insert and build vector.
2534 EVT EltVT = VT.getVectorElementType();
2535 EVT PtrVT = TLI.getPointerTy();
2536 SmallVector<SDValue,8> Ops;
2537 for (unsigned i = 0; i != MaskNumElts; ++i) {
2539 Ops.push_back(DAG.getUNDEF(EltVT));
2542 if (Idx < (int)SrcNumElts)
2543 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2544 EltVT, Src1, DAG.getConstant(Idx, PtrVT)));
2546 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2548 DAG.getConstant(Idx - SrcNumElts, PtrVT)));
2551 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2552 VT, &Ops[0], Ops.size()));
2555 void SelectionDAGBuilder::visitInsertValue(InsertValueInst &I) {
2556 const Value *Op0 = I.getOperand(0);
2557 const Value *Op1 = I.getOperand(1);
2558 const Type *AggTy = I.getType();
2559 const Type *ValTy = Op1->getType();
2560 bool IntoUndef = isa<UndefValue>(Op0);
2561 bool FromUndef = isa<UndefValue>(Op1);
2563 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2564 I.idx_begin(), I.idx_end());
2566 SmallVector<EVT, 4> AggValueVTs;
2567 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2568 SmallVector<EVT, 4> ValValueVTs;
2569 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2571 unsigned NumAggValues = AggValueVTs.size();
2572 unsigned NumValValues = ValValueVTs.size();
2573 SmallVector<SDValue, 4> Values(NumAggValues);
2575 SDValue Agg = getValue(Op0);
2576 SDValue Val = getValue(Op1);
2578 // Copy the beginning value(s) from the original aggregate.
2579 for (; i != LinearIndex; ++i)
2580 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2581 SDValue(Agg.getNode(), Agg.getResNo() + i);
2582 // Copy values from the inserted value(s).
2583 for (; i != LinearIndex + NumValValues; ++i)
2584 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2585 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2586 // Copy remaining value(s) from the original aggregate.
2587 for (; i != NumAggValues; ++i)
2588 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2589 SDValue(Agg.getNode(), Agg.getResNo() + i);
2591 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2592 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2593 &Values[0], NumAggValues));
2596 void SelectionDAGBuilder::visitExtractValue(ExtractValueInst &I) {
2597 const Value *Op0 = I.getOperand(0);
2598 const Type *AggTy = Op0->getType();
2599 const Type *ValTy = I.getType();
2600 bool OutOfUndef = isa<UndefValue>(Op0);
2602 unsigned LinearIndex = ComputeLinearIndex(TLI, AggTy,
2603 I.idx_begin(), I.idx_end());
2605 SmallVector<EVT, 4> ValValueVTs;
2606 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2608 unsigned NumValValues = ValValueVTs.size();
2609 SmallVector<SDValue, 4> Values(NumValValues);
2611 SDValue Agg = getValue(Op0);
2612 // Copy out the selected value(s).
2613 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2614 Values[i - LinearIndex] =
2616 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2617 SDValue(Agg.getNode(), Agg.getResNo() + i);
2619 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2620 DAG.getVTList(&ValValueVTs[0], NumValValues),
2621 &Values[0], NumValValues));
2625 void SelectionDAGBuilder::visitGetElementPtr(User &I) {
2626 SDValue N = getValue(I.getOperand(0));
2627 const Type *Ty = I.getOperand(0)->getType();
2629 for (GetElementPtrInst::op_iterator OI = I.op_begin()+1, E = I.op_end();
2632 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2633 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2636 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2637 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2638 DAG.getIntPtrConstant(Offset));
2640 Ty = StTy->getElementType(Field);
2642 Ty = cast<SequentialType>(Ty)->getElementType();
2644 // If this is a constant subscript, handle it quickly.
2645 if (ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2646 if (CI->getZExtValue() == 0) continue;
2648 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2650 EVT PTy = TLI.getPointerTy();
2651 unsigned PtrBits = PTy.getSizeInBits();
2653 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2655 DAG.getConstant(Offs, MVT::i64));
2657 OffsVal = DAG.getIntPtrConstant(Offs);
2658 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2663 // N = N + Idx * ElementSize;
2664 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
2665 TD->getTypeAllocSize(Ty));
2666 SDValue IdxN = getValue(Idx);
2668 // If the index is smaller or larger than intptr_t, truncate or extend
2670 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
2672 // If this is a multiply by a power of two, turn it into a shl
2673 // immediately. This is a very common case.
2674 if (ElementSize != 1) {
2675 if (ElementSize.isPowerOf2()) {
2676 unsigned Amt = ElementSize.logBase2();
2677 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
2678 N.getValueType(), IdxN,
2679 DAG.getConstant(Amt, TLI.getPointerTy()));
2681 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
2682 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
2683 N.getValueType(), IdxN, Scale);
2687 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2688 N.getValueType(), N, IdxN);
2694 void SelectionDAGBuilder::visitAlloca(AllocaInst &I) {
2695 // If this is a fixed sized alloca in the entry block of the function,
2696 // allocate it statically on the stack.
2697 if (FuncInfo.StaticAllocaMap.count(&I))
2698 return; // getValue will auto-populate this.
2700 const Type *Ty = I.getAllocatedType();
2701 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
2703 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
2706 SDValue AllocSize = getValue(I.getArraySize());
2708 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), AllocSize.getValueType(),
2710 DAG.getConstant(TySize, AllocSize.getValueType()));
2714 EVT IntPtr = TLI.getPointerTy();
2715 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
2717 // Handle alignment. If the requested alignment is less than or equal to
2718 // the stack alignment, ignore it. If the size is greater than or equal to
2719 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
2720 unsigned StackAlign =
2721 TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
2722 if (Align <= StackAlign)
2725 // Round the size of the allocation up to the stack alignment size
2726 // by add SA-1 to the size.
2727 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2728 AllocSize.getValueType(), AllocSize,
2729 DAG.getIntPtrConstant(StackAlign-1));
2730 // Mask out the low bits for alignment purposes.
2731 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
2732 AllocSize.getValueType(), AllocSize,
2733 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
2735 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
2736 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
2737 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
2740 DAG.setRoot(DSA.getValue(1));
2742 // Inform the Frame Information that we have just allocated a variable-sized
2744 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject();
2747 void SelectionDAGBuilder::visitLoad(LoadInst &I) {
2748 const Value *SV = I.getOperand(0);
2749 SDValue Ptr = getValue(SV);
2751 const Type *Ty = I.getType();
2752 bool isVolatile = I.isVolatile();
2753 unsigned Alignment = I.getAlignment();
2755 SmallVector<EVT, 4> ValueVTs;
2756 SmallVector<uint64_t, 4> Offsets;
2757 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
2758 unsigned NumValues = ValueVTs.size();
2763 bool ConstantMemory = false;
2765 // Serialize volatile loads with other side effects.
2767 else if (AA->pointsToConstantMemory(SV)) {
2768 // Do not serialize (non-volatile) loads of constant memory with anything.
2769 Root = DAG.getEntryNode();
2770 ConstantMemory = true;
2772 // Do not serialize non-volatile loads against each other.
2773 Root = DAG.getRoot();
2776 SmallVector<SDValue, 4> Values(NumValues);
2777 SmallVector<SDValue, 4> Chains(NumValues);
2778 EVT PtrVT = Ptr.getValueType();
2779 for (unsigned i = 0; i != NumValues; ++i) {
2780 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
2781 DAG.getNode(ISD::ADD, getCurDebugLoc(),
2783 DAG.getConstant(Offsets[i], PtrVT)),
2784 SV, Offsets[i], isVolatile, Alignment);
2786 Chains[i] = L.getValue(1);
2789 if (!ConstantMemory) {
2790 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2792 &Chains[0], NumValues);
2796 PendingLoads.push_back(Chain);
2799 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2800 DAG.getVTList(&ValueVTs[0], NumValues),
2801 &Values[0], NumValues));
2805 void SelectionDAGBuilder::visitStore(StoreInst &I) {
2806 Value *SrcV = I.getOperand(0);
2807 Value *PtrV = I.getOperand(1);
2809 SmallVector<EVT, 4> ValueVTs;
2810 SmallVector<uint64_t, 4> Offsets;
2811 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
2812 unsigned NumValues = ValueVTs.size();
2816 // Get the lowered operands. Note that we do this after
2817 // checking if NumResults is zero, because with zero results
2818 // the operands won't have values in the map.
2819 SDValue Src = getValue(SrcV);
2820 SDValue Ptr = getValue(PtrV);
2822 SDValue Root = getRoot();
2823 SmallVector<SDValue, 4> Chains(NumValues);
2824 EVT PtrVT = Ptr.getValueType();
2825 bool isVolatile = I.isVolatile();
2826 unsigned Alignment = I.getAlignment();
2827 for (unsigned i = 0; i != NumValues; ++i)
2828 Chains[i] = DAG.getStore(Root, getCurDebugLoc(),
2829 SDValue(Src.getNode(), Src.getResNo() + i),
2830 DAG.getNode(ISD::ADD, getCurDebugLoc(),
2832 DAG.getConstant(Offsets[i], PtrVT)),
2833 PtrV, Offsets[i], isVolatile, Alignment);
2835 DAG.setRoot(DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
2836 MVT::Other, &Chains[0], NumValues));
2839 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
2841 void SelectionDAGBuilder::visitTargetIntrinsic(CallInst &I,
2842 unsigned Intrinsic) {
2843 bool HasChain = !I.doesNotAccessMemory();
2844 bool OnlyLoad = HasChain && I.onlyReadsMemory();
2846 // Build the operand list.
2847 SmallVector<SDValue, 8> Ops;
2848 if (HasChain) { // If this intrinsic has side-effects, chainify it.
2850 // We don't need to serialize loads against other loads.
2851 Ops.push_back(DAG.getRoot());
2853 Ops.push_back(getRoot());
2857 // Info is set by getTgtMemInstrinsic
2858 TargetLowering::IntrinsicInfo Info;
2859 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
2861 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
2862 if (!IsTgtIntrinsic)
2863 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
2865 // Add all operands of the call to the operand list.
2866 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
2867 SDValue Op = getValue(I.getOperand(i));
2868 assert(TLI.isTypeLegal(Op.getValueType()) &&
2869 "Intrinsic uses a non-legal type?");
2873 SmallVector<EVT, 4> ValueVTs;
2874 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2876 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
2877 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
2878 "Intrinsic uses a non-legal type?");
2882 ValueVTs.push_back(MVT::Other);
2884 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
2888 if (IsTgtIntrinsic) {
2889 // This is target intrinsic that touches memory
2890 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
2891 VTs, &Ops[0], Ops.size(),
2892 Info.memVT, Info.ptrVal, Info.offset,
2893 Info.align, Info.vol,
2894 Info.readMem, Info.writeMem);
2897 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
2898 VTs, &Ops[0], Ops.size());
2899 else if (I.getType() != Type::getVoidTy(*DAG.getContext()))
2900 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
2901 VTs, &Ops[0], Ops.size());
2903 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
2904 VTs, &Ops[0], Ops.size());
2907 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
2909 PendingLoads.push_back(Chain);
2913 if (I.getType() != Type::getVoidTy(*DAG.getContext())) {
2914 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
2915 EVT VT = TLI.getValueType(PTy);
2916 Result = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(), VT, Result);
2918 setValue(&I, Result);
2922 /// GetSignificand - Get the significand and build it into a floating-point
2923 /// number with exponent of 1:
2925 /// Op = (Op & 0x007fffff) | 0x3f800000;
2927 /// where Op is the hexidecimal representation of floating point value.
2929 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
2930 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
2931 DAG.getConstant(0x007fffff, MVT::i32));
2932 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
2933 DAG.getConstant(0x3f800000, MVT::i32));
2934 return DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t2);
2937 /// GetExponent - Get the exponent:
2939 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
2941 /// where Op is the hexidecimal representation of floating point value.
2943 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
2945 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
2946 DAG.getConstant(0x7f800000, MVT::i32));
2947 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
2948 DAG.getConstant(23, TLI.getPointerTy()));
2949 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
2950 DAG.getConstant(127, MVT::i32));
2951 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
2954 /// getF32Constant - Get 32-bit floating point constant.
2956 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
2957 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
2960 /// Inlined utility function to implement binary input atomic intrinsics for
2961 /// visitIntrinsicCall: I is a call instruction
2962 /// Op is the associated NodeType for I
2964 SelectionDAGBuilder::implVisitBinaryAtomic(CallInst& I, ISD::NodeType Op) {
2965 SDValue Root = getRoot();
2967 DAG.getAtomic(Op, getCurDebugLoc(),
2968 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
2970 getValue(I.getOperand(1)),
2971 getValue(I.getOperand(2)),
2974 DAG.setRoot(L.getValue(1));
2978 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
2980 SelectionDAGBuilder::implVisitAluOverflow(CallInst &I, ISD::NodeType Op) {
2981 SDValue Op1 = getValue(I.getOperand(1));
2982 SDValue Op2 = getValue(I.getOperand(2));
2984 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
2985 SDValue Result = DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2);
2987 setValue(&I, Result);
2991 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
2992 /// limited-precision mode.
2994 SelectionDAGBuilder::visitExp(CallInst &I) {
2996 DebugLoc dl = getCurDebugLoc();
2998 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
2999 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3000 SDValue Op = getValue(I.getOperand(1));
3002 // Put the exponent in the right bit position for later addition to the
3005 // #define LOG2OFe 1.4426950f
3006 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3007 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3008 getF32Constant(DAG, 0x3fb8aa3b));
3009 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3011 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3012 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3013 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3015 // IntegerPartOfX <<= 23;
3016 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3017 DAG.getConstant(23, TLI.getPointerTy()));
3019 if (LimitFloatPrecision <= 6) {
3020 // For floating-point precision of 6:
3022 // TwoToFractionalPartOfX =
3024 // (0.735607626f + 0.252464424f * x) * x;
3026 // error 0.0144103317, which is 6 bits
3027 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3028 getF32Constant(DAG, 0x3e814304));
3029 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3030 getF32Constant(DAG, 0x3f3c50c8));
3031 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3032 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3033 getF32Constant(DAG, 0x3f7f5e7e));
3034 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t5);
3036 // Add the exponent into the result in integer domain.
3037 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3038 TwoToFracPartOfX, IntegerPartOfX);
3040 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t6);
3041 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3042 // For floating-point precision of 12:
3044 // TwoToFractionalPartOfX =
3047 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3049 // 0.000107046256 error, which is 13 to 14 bits
3050 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3051 getF32Constant(DAG, 0x3da235e3));
3052 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3053 getF32Constant(DAG, 0x3e65b8f3));
3054 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3055 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3056 getF32Constant(DAG, 0x3f324b07));
3057 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3058 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3059 getF32Constant(DAG, 0x3f7ff8fd));
3060 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,MVT::i32, t7);
3062 // Add the exponent into the result in integer domain.
3063 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3064 TwoToFracPartOfX, IntegerPartOfX);
3066 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t8);
3067 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3068 // For floating-point precision of 18:
3070 // TwoToFractionalPartOfX =
3074 // (0.554906021e-1f +
3075 // (0.961591928e-2f +
3076 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3078 // error 2.47208000*10^(-7), which is better than 18 bits
3079 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3080 getF32Constant(DAG, 0x3924b03e));
3081 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3082 getF32Constant(DAG, 0x3ab24b87));
3083 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3084 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3085 getF32Constant(DAG, 0x3c1d8c17));
3086 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3087 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3088 getF32Constant(DAG, 0x3d634a1d));
3089 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3090 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3091 getF32Constant(DAG, 0x3e75fe14));
3092 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3093 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3094 getF32Constant(DAG, 0x3f317234));
3095 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3096 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3097 getF32Constant(DAG, 0x3f800000));
3098 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BIT_CONVERT, dl,
3101 // Add the exponent into the result in integer domain.
3102 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3103 TwoToFracPartOfX, IntegerPartOfX);
3105 result = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::f32, t14);
3108 // No special expansion.
3109 result = DAG.getNode(ISD::FEXP, dl,
3110 getValue(I.getOperand(1)).getValueType(),
3111 getValue(I.getOperand(1)));
3114 setValue(&I, result);
3117 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3118 /// limited-precision mode.
3120 SelectionDAGBuilder::visitLog(CallInst &I) {
3122 DebugLoc dl = getCurDebugLoc();
3124 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3125 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3126 SDValue Op = getValue(I.getOperand(1));
3127 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3129 // Scale the exponent by log(2) [0.69314718f].
3130 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3131 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3132 getF32Constant(DAG, 0x3f317218));
3134 // Get the significand and build it into a floating-point number with
3136 SDValue X = GetSignificand(DAG, Op1, dl);
3138 if (LimitFloatPrecision <= 6) {
3139 // For floating-point precision of 6:
3143 // (1.4034025f - 0.23903021f * x) * x;
3145 // error 0.0034276066, which is better than 8 bits
3146 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3147 getF32Constant(DAG, 0xbe74c456));
3148 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3149 getF32Constant(DAG, 0x3fb3a2b1));
3150 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3151 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3152 getF32Constant(DAG, 0x3f949a29));
3154 result = DAG.getNode(ISD::FADD, dl,
3155 MVT::f32, LogOfExponent, LogOfMantissa);
3156 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3157 // For floating-point precision of 12:
3163 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3165 // error 0.000061011436, which is 14 bits
3166 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3167 getF32Constant(DAG, 0xbd67b6d6));
3168 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3169 getF32Constant(DAG, 0x3ee4f4b8));
3170 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3171 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3172 getF32Constant(DAG, 0x3fbc278b));
3173 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3174 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3175 getF32Constant(DAG, 0x40348e95));
3176 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3177 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3178 getF32Constant(DAG, 0x3fdef31a));
3180 result = DAG.getNode(ISD::FADD, dl,
3181 MVT::f32, LogOfExponent, LogOfMantissa);
3182 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3183 // For floating-point precision of 18:
3191 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3193 // error 0.0000023660568, which is better than 18 bits
3194 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3195 getF32Constant(DAG, 0xbc91e5ac));
3196 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3197 getF32Constant(DAG, 0x3e4350aa));
3198 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3199 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3200 getF32Constant(DAG, 0x3f60d3e3));
3201 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3202 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3203 getF32Constant(DAG, 0x4011cdf0));
3204 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3205 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3206 getF32Constant(DAG, 0x406cfd1c));
3207 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3208 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3209 getF32Constant(DAG, 0x408797cb));
3210 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3211 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3212 getF32Constant(DAG, 0x4006dcab));
3214 result = DAG.getNode(ISD::FADD, dl,
3215 MVT::f32, LogOfExponent, LogOfMantissa);
3218 // No special expansion.
3219 result = DAG.getNode(ISD::FLOG, dl,
3220 getValue(I.getOperand(1)).getValueType(),
3221 getValue(I.getOperand(1)));
3224 setValue(&I, result);
3227 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3228 /// limited-precision mode.
3230 SelectionDAGBuilder::visitLog2(CallInst &I) {
3232 DebugLoc dl = getCurDebugLoc();
3234 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3235 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3236 SDValue Op = getValue(I.getOperand(1));
3237 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3239 // Get the exponent.
3240 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
3242 // Get the significand and build it into a floating-point number with
3244 SDValue X = GetSignificand(DAG, Op1, dl);
3246 // Different possible minimax approximations of significand in
3247 // floating-point for various degrees of accuracy over [1,2].
3248 if (LimitFloatPrecision <= 6) {
3249 // For floating-point precision of 6:
3251 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3253 // error 0.0049451742, which is more than 7 bits
3254 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3255 getF32Constant(DAG, 0xbeb08fe0));
3256 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3257 getF32Constant(DAG, 0x40019463));
3258 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3259 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3260 getF32Constant(DAG, 0x3fd6633d));
3262 result = DAG.getNode(ISD::FADD, dl,
3263 MVT::f32, LogOfExponent, Log2ofMantissa);
3264 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3265 // For floating-point precision of 12:
3271 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3273 // error 0.0000876136000, which is better than 13 bits
3274 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3275 getF32Constant(DAG, 0xbda7262e));
3276 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3277 getF32Constant(DAG, 0x3f25280b));
3278 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3279 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3280 getF32Constant(DAG, 0x4007b923));
3281 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3282 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3283 getF32Constant(DAG, 0x40823e2f));
3284 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3285 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3286 getF32Constant(DAG, 0x4020d29c));
3288 result = DAG.getNode(ISD::FADD, dl,
3289 MVT::f32, LogOfExponent, Log2ofMantissa);
3290 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3291 // For floating-point precision of 18:
3300 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3302 // error 0.0000018516, which is better than 18 bits
3303 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3304 getF32Constant(DAG, 0xbcd2769e));
3305 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3306 getF32Constant(DAG, 0x3e8ce0b9));
3307 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3308 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3309 getF32Constant(DAG, 0x3fa22ae7));
3310 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3311 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3312 getF32Constant(DAG, 0x40525723));
3313 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3314 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3315 getF32Constant(DAG, 0x40aaf200));
3316 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3317 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3318 getF32Constant(DAG, 0x40c39dad));
3319 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3320 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3321 getF32Constant(DAG, 0x4042902c));
3323 result = DAG.getNode(ISD::FADD, dl,
3324 MVT::f32, LogOfExponent, Log2ofMantissa);
3327 // No special expansion.
3328 result = DAG.getNode(ISD::FLOG2, dl,
3329 getValue(I.getOperand(1)).getValueType(),
3330 getValue(I.getOperand(1)));
3333 setValue(&I, result);
3336 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3337 /// limited-precision mode.
3339 SelectionDAGBuilder::visitLog10(CallInst &I) {
3341 DebugLoc dl = getCurDebugLoc();
3343 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3344 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3345 SDValue Op = getValue(I.getOperand(1));
3346 SDValue Op1 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, Op);
3348 // Scale the exponent by log10(2) [0.30102999f].
3349 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3350 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3351 getF32Constant(DAG, 0x3e9a209a));
3353 // Get the significand and build it into a floating-point number with
3355 SDValue X = GetSignificand(DAG, Op1, dl);
3357 if (LimitFloatPrecision <= 6) {
3358 // For floating-point precision of 6:
3360 // Log10ofMantissa =
3362 // (0.60948995f - 0.10380950f * x) * x;
3364 // error 0.0014886165, which is 6 bits
3365 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3366 getF32Constant(DAG, 0xbdd49a13));
3367 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3368 getF32Constant(DAG, 0x3f1c0789));
3369 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3370 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3371 getF32Constant(DAG, 0x3f011300));
3373 result = DAG.getNode(ISD::FADD, dl,
3374 MVT::f32, LogOfExponent, Log10ofMantissa);
3375 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3376 // For floating-point precision of 12:
3378 // Log10ofMantissa =
3381 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3383 // error 0.00019228036, which is better than 12 bits
3384 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3385 getF32Constant(DAG, 0x3d431f31));
3386 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3387 getF32Constant(DAG, 0x3ea21fb2));
3388 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3389 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3390 getF32Constant(DAG, 0x3f6ae232));
3391 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3392 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3393 getF32Constant(DAG, 0x3f25f7c3));
3395 result = DAG.getNode(ISD::FADD, dl,
3396 MVT::f32, LogOfExponent, Log10ofMantissa);
3397 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3398 // For floating-point precision of 18:
3400 // Log10ofMantissa =
3405 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3407 // error 0.0000037995730, which is better than 18 bits
3408 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3409 getF32Constant(DAG, 0x3c5d51ce));
3410 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3411 getF32Constant(DAG, 0x3e00685a));
3412 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3413 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3414 getF32Constant(DAG, 0x3efb6798));
3415 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3416 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3417 getF32Constant(DAG, 0x3f88d192));
3418 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3419 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3420 getF32Constant(DAG, 0x3fc4316c));
3421 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3422 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
3423 getF32Constant(DAG, 0x3f57ce70));
3425 result = DAG.getNode(ISD::FADD, dl,
3426 MVT::f32, LogOfExponent, Log10ofMantissa);
3429 // No special expansion.
3430 result = DAG.getNode(ISD::FLOG10, dl,
3431 getValue(I.getOperand(1)).getValueType(),
3432 getValue(I.getOperand(1)));
3435 setValue(&I, result);
3438 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3439 /// limited-precision mode.
3441 SelectionDAGBuilder::visitExp2(CallInst &I) {
3443 DebugLoc dl = getCurDebugLoc();
3445 if (getValue(I.getOperand(1)).getValueType() == MVT::f32 &&
3446 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3447 SDValue Op = getValue(I.getOperand(1));
3449 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
3451 // FractionalPartOfX = x - (float)IntegerPartOfX;
3452 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3453 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
3455 // IntegerPartOfX <<= 23;
3456 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3457 DAG.getConstant(23, TLI.getPointerTy()));
3459 if (LimitFloatPrecision <= 6) {
3460 // For floating-point precision of 6:
3462 // TwoToFractionalPartOfX =
3464 // (0.735607626f + 0.252464424f * x) * x;
3466 // error 0.0144103317, which is 6 bits
3467 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3468 getF32Constant(DAG, 0x3e814304));
3469 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3470 getF32Constant(DAG, 0x3f3c50c8));
3471 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3472 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3473 getF32Constant(DAG, 0x3f7f5e7e));
3474 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3475 SDValue TwoToFractionalPartOfX =
3476 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3478 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3479 MVT::f32, TwoToFractionalPartOfX);
3480 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3481 // For floating-point precision of 12:
3483 // TwoToFractionalPartOfX =
3486 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3488 // error 0.000107046256, which is 13 to 14 bits
3489 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3490 getF32Constant(DAG, 0x3da235e3));
3491 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3492 getF32Constant(DAG, 0x3e65b8f3));
3493 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3494 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3495 getF32Constant(DAG, 0x3f324b07));
3496 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3497 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3498 getF32Constant(DAG, 0x3f7ff8fd));
3499 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3500 SDValue TwoToFractionalPartOfX =
3501 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3503 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3504 MVT::f32, TwoToFractionalPartOfX);
3505 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3506 // For floating-point precision of 18:
3508 // TwoToFractionalPartOfX =
3512 // (0.554906021e-1f +
3513 // (0.961591928e-2f +
3514 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3515 // error 2.47208000*10^(-7), which is better than 18 bits
3516 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3517 getF32Constant(DAG, 0x3924b03e));
3518 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3519 getF32Constant(DAG, 0x3ab24b87));
3520 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3521 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3522 getF32Constant(DAG, 0x3c1d8c17));
3523 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3524 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3525 getF32Constant(DAG, 0x3d634a1d));
3526 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3527 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3528 getF32Constant(DAG, 0x3e75fe14));
3529 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3530 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3531 getF32Constant(DAG, 0x3f317234));
3532 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3533 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3534 getF32Constant(DAG, 0x3f800000));
3535 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3536 SDValue TwoToFractionalPartOfX =
3537 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3539 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3540 MVT::f32, TwoToFractionalPartOfX);
3543 // No special expansion.
3544 result = DAG.getNode(ISD::FEXP2, dl,
3545 getValue(I.getOperand(1)).getValueType(),
3546 getValue(I.getOperand(1)));
3549 setValue(&I, result);
3552 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3553 /// limited-precision mode with x == 10.0f.
3555 SelectionDAGBuilder::visitPow(CallInst &I) {
3557 Value *Val = I.getOperand(1);
3558 DebugLoc dl = getCurDebugLoc();
3559 bool IsExp10 = false;
3561 if (getValue(Val).getValueType() == MVT::f32 &&
3562 getValue(I.getOperand(2)).getValueType() == MVT::f32 &&
3563 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3564 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3565 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3567 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3572 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3573 SDValue Op = getValue(I.getOperand(2));
3575 // Put the exponent in the right bit position for later addition to the
3578 // #define LOG2OF10 3.3219281f
3579 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3580 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3581 getF32Constant(DAG, 0x40549a78));
3582 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3584 // FractionalPartOfX = x - (float)IntegerPartOfX;
3585 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3586 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3588 // IntegerPartOfX <<= 23;
3589 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3590 DAG.getConstant(23, TLI.getPointerTy()));
3592 if (LimitFloatPrecision <= 6) {
3593 // For floating-point precision of 6:
3595 // twoToFractionalPartOfX =
3597 // (0.735607626f + 0.252464424f * x) * x;
3599 // error 0.0144103317, which is 6 bits
3600 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3601 getF32Constant(DAG, 0x3e814304));
3602 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3603 getF32Constant(DAG, 0x3f3c50c8));
3604 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3605 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3606 getF32Constant(DAG, 0x3f7f5e7e));
3607 SDValue t6 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t5);
3608 SDValue TwoToFractionalPartOfX =
3609 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3611 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3612 MVT::f32, TwoToFractionalPartOfX);
3613 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3614 // For floating-point precision of 12:
3616 // TwoToFractionalPartOfX =
3619 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3621 // error 0.000107046256, which is 13 to 14 bits
3622 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3623 getF32Constant(DAG, 0x3da235e3));
3624 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3625 getF32Constant(DAG, 0x3e65b8f3));
3626 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3627 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3628 getF32Constant(DAG, 0x3f324b07));
3629 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3630 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3631 getF32Constant(DAG, 0x3f7ff8fd));
3632 SDValue t8 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t7);
3633 SDValue TwoToFractionalPartOfX =
3634 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3636 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3637 MVT::f32, TwoToFractionalPartOfX);
3638 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3639 // For floating-point precision of 18:
3641 // TwoToFractionalPartOfX =
3645 // (0.554906021e-1f +
3646 // (0.961591928e-2f +
3647 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3648 // error 2.47208000*10^(-7), which is better than 18 bits
3649 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3650 getF32Constant(DAG, 0x3924b03e));
3651 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3652 getF32Constant(DAG, 0x3ab24b87));
3653 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3654 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3655 getF32Constant(DAG, 0x3c1d8c17));
3656 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3657 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3658 getF32Constant(DAG, 0x3d634a1d));
3659 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3660 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3661 getF32Constant(DAG, 0x3e75fe14));
3662 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3663 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3664 getF32Constant(DAG, 0x3f317234));
3665 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3666 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3667 getF32Constant(DAG, 0x3f800000));
3668 SDValue t14 = DAG.getNode(ISD::BIT_CONVERT, dl, MVT::i32, t13);
3669 SDValue TwoToFractionalPartOfX =
3670 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3672 result = DAG.getNode(ISD::BIT_CONVERT, dl,
3673 MVT::f32, TwoToFractionalPartOfX);
3676 // No special expansion.
3677 result = DAG.getNode(ISD::FPOW, dl,
3678 getValue(I.getOperand(1)).getValueType(),
3679 getValue(I.getOperand(1)),
3680 getValue(I.getOperand(2)));
3683 setValue(&I, result);
3686 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
3687 /// we want to emit this as a call to a named external function, return the name
3688 /// otherwise lower it and return null.
3690 SelectionDAGBuilder::visitIntrinsicCall(CallInst &I, unsigned Intrinsic) {
3691 DebugLoc dl = getCurDebugLoc();
3692 switch (Intrinsic) {
3694 // By default, turn this into a target intrinsic node.
3695 visitTargetIntrinsic(I, Intrinsic);
3697 case Intrinsic::vastart: visitVAStart(I); return 0;
3698 case Intrinsic::vaend: visitVAEnd(I); return 0;
3699 case Intrinsic::vacopy: visitVACopy(I); return 0;
3700 case Intrinsic::returnaddress:
3701 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
3702 getValue(I.getOperand(1))));
3704 case Intrinsic::frameaddress:
3705 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
3706 getValue(I.getOperand(1))));
3708 case Intrinsic::setjmp:
3709 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
3711 case Intrinsic::longjmp:
3712 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
3714 case Intrinsic::memcpy: {
3715 SDValue Op1 = getValue(I.getOperand(1));
3716 SDValue Op2 = getValue(I.getOperand(2));
3717 SDValue Op3 = getValue(I.getOperand(3));
3718 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3719 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
3720 I.getOperand(1), 0, I.getOperand(2), 0));
3723 case Intrinsic::memset: {
3724 SDValue Op1 = getValue(I.getOperand(1));
3725 SDValue Op2 = getValue(I.getOperand(2));
3726 SDValue Op3 = getValue(I.getOperand(3));
3727 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3728 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align,
3729 I.getOperand(1), 0));
3732 case Intrinsic::memmove: {
3733 SDValue Op1 = getValue(I.getOperand(1));
3734 SDValue Op2 = getValue(I.getOperand(2));
3735 SDValue Op3 = getValue(I.getOperand(3));
3736 unsigned Align = cast<ConstantInt>(I.getOperand(4))->getZExtValue();
3738 // If the source and destination are known to not be aliases, we can
3739 // lower memmove as memcpy.
3740 uint64_t Size = -1ULL;
3741 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op3))
3742 Size = C->getZExtValue();
3743 if (AA->alias(I.getOperand(1), Size, I.getOperand(2), Size) ==
3744 AliasAnalysis::NoAlias) {
3745 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, false,
3746 I.getOperand(1), 0, I.getOperand(2), 0));
3750 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align,
3751 I.getOperand(1), 0, I.getOperand(2), 0));
3754 case Intrinsic::dbg_stoppoint:
3755 case Intrinsic::dbg_region_start:
3756 case Intrinsic::dbg_region_end:
3757 case Intrinsic::dbg_func_start:
3758 // FIXME - Remove this instructions once the dust settles.
3760 case Intrinsic::dbg_declare: {
3761 if (OptLevel != CodeGenOpt::None)
3762 // FIXME: Variable debug info is not supported here.
3764 DwarfWriter *DW = DAG.getDwarfWriter();
3767 DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
3768 if (!isValidDebugInfoIntrinsic(DI, CodeGenOpt::None))
3771 MDNode *Variable = DI.getVariable();
3772 Value *Address = DI.getAddress();
3773 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
3774 Address = BCI->getOperand(0);
3775 AllocaInst *AI = dyn_cast<AllocaInst>(Address);
3776 // Don't handle byval struct arguments or VLAs, for example.
3779 DenseMap<const AllocaInst*, int>::iterator SI =
3780 FuncInfo.StaticAllocaMap.find(AI);
3781 if (SI == FuncInfo.StaticAllocaMap.end())
3783 int FI = SI->second;
3785 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3787 MetadataContext &TheMetadata =
3788 DI.getParent()->getContext().getMetadata();
3789 unsigned MDDbgKind = TheMetadata.getMDKind("dbg");
3790 MDNode *Dbg = TheMetadata.getMD(MDDbgKind, &DI);
3791 MMI->setVariableDbgInfo(Variable, FI, Dbg);
3795 case Intrinsic::eh_exception: {
3796 // Insert the EXCEPTIONADDR instruction.
3797 assert(CurMBB->isLandingPad() &&"Call to eh.exception not in landing pad!");
3798 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3800 Ops[0] = DAG.getRoot();
3801 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
3803 DAG.setRoot(Op.getValue(1));
3807 case Intrinsic::eh_selector: {
3808 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3810 if (CurMBB->isLandingPad())
3811 AddCatchInfo(I, MMI, CurMBB);
3814 FuncInfo.CatchInfoLost.insert(&I);
3816 // FIXME: Mark exception selector register as live in. Hack for PR1508.
3817 unsigned Reg = TLI.getExceptionSelectorRegister();
3818 if (Reg) CurMBB->addLiveIn(Reg);
3821 // Insert the EHSELECTION instruction.
3822 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
3824 Ops[0] = getValue(I.getOperand(1));
3826 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
3828 DAG.setRoot(Op.getValue(1));
3830 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
3834 case Intrinsic::eh_typeid_for: {
3835 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
3838 // Find the type id for the given typeinfo.
3839 GlobalVariable *GV = ExtractTypeInfo(I.getOperand(1));
3841 unsigned TypeID = MMI->getTypeIDFor(GV);
3842 setValue(&I, DAG.getConstant(TypeID, MVT::i32));
3844 // Return something different to eh_selector.
3845 setValue(&I, DAG.getConstant(1, MVT::i32));
3851 case Intrinsic::eh_return_i32:
3852 case Intrinsic::eh_return_i64:
3853 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3854 MMI->setCallsEHReturn(true);
3855 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
3858 getValue(I.getOperand(1)),
3859 getValue(I.getOperand(2))));
3861 setValue(&I, DAG.getConstant(0, TLI.getPointerTy()));
3865 case Intrinsic::eh_unwind_init:
3866 if (MachineModuleInfo *MMI = DAG.getMachineModuleInfo()) {
3867 MMI->setCallsUnwindInit(true);
3872 case Intrinsic::eh_dwarf_cfa: {
3873 EVT VT = getValue(I.getOperand(1)).getValueType();
3874 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getOperand(1)), dl,
3875 TLI.getPointerTy());
3877 SDValue Offset = DAG.getNode(ISD::ADD, dl,
3879 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
3880 TLI.getPointerTy()),
3882 setValue(&I, DAG.getNode(ISD::ADD, dl,
3884 DAG.getNode(ISD::FRAMEADDR, dl,
3887 TLI.getPointerTy())),
3891 case Intrinsic::convertff:
3892 case Intrinsic::convertfsi:
3893 case Intrinsic::convertfui:
3894 case Intrinsic::convertsif:
3895 case Intrinsic::convertuif:
3896 case Intrinsic::convertss:
3897 case Intrinsic::convertsu:
3898 case Intrinsic::convertus:
3899 case Intrinsic::convertuu: {
3900 ISD::CvtCode Code = ISD::CVT_INVALID;
3901 switch (Intrinsic) {
3902 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
3903 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
3904 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
3905 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
3906 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
3907 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
3908 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
3909 case Intrinsic::convertus: Code = ISD::CVT_US; break;
3910 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
3912 EVT DestVT = TLI.getValueType(I.getType());
3913 Value* Op1 = I.getOperand(1);
3914 setValue(&I, DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
3915 DAG.getValueType(DestVT),
3916 DAG.getValueType(getValue(Op1).getValueType()),
3917 getValue(I.getOperand(2)),
3918 getValue(I.getOperand(3)),
3923 case Intrinsic::sqrt:
3924 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
3925 getValue(I.getOperand(1)).getValueType(),
3926 getValue(I.getOperand(1))));
3928 case Intrinsic::powi:
3929 setValue(&I, DAG.getNode(ISD::FPOWI, dl,
3930 getValue(I.getOperand(1)).getValueType(),
3931 getValue(I.getOperand(1)),
3932 getValue(I.getOperand(2))));
3934 case Intrinsic::sin:
3935 setValue(&I, DAG.getNode(ISD::FSIN, dl,
3936 getValue(I.getOperand(1)).getValueType(),
3937 getValue(I.getOperand(1))));
3939 case Intrinsic::cos:
3940 setValue(&I, DAG.getNode(ISD::FCOS, dl,
3941 getValue(I.getOperand(1)).getValueType(),
3942 getValue(I.getOperand(1))));
3944 case Intrinsic::log:
3947 case Intrinsic::log2:
3950 case Intrinsic::log10:
3953 case Intrinsic::exp:
3956 case Intrinsic::exp2:
3959 case Intrinsic::pow:
3962 case Intrinsic::pcmarker: {
3963 SDValue Tmp = getValue(I.getOperand(1));
3964 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
3967 case Intrinsic::readcyclecounter: {
3968 SDValue Op = getRoot();
3969 SDValue Tmp = DAG.getNode(ISD::READCYCLECOUNTER, dl,
3970 DAG.getVTList(MVT::i64, MVT::Other),
3973 DAG.setRoot(Tmp.getValue(1));
3976 case Intrinsic::bswap:
3977 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
3978 getValue(I.getOperand(1)).getValueType(),
3979 getValue(I.getOperand(1))));
3981 case Intrinsic::cttz: {
3982 SDValue Arg = getValue(I.getOperand(1));
3983 EVT Ty = Arg.getValueType();
3984 SDValue result = DAG.getNode(ISD::CTTZ, dl, Ty, Arg);
3985 setValue(&I, result);
3988 case Intrinsic::ctlz: {
3989 SDValue Arg = getValue(I.getOperand(1));
3990 EVT Ty = Arg.getValueType();
3991 SDValue result = DAG.getNode(ISD::CTLZ, dl, Ty, Arg);
3992 setValue(&I, result);
3995 case Intrinsic::ctpop: {
3996 SDValue Arg = getValue(I.getOperand(1));
3997 EVT Ty = Arg.getValueType();
3998 SDValue result = DAG.getNode(ISD::CTPOP, dl, Ty, Arg);
3999 setValue(&I, result);
4002 case Intrinsic::stacksave: {
4003 SDValue Op = getRoot();
4004 SDValue Tmp = DAG.getNode(ISD::STACKSAVE, dl,
4005 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4007 DAG.setRoot(Tmp.getValue(1));
4010 case Intrinsic::stackrestore: {
4011 SDValue Tmp = getValue(I.getOperand(1));
4012 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Tmp));
4015 case Intrinsic::stackprotector: {
4016 // Emit code into the DAG to store the stack guard onto the stack.
4017 MachineFunction &MF = DAG.getMachineFunction();
4018 MachineFrameInfo *MFI = MF.getFrameInfo();
4019 EVT PtrTy = TLI.getPointerTy();
4021 SDValue Src = getValue(I.getOperand(1)); // The guard's value.
4022 AllocaInst *Slot = cast<AllocaInst>(I.getOperand(2));
4024 int FI = FuncInfo.StaticAllocaMap[Slot];
4025 MFI->setStackProtectorIndex(FI);
4027 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4029 // Store the stack protector onto the stack.
4030 SDValue Result = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4031 PseudoSourceValue::getFixedStack(FI),
4033 setValue(&I, Result);
4034 DAG.setRoot(Result);
4037 case Intrinsic::objectsize: {
4038 // If we don't know by now, we're never going to know.
4039 ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand(2));
4041 assert(CI && "Non-constant type in __builtin_object_size?");
4043 SDValue Arg = getValue(I.getOperand(0));
4044 EVT Ty = Arg.getValueType();
4046 if (CI->getZExtValue() < 2)
4047 setValue(&I, DAG.getConstant(-1ULL, Ty));
4049 setValue(&I, DAG.getConstant(0, Ty));
4052 case Intrinsic::var_annotation:
4053 // Discard annotate attributes
4056 case Intrinsic::init_trampoline: {
4057 const Function *F = cast<Function>(I.getOperand(2)->stripPointerCasts());
4061 Ops[1] = getValue(I.getOperand(1));
4062 Ops[2] = getValue(I.getOperand(2));
4063 Ops[3] = getValue(I.getOperand(3));
4064 Ops[4] = DAG.getSrcValue(I.getOperand(1));
4065 Ops[5] = DAG.getSrcValue(F);
4067 SDValue Tmp = DAG.getNode(ISD::TRAMPOLINE, dl,
4068 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4072 DAG.setRoot(Tmp.getValue(1));
4076 case Intrinsic::gcroot:
4078 Value *Alloca = I.getOperand(1);
4079 Constant *TypeMap = cast<Constant>(I.getOperand(2));
4081 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4082 GFI->addStackRoot(FI->getIndex(), TypeMap);
4086 case Intrinsic::gcread:
4087 case Intrinsic::gcwrite:
4088 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
4091 case Intrinsic::flt_rounds: {
4092 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
4096 case Intrinsic::trap: {
4097 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
4101 case Intrinsic::uadd_with_overflow:
4102 return implVisitAluOverflow(I, ISD::UADDO);
4103 case Intrinsic::sadd_with_overflow:
4104 return implVisitAluOverflow(I, ISD::SADDO);
4105 case Intrinsic::usub_with_overflow:
4106 return implVisitAluOverflow(I, ISD::USUBO);
4107 case Intrinsic::ssub_with_overflow:
4108 return implVisitAluOverflow(I, ISD::SSUBO);
4109 case Intrinsic::umul_with_overflow:
4110 return implVisitAluOverflow(I, ISD::UMULO);
4111 case Intrinsic::smul_with_overflow:
4112 return implVisitAluOverflow(I, ISD::SMULO);
4114 case Intrinsic::prefetch: {
4117 Ops[1] = getValue(I.getOperand(1));
4118 Ops[2] = getValue(I.getOperand(2));
4119 Ops[3] = getValue(I.getOperand(3));
4120 DAG.setRoot(DAG.getNode(ISD::PREFETCH, dl, MVT::Other, &Ops[0], 4));
4124 case Intrinsic::memory_barrier: {
4127 for (int x = 1; x < 6; ++x)
4128 Ops[x] = getValue(I.getOperand(x));
4130 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
4133 case Intrinsic::atomic_cmp_swap: {
4134 SDValue Root = getRoot();
4136 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
4137 getValue(I.getOperand(2)).getValueType().getSimpleVT(),
4139 getValue(I.getOperand(1)),
4140 getValue(I.getOperand(2)),
4141 getValue(I.getOperand(3)),
4144 DAG.setRoot(L.getValue(1));
4147 case Intrinsic::atomic_load_add:
4148 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4149 case Intrinsic::atomic_load_sub:
4150 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4151 case Intrinsic::atomic_load_or:
4152 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4153 case Intrinsic::atomic_load_xor:
4154 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4155 case Intrinsic::atomic_load_and:
4156 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4157 case Intrinsic::atomic_load_nand:
4158 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4159 case Intrinsic::atomic_load_max:
4160 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4161 case Intrinsic::atomic_load_min:
4162 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4163 case Intrinsic::atomic_load_umin:
4164 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4165 case Intrinsic::atomic_load_umax:
4166 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4167 case Intrinsic::atomic_swap:
4168 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4170 case Intrinsic::invariant_start:
4171 case Intrinsic::lifetime_start:
4172 // Discard region information.
4173 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
4175 case Intrinsic::invariant_end:
4176 case Intrinsic::lifetime_end:
4177 // Discard region information.
4182 /// Test if the given instruction is in a position to be optimized
4183 /// with a tail-call. This roughly means that it's in a block with
4184 /// a return and there's nothing that needs to be scheduled
4185 /// between it and the return.
4187 /// This function only tests target-independent requirements.
4188 /// For target-dependent requirements, a target should override
4189 /// TargetLowering::IsEligibleForTailCallOptimization.
4192 isInTailCallPosition(const Instruction *I, Attributes CalleeRetAttr,
4193 const TargetLowering &TLI) {
4194 const BasicBlock *ExitBB = I->getParent();
4195 const TerminatorInst *Term = ExitBB->getTerminator();
4196 const ReturnInst *Ret = dyn_cast<ReturnInst>(Term);
4197 const Function *F = ExitBB->getParent();
4199 // The block must end in a return statement or an unreachable.
4200 if (!Ret && !isa<UnreachableInst>(Term)) return false;
4202 // If I will have a chain, make sure no other instruction that will have a
4203 // chain interposes between I and the return.
4204 if (I->mayHaveSideEffects() || I->mayReadFromMemory() ||
4205 !I->isSafeToSpeculativelyExecute())
4206 for (BasicBlock::const_iterator BBI = prior(prior(ExitBB->end())); ;
4210 if (BBI->mayHaveSideEffects() || BBI->mayReadFromMemory() ||
4211 !BBI->isSafeToSpeculativelyExecute())
4215 // If the block ends with a void return or unreachable, it doesn't matter
4216 // what the call's return type is.
4217 if (!Ret || Ret->getNumOperands() == 0) return true;
4219 // If the return value is undef, it doesn't matter what the call's
4221 if (isa<UndefValue>(Ret->getOperand(0))) return true;
4223 // Conservatively require the attributes of the call to match those of
4224 // the return. Ignore noalias because it doesn't affect the call sequence.
4225 unsigned CallerRetAttr = F->getAttributes().getRetAttributes();
4226 if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
4229 // Otherwise, make sure the unmodified return value of I is the return value.
4230 for (const Instruction *U = dyn_cast<Instruction>(Ret->getOperand(0)); ;
4231 U = dyn_cast<Instruction>(U->getOperand(0))) {
4234 if (!U->hasOneUse())
4238 // Check for a truly no-op truncate.
4239 if (isa<TruncInst>(U) &&
4240 TLI.isTruncateFree(U->getOperand(0)->getType(), U->getType()))
4242 // Check for a truly no-op bitcast.
4243 if (isa<BitCastInst>(U) &&
4244 (U->getOperand(0)->getType() == U->getType() ||
4245 (isa<PointerType>(U->getOperand(0)->getType()) &&
4246 isa<PointerType>(U->getType()))))
4248 // Otherwise it's not a true no-op.
4255 void SelectionDAGBuilder::LowerCallTo(CallSite CS, SDValue Callee,
4257 MachineBasicBlock *LandingPad) {
4258 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4259 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4260 const Type *RetTy = FTy->getReturnType();
4261 MachineModuleInfo *MMI = DAG.getMachineModuleInfo();
4262 unsigned BeginLabel = 0, EndLabel = 0;
4264 TargetLowering::ArgListTy Args;
4265 TargetLowering::ArgListEntry Entry;
4266 Args.reserve(CS.arg_size());
4268 // Check whether the function can return without sret-demotion.
4269 SmallVector<EVT, 4> OutVTs;
4270 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
4271 SmallVector<uint64_t, 4> Offsets;
4272 getReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
4273 OutVTs, OutsFlags, TLI, &Offsets);
4276 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
4277 FTy->isVarArg(), OutVTs, OutsFlags, DAG);
4279 SDValue DemoteStackSlot;
4281 if (!CanLowerReturn) {
4282 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
4283 FTy->getReturnType());
4284 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
4285 FTy->getReturnType());
4286 MachineFunction &MF = DAG.getMachineFunction();
4287 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
4288 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
4290 DemoteStackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
4291 Entry.Node = DemoteStackSlot;
4292 Entry.Ty = StackSlotPtrType;
4293 Entry.isSExt = false;
4294 Entry.isZExt = false;
4295 Entry.isInReg = false;
4296 Entry.isSRet = true;
4297 Entry.isNest = false;
4298 Entry.isByVal = false;
4299 Entry.Alignment = Align;
4300 Args.push_back(Entry);
4301 RetTy = Type::getVoidTy(FTy->getContext());
4304 for (CallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4306 SDValue ArgNode = getValue(*i);
4307 Entry.Node = ArgNode; Entry.Ty = (*i)->getType();
4309 unsigned attrInd = i - CS.arg_begin() + 1;
4310 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4311 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4312 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4313 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4314 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4315 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4316 Entry.Alignment = CS.getParamAlignment(attrInd);
4317 Args.push_back(Entry);
4320 if (LandingPad && MMI) {
4321 // Insert a label before the invoke call to mark the try range. This can be
4322 // used to detect deletion of the invoke via the MachineModuleInfo.
4323 BeginLabel = MMI->NextLabelID();
4325 // Both PendingLoads and PendingExports must be flushed here;
4326 // this call might not return.
4328 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4329 getControlRoot(), BeginLabel));
4332 // Check if target-independent constraints permit a tail call here.
4333 // Target-dependent constraints are checked within TLI.LowerCallTo.
4335 !isInTailCallPosition(CS.getInstruction(),
4336 CS.getAttributes().getRetAttributes(),
4340 std::pair<SDValue,SDValue> Result =
4341 TLI.LowerCallTo(getRoot(), RetTy,
4342 CS.paramHasAttr(0, Attribute::SExt),
4343 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4344 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
4345 CS.getCallingConv(),
4347 !CS.getInstruction()->use_empty(),
4348 Callee, Args, DAG, getCurDebugLoc());
4349 assert((isTailCall || Result.second.getNode()) &&
4350 "Non-null chain expected with non-tail call!");
4351 assert((Result.second.getNode() || !Result.first.getNode()) &&
4352 "Null value expected with tail call!");
4353 if (Result.first.getNode())
4354 setValue(CS.getInstruction(), Result.first);
4355 else if (!CanLowerReturn && Result.second.getNode()) {
4356 // The instruction result is the result of loading from the
4357 // hidden sret parameter.
4358 SmallVector<EVT, 1> PVTs;
4359 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
4361 ComputeValueVTs(TLI, PtrRetTy, PVTs);
4362 assert(PVTs.size() == 1 && "Pointers should fit in one register");
4363 EVT PtrVT = PVTs[0];
4364 unsigned NumValues = OutVTs.size();
4365 SmallVector<SDValue, 4> Values(NumValues);
4366 SmallVector<SDValue, 4> Chains(NumValues);
4368 for (unsigned i = 0; i < NumValues; ++i) {
4369 SDValue L = DAG.getLoad(OutVTs[i], getCurDebugLoc(), Result.second,
4370 DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, DemoteStackSlot,
4371 DAG.getConstant(Offsets[i], PtrVT)),
4372 NULL, Offsets[i], false, 1);
4374 Chains[i] = L.getValue(1);
4376 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
4377 MVT::Other, &Chains[0], NumValues);
4378 PendingLoads.push_back(Chain);
4380 setValue(CS.getInstruction(), DAG.getNode(ISD::MERGE_VALUES,
4381 getCurDebugLoc(), DAG.getVTList(&OutVTs[0], NumValues),
4382 &Values[0], NumValues));
4384 // As a special case, a null chain means that a tail call has
4385 // been emitted and the DAG root is already updated.
4386 if (Result.second.getNode())
4387 DAG.setRoot(Result.second);
4391 if (LandingPad && MMI) {
4392 // Insert a label at the end of the invoke call to mark the try range. This
4393 // can be used to detect deletion of the invoke via the MachineModuleInfo.
4394 EndLabel = MMI->NextLabelID();
4395 DAG.setRoot(DAG.getLabel(ISD::EH_LABEL, getCurDebugLoc(),
4396 getRoot(), EndLabel));
4398 // Inform MachineModuleInfo of range.
4399 MMI->addInvoke(LandingPad, BeginLabel, EndLabel);
4404 void SelectionDAGBuilder::visitCall(CallInst &I) {
4405 const char *RenameFn = 0;
4406 if (Function *F = I.getCalledFunction()) {
4407 if (F->isDeclaration()) {
4408 const TargetIntrinsicInfo *II = TLI.getTargetMachine().getIntrinsicInfo();
4410 if (unsigned IID = II->getIntrinsicID(F)) {
4411 RenameFn = visitIntrinsicCall(I, IID);
4416 if (unsigned IID = F->getIntrinsicID()) {
4417 RenameFn = visitIntrinsicCall(I, IID);
4423 // Check for well-known libc/libm calls. If the function is internal, it
4424 // can't be a library call.
4425 if (!F->hasLocalLinkage() && F->hasName()) {
4426 StringRef Name = F->getName();
4427 if (Name == "copysign" || Name == "copysignf") {
4428 if (I.getNumOperands() == 3 && // Basic sanity checks.
4429 I.getOperand(1)->getType()->isFloatingPoint() &&
4430 I.getType() == I.getOperand(1)->getType() &&
4431 I.getType() == I.getOperand(2)->getType()) {
4432 SDValue LHS = getValue(I.getOperand(1));
4433 SDValue RHS = getValue(I.getOperand(2));
4434 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
4435 LHS.getValueType(), LHS, RHS));
4438 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
4439 if (I.getNumOperands() == 2 && // Basic sanity checks.
4440 I.getOperand(1)->getType()->isFloatingPoint() &&
4441 I.getType() == I.getOperand(1)->getType()) {
4442 SDValue Tmp = getValue(I.getOperand(1));
4443 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
4444 Tmp.getValueType(), Tmp));
4447 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
4448 if (I.getNumOperands() == 2 && // Basic sanity checks.
4449 I.getOperand(1)->getType()->isFloatingPoint() &&
4450 I.getType() == I.getOperand(1)->getType() &&
4451 I.onlyReadsMemory()) {
4452 SDValue Tmp = getValue(I.getOperand(1));
4453 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
4454 Tmp.getValueType(), Tmp));
4457 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
4458 if (I.getNumOperands() == 2 && // Basic sanity checks.
4459 I.getOperand(1)->getType()->isFloatingPoint() &&
4460 I.getType() == I.getOperand(1)->getType() &&
4461 I.onlyReadsMemory()) {
4462 SDValue Tmp = getValue(I.getOperand(1));
4463 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
4464 Tmp.getValueType(), Tmp));
4467 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
4468 if (I.getNumOperands() == 2 && // Basic sanity checks.
4469 I.getOperand(1)->getType()->isFloatingPoint() &&
4470 I.getType() == I.getOperand(1)->getType() &&
4471 I.onlyReadsMemory()) {
4472 SDValue Tmp = getValue(I.getOperand(1));
4473 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
4474 Tmp.getValueType(), Tmp));
4479 } else if (isa<InlineAsm>(I.getOperand(0))) {
4486 Callee = getValue(I.getOperand(0));
4488 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
4490 // Check if we can potentially perform a tail call. More detailed
4491 // checking is be done within LowerCallTo, after more information
4492 // about the call is known.
4493 bool isTailCall = PerformTailCallOpt && I.isTailCall();
4495 LowerCallTo(&I, Callee, isTailCall);
4499 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
4500 /// this value and returns the result as a ValueVT value. This uses
4501 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4502 /// If the Flag pointer is NULL, no flag is used.
4503 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG, DebugLoc dl,
4505 SDValue *Flag) const {
4506 // Assemble the legal parts into the final values.
4507 SmallVector<SDValue, 4> Values(ValueVTs.size());
4508 SmallVector<SDValue, 8> Parts;
4509 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4510 // Copy the legal parts from the registers.
4511 EVT ValueVT = ValueVTs[Value];
4512 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
4513 EVT RegisterVT = RegVTs[Value];
4515 Parts.resize(NumRegs);
4516 for (unsigned i = 0; i != NumRegs; ++i) {
4519 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
4521 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
4522 *Flag = P.getValue(2);
4524 Chain = P.getValue(1);
4526 // If the source register was virtual and if we know something about it,
4527 // add an assert node.
4528 if (TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) &&
4529 RegisterVT.isInteger() && !RegisterVT.isVector()) {
4530 unsigned SlotNo = Regs[Part+i]-TargetRegisterInfo::FirstVirtualRegister;
4531 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
4532 if (FLI.LiveOutRegInfo.size() > SlotNo) {
4533 FunctionLoweringInfo::LiveOutInfo &LOI = FLI.LiveOutRegInfo[SlotNo];
4535 unsigned RegSize = RegisterVT.getSizeInBits();
4536 unsigned NumSignBits = LOI.NumSignBits;
4537 unsigned NumZeroBits = LOI.KnownZero.countLeadingOnes();
4539 // FIXME: We capture more information than the dag can represent. For
4540 // now, just use the tightest assertzext/assertsext possible.
4542 EVT FromVT(MVT::Other);
4543 if (NumSignBits == RegSize)
4544 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
4545 else if (NumZeroBits >= RegSize-1)
4546 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
4547 else if (NumSignBits > RegSize-8)
4548 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
4549 else if (NumZeroBits >= RegSize-8)
4550 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
4551 else if (NumSignBits > RegSize-16)
4552 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
4553 else if (NumZeroBits >= RegSize-16)
4554 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
4555 else if (NumSignBits > RegSize-32)
4556 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
4557 else if (NumZeroBits >= RegSize-32)
4558 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
4560 if (FromVT != MVT::Other) {
4561 P = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
4562 RegisterVT, P, DAG.getValueType(FromVT));
4571 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
4572 NumRegs, RegisterVT, ValueVT);
4577 return DAG.getNode(ISD::MERGE_VALUES, dl,
4578 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
4579 &Values[0], ValueVTs.size());
4582 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
4583 /// specified value into the registers specified by this object. This uses
4584 /// Chain/Flag as the input and updates them for the output Chain/Flag.
4585 /// If the Flag pointer is NULL, no flag is used.
4586 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
4587 SDValue &Chain, SDValue *Flag) const {
4588 // Get the list of the values's legal parts.
4589 unsigned NumRegs = Regs.size();
4590 SmallVector<SDValue, 8> Parts(NumRegs);
4591 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
4592 EVT ValueVT = ValueVTs[Value];
4593 unsigned NumParts = TLI->getNumRegisters(*DAG.getContext(), ValueVT);
4594 EVT RegisterVT = RegVTs[Value];
4596 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
4597 &Parts[Part], NumParts, RegisterVT);
4601 // Copy the parts into the registers.
4602 SmallVector<SDValue, 8> Chains(NumRegs);
4603 for (unsigned i = 0; i != NumRegs; ++i) {
4606 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
4608 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
4609 *Flag = Part.getValue(1);
4611 Chains[i] = Part.getValue(0);
4614 if (NumRegs == 1 || Flag)
4615 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
4616 // flagged to it. That is the CopyToReg nodes and the user are considered
4617 // a single scheduling unit. If we create a TokenFactor and return it as
4618 // chain, then the TokenFactor is both a predecessor (operand) of the
4619 // user as well as a successor (the TF operands are flagged to the user).
4620 // c1, f1 = CopyToReg
4621 // c2, f2 = CopyToReg
4622 // c3 = TokenFactor c1, c2
4625 Chain = Chains[NumRegs-1];
4627 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
4630 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
4631 /// operand list. This adds the code marker and includes the number of
4632 /// values added into it.
4633 void RegsForValue::AddInlineAsmOperands(unsigned Code,
4634 bool HasMatching,unsigned MatchingIdx,
4636 std::vector<SDValue> &Ops) const {
4637 EVT IntPtrTy = DAG.getTargetLoweringInfo().getPointerTy();
4638 assert(Regs.size() < (1 << 13) && "Too many inline asm outputs!");
4639 unsigned Flag = Code | (Regs.size() << 3);
4641 Flag |= 0x80000000 | (MatchingIdx << 16);
4642 Ops.push_back(DAG.getTargetConstant(Flag, IntPtrTy));
4643 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
4644 unsigned NumRegs = TLI->getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
4645 EVT RegisterVT = RegVTs[Value];
4646 for (unsigned i = 0; i != NumRegs; ++i) {
4647 assert(Reg < Regs.size() && "Mismatch in # registers expected");
4648 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
4653 /// isAllocatableRegister - If the specified register is safe to allocate,
4654 /// i.e. it isn't a stack pointer or some other special register, return the
4655 /// register class for the register. Otherwise, return null.
4656 static const TargetRegisterClass *
4657 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
4658 const TargetLowering &TLI,
4659 const TargetRegisterInfo *TRI) {
4660 EVT FoundVT = MVT::Other;
4661 const TargetRegisterClass *FoundRC = 0;
4662 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
4663 E = TRI->regclass_end(); RCI != E; ++RCI) {
4664 EVT ThisVT = MVT::Other;
4666 const TargetRegisterClass *RC = *RCI;
4667 // If none of the the value types for this register class are valid, we
4668 // can't use it. For example, 64-bit reg classes on 32-bit targets.
4669 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
4671 if (TLI.isTypeLegal(*I)) {
4672 // If we have already found this register in a different register class,
4673 // choose the one with the largest VT specified. For example, on
4674 // PowerPC, we favor f64 register classes over f32.
4675 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
4682 if (ThisVT == MVT::Other) continue;
4684 // NOTE: This isn't ideal. In particular, this might allocate the
4685 // frame pointer in functions that need it (due to them not being taken
4686 // out of allocation, because a variable sized allocation hasn't been seen
4687 // yet). This is a slight code pessimization, but should still work.
4688 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
4689 E = RC->allocation_order_end(MF); I != E; ++I)
4691 // We found a matching register class. Keep looking at others in case
4692 // we find one with larger registers that this physreg is also in.
4703 /// AsmOperandInfo - This contains information for each constraint that we are
4705 class VISIBILITY_HIDDEN SDISelAsmOperandInfo :
4706 public TargetLowering::AsmOperandInfo {
4708 /// CallOperand - If this is the result output operand or a clobber
4709 /// this is null, otherwise it is the incoming operand to the CallInst.
4710 /// This gets modified as the asm is processed.
4711 SDValue CallOperand;
4713 /// AssignedRegs - If this is a register or register class operand, this
4714 /// contains the set of register corresponding to the operand.
4715 RegsForValue AssignedRegs;
4717 explicit SDISelAsmOperandInfo(const InlineAsm::ConstraintInfo &info)
4718 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
4721 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
4722 /// busy in OutputRegs/InputRegs.
4723 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
4724 std::set<unsigned> &OutputRegs,
4725 std::set<unsigned> &InputRegs,
4726 const TargetRegisterInfo &TRI) const {
4728 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4729 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
4732 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
4733 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
4737 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
4738 /// corresponds to. If there is no Value* for this operand, it returns
4740 EVT getCallOperandValEVT(LLVMContext &Context,
4741 const TargetLowering &TLI,
4742 const TargetData *TD) const {
4743 if (CallOperandVal == 0) return MVT::Other;
4745 if (isa<BasicBlock>(CallOperandVal))
4746 return TLI.getPointerTy();
4748 const llvm::Type *OpTy = CallOperandVal->getType();
4750 // If this is an indirect operand, the operand is a pointer to the
4753 OpTy = cast<PointerType>(OpTy)->getElementType();
4755 // If OpTy is not a single value, it may be a struct/union that we
4756 // can tile with integers.
4757 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
4758 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
4767 OpTy = IntegerType::get(Context, BitSize);
4772 return TLI.getValueType(OpTy, true);
4776 /// MarkRegAndAliases - Mark the specified register and all aliases in the
4778 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
4779 const TargetRegisterInfo &TRI) {
4780 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
4782 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
4783 for (; *Aliases; ++Aliases)
4784 Regs.insert(*Aliases);
4787 } // end llvm namespace.
4790 /// GetRegistersForValue - Assign registers (virtual or physical) for the
4791 /// specified operand. We prefer to assign virtual registers, to allow the
4792 /// register allocator to handle the assignment process. However, if the asm
4793 /// uses features that we can't model on machineinstrs, we have SDISel do the
4794 /// allocation. This produces generally horrible, but correct, code.
4796 /// OpInfo describes the operand.
4797 /// Input and OutputRegs are the set of already allocated physical registers.
4799 void SelectionDAGBuilder::
4800 GetRegistersForValue(SDISelAsmOperandInfo &OpInfo,
4801 std::set<unsigned> &OutputRegs,
4802 std::set<unsigned> &InputRegs) {
4803 LLVMContext &Context = FuncInfo.Fn->getContext();
4805 // Compute whether this value requires an input register, an output register,
4807 bool isOutReg = false;
4808 bool isInReg = false;
4809 switch (OpInfo.Type) {
4810 case InlineAsm::isOutput:
4813 // If there is an input constraint that matches this, we need to reserve
4814 // the input register so no other inputs allocate to it.
4815 isInReg = OpInfo.hasMatchingInput();
4817 case InlineAsm::isInput:
4821 case InlineAsm::isClobber:
4828 MachineFunction &MF = DAG.getMachineFunction();
4829 SmallVector<unsigned, 4> Regs;
4831 // If this is a constraint for a single physreg, or a constraint for a
4832 // register class, find it.
4833 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
4834 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
4835 OpInfo.ConstraintVT);
4837 unsigned NumRegs = 1;
4838 if (OpInfo.ConstraintVT != MVT::Other) {
4839 // If this is a FP input in an integer register (or visa versa) insert a bit
4840 // cast of the input value. More generally, handle any case where the input
4841 // value disagrees with the register class we plan to stick this in.
4842 if (OpInfo.Type == InlineAsm::isInput &&
4843 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
4844 // Try to convert to the first EVT that the reg class contains. If the
4845 // types are identical size, use a bitcast to convert (e.g. two differing
4847 EVT RegVT = *PhysReg.second->vt_begin();
4848 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
4849 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
4850 RegVT, OpInfo.CallOperand);
4851 OpInfo.ConstraintVT = RegVT;
4852 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
4853 // If the input is a FP value and we want it in FP registers, do a
4854 // bitcast to the corresponding integer type. This turns an f64 value
4855 // into i64, which can be passed with two i32 values on a 32-bit
4857 RegVT = EVT::getIntegerVT(Context,
4858 OpInfo.ConstraintVT.getSizeInBits());
4859 OpInfo.CallOperand = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
4860 RegVT, OpInfo.CallOperand);
4861 OpInfo.ConstraintVT = RegVT;
4865 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
4869 EVT ValueVT = OpInfo.ConstraintVT;
4871 // If this is a constraint for a specific physical register, like {r17},
4873 if (unsigned AssignedReg = PhysReg.first) {
4874 const TargetRegisterClass *RC = PhysReg.second;
4875 if (OpInfo.ConstraintVT == MVT::Other)
4876 ValueVT = *RC->vt_begin();
4878 // Get the actual register value type. This is important, because the user
4879 // may have asked for (e.g.) the AX register in i32 type. We need to
4880 // remember that AX is actually i16 to get the right extension.
4881 RegVT = *RC->vt_begin();
4883 // This is a explicit reference to a physical register.
4884 Regs.push_back(AssignedReg);
4886 // If this is an expanded reference, add the rest of the regs to Regs.
4888 TargetRegisterClass::iterator I = RC->begin();
4889 for (; *I != AssignedReg; ++I)
4890 assert(I != RC->end() && "Didn't find reg!");
4892 // Already added the first reg.
4894 for (; NumRegs; --NumRegs, ++I) {
4895 assert(I != RC->end() && "Ran out of registers to allocate!");
4899 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4900 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4901 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4905 // Otherwise, if this was a reference to an LLVM register class, create vregs
4906 // for this reference.
4907 if (const TargetRegisterClass *RC = PhysReg.second) {
4908 RegVT = *RC->vt_begin();
4909 if (OpInfo.ConstraintVT == MVT::Other)
4912 // Create the appropriate number of virtual registers.
4913 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4914 for (; NumRegs; --NumRegs)
4915 Regs.push_back(RegInfo.createVirtualRegister(RC));
4917 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, RegVT, ValueVT);
4921 // This is a reference to a register class that doesn't directly correspond
4922 // to an LLVM register class. Allocate NumRegs consecutive, available,
4923 // registers from the class.
4924 std::vector<unsigned> RegClassRegs
4925 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
4926 OpInfo.ConstraintVT);
4928 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4929 unsigned NumAllocated = 0;
4930 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
4931 unsigned Reg = RegClassRegs[i];
4932 // See if this register is available.
4933 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
4934 (isInReg && InputRegs.count(Reg))) { // Already used.
4935 // Make sure we find consecutive registers.
4940 // Check to see if this register is allocatable (i.e. don't give out the
4942 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
4943 if (!RC) { // Couldn't allocate this register.
4944 // Reset NumAllocated to make sure we return consecutive registers.
4949 // Okay, this register is good, we can use it.
4952 // If we allocated enough consecutive registers, succeed.
4953 if (NumAllocated == NumRegs) {
4954 unsigned RegStart = (i-NumAllocated)+1;
4955 unsigned RegEnd = i+1;
4956 // Mark all of the allocated registers used.
4957 for (unsigned i = RegStart; i != RegEnd; ++i)
4958 Regs.push_back(RegClassRegs[i]);
4960 OpInfo.AssignedRegs = RegsForValue(TLI, Regs, *RC->vt_begin(),
4961 OpInfo.ConstraintVT);
4962 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
4967 // Otherwise, we couldn't allocate enough registers for this.
4970 /// hasInlineAsmMemConstraint - Return true if the inline asm instruction being
4971 /// processed uses a memory 'm' constraint.
4973 hasInlineAsmMemConstraint(std::vector<InlineAsm::ConstraintInfo> &CInfos,
4974 const TargetLowering &TLI) {
4975 for (unsigned i = 0, e = CInfos.size(); i != e; ++i) {
4976 InlineAsm::ConstraintInfo &CI = CInfos[i];
4977 for (unsigned j = 0, ee = CI.Codes.size(); j != ee; ++j) {
4978 TargetLowering::ConstraintType CType = TLI.getConstraintType(CI.Codes[j]);
4979 if (CType == TargetLowering::C_Memory)
4983 // Indirect operand accesses access memory.
4991 /// visitInlineAsm - Handle a call to an InlineAsm object.
4993 void SelectionDAGBuilder::visitInlineAsm(CallSite CS) {
4994 InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
4996 /// ConstraintOperands - Information about all of the constraints.
4997 std::vector<SDISelAsmOperandInfo> ConstraintOperands;
4999 std::set<unsigned> OutputRegs, InputRegs;
5001 // Do a prepass over the constraints, canonicalizing them, and building up the
5002 // ConstraintOperands list.
5003 std::vector<InlineAsm::ConstraintInfo>
5004 ConstraintInfos = IA->ParseConstraints();
5006 bool hasMemory = hasInlineAsmMemConstraint(ConstraintInfos, TLI);
5008 SDValue Chain, Flag;
5010 // We won't need to flush pending loads if this asm doesn't touch
5011 // memory and is nonvolatile.
5012 if (hasMemory || IA->hasSideEffects())
5015 Chain = DAG.getRoot();
5017 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5018 unsigned ResNo = 0; // ResNo - The result number of the next output.
5019 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5020 ConstraintOperands.push_back(SDISelAsmOperandInfo(ConstraintInfos[i]));
5021 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5023 EVT OpVT = MVT::Other;
5025 // Compute the value type for each operand.
5026 switch (OpInfo.Type) {
5027 case InlineAsm::isOutput:
5028 // Indirect outputs just consume an argument.
5029 if (OpInfo.isIndirect) {
5030 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5034 // The return value of the call is this value. As such, there is no
5035 // corresponding argument.
5036 assert(CS.getType() != Type::getVoidTy(*DAG.getContext()) &&
5038 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5039 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5041 assert(ResNo == 0 && "Asm only has one result!");
5042 OpVT = TLI.getValueType(CS.getType());
5046 case InlineAsm::isInput:
5047 OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
5049 case InlineAsm::isClobber:
5054 // If this is an input or an indirect output, process the call argument.
5055 // BasicBlocks are labels, currently appearing only in asm's.
5056 if (OpInfo.CallOperandVal) {
5057 // Strip bitcasts, if any. This mostly comes up for functions.
5058 OpInfo.CallOperandVal = OpInfo.CallOperandVal->stripPointerCasts();
5060 if (BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5061 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5063 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5066 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
5069 OpInfo.ConstraintVT = OpVT;
5072 // Second pass over the constraints: compute which constraint option to use
5073 // and assign registers to constraints that want a specific physreg.
5074 for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
5075 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5077 // If this is an output operand with a matching input operand, look up the
5078 // matching input. If their types mismatch, e.g. one is an integer, the
5079 // other is floating point, or their sizes are different, flag it as an
5081 if (OpInfo.hasMatchingInput()) {
5082 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5083 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5084 if ((OpInfo.ConstraintVT.isInteger() !=
5085 Input.ConstraintVT.isInteger()) ||
5086 (OpInfo.ConstraintVT.getSizeInBits() !=
5087 Input.ConstraintVT.getSizeInBits())) {
5088 llvm_report_error("Unsupported asm: input constraint"
5089 " with a matching output constraint of incompatible"
5092 Input.ConstraintVT = OpInfo.ConstraintVT;
5096 // Compute the constraint code and ConstraintType to use.
5097 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, hasMemory, &DAG);
5099 // If this is a memory input, and if the operand is not indirect, do what we
5100 // need to to provide an address for the memory input.
5101 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5102 !OpInfo.isIndirect) {
5103 assert(OpInfo.Type == InlineAsm::isInput &&
5104 "Can only indirectify direct input operands!");
5106 // Memory operands really want the address of the value. If we don't have
5107 // an indirect input, put it in the constpool if we can, otherwise spill
5108 // it to a stack slot.
5110 // If the operand is a float, integer, or vector constant, spill to a
5111 // constant pool entry to get its address.
5112 Value *OpVal = OpInfo.CallOperandVal;
5113 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5114 isa<ConstantVector>(OpVal)) {
5115 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5116 TLI.getPointerTy());
5118 // Otherwise, create a stack slot and emit a store to it before the
5120 const Type *Ty = OpVal->getType();
5121 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
5122 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5123 MachineFunction &MF = DAG.getMachineFunction();
5124 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5125 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5126 Chain = DAG.getStore(Chain, getCurDebugLoc(),
5127 OpInfo.CallOperand, StackSlot, NULL, 0);
5128 OpInfo.CallOperand = StackSlot;
5131 // There is no longer a Value* corresponding to this operand.
5132 OpInfo.CallOperandVal = 0;
5133 // It is now an indirect operand.
5134 OpInfo.isIndirect = true;
5137 // If this constraint is for a specific register, allocate it before
5139 if (OpInfo.ConstraintType == TargetLowering::C_Register)
5140 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5142 ConstraintInfos.clear();
5145 // Second pass - Loop over all of the operands, assigning virtual or physregs
5146 // to register class operands.
5147 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5148 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5150 // C_Register operands have already been allocated, Other/Memory don't need
5152 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
5153 GetRegistersForValue(OpInfo, OutputRegs, InputRegs);
5156 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5157 std::vector<SDValue> AsmNodeOperands;
5158 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5159 AsmNodeOperands.push_back(
5160 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(), MVT::Other));
5163 // Loop over all of the inputs, copying the operand values into the
5164 // appropriate registers and processing the output regs.
5165 RegsForValue RetValRegs;
5167 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5168 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
5170 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5171 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5173 switch (OpInfo.Type) {
5174 case InlineAsm::isOutput: {
5175 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5176 OpInfo.ConstraintType != TargetLowering::C_Register) {
5177 // Memory output, or 'other' output (e.g. 'X' constraint).
5178 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5180 // Add information to the INLINEASM node to know about this output.
5181 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5182 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5183 TLI.getPointerTy()));
5184 AsmNodeOperands.push_back(OpInfo.CallOperand);
5188 // Otherwise, this is a register or register class output.
5190 // Copy the output from the appropriate register. Find a register that
5192 if (OpInfo.AssignedRegs.Regs.empty()) {
5193 llvm_report_error("Couldn't allocate output reg for"
5194 " constraint '" + OpInfo.ConstraintCode + "'!");
5197 // If this is an indirect operand, store through the pointer after the
5199 if (OpInfo.isIndirect) {
5200 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5201 OpInfo.CallOperandVal));
5203 // This is the result value of the call.
5204 assert(CS.getType() != Type::getVoidTy(*DAG.getContext()) &&
5206 // Concatenate this output onto the outputs list.
5207 RetValRegs.append(OpInfo.AssignedRegs);
5210 // Add information to the INLINEASM node to know that this register is
5212 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5213 6 /* EARLYCLOBBER REGDEF */ :
5217 DAG, AsmNodeOperands);
5220 case InlineAsm::isInput: {
5221 SDValue InOperandVal = OpInfo.CallOperand;
5223 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
5224 // If this is required to match an output register we have already set,
5225 // just use its register.
5226 unsigned OperandNo = OpInfo.getMatchedOperand();
5228 // Scan until we find the definition we already emitted of this operand.
5229 // When we find it, create a RegsForValue operand.
5230 unsigned CurOp = 2; // The first operand.
5231 for (; OperandNo; --OperandNo) {
5232 // Advance to the next operand.
5234 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5235 assert(((OpFlag & 7) == 2 /*REGDEF*/ ||
5236 (OpFlag & 7) == 6 /*EARLYCLOBBER REGDEF*/ ||
5237 (OpFlag & 7) == 4 /*MEM*/) &&
5238 "Skipped past definitions?");
5239 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
5243 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5244 if ((OpFlag & 7) == 2 /*REGDEF*/
5245 || (OpFlag & 7) == 6 /* EARLYCLOBBER REGDEF */) {
5246 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
5247 if (OpInfo.isIndirect) {
5248 llvm_report_error("Don't know how to handle tied indirect "
5249 "register inputs yet!");
5251 RegsForValue MatchedRegs;
5252 MatchedRegs.TLI = &TLI;
5253 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5254 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5255 MatchedRegs.RegVTs.push_back(RegVT);
5256 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
5257 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
5260 push_back(RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
5262 // Use the produced MatchedRegs object to
5263 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5265 MatchedRegs.AddInlineAsmOperands(1 /*REGUSE*/,
5266 true, OpInfo.getMatchedOperand(),
5267 DAG, AsmNodeOperands);
5270 assert(((OpFlag & 7) == 4) && "Unknown matching constraint!");
5271 assert((InlineAsm::getNumOperandRegisters(OpFlag)) == 1 &&
5272 "Unexpected number of operands");
5273 // Add information to the INLINEASM node to know about this input.
5274 // See InlineAsm.h isUseOperandTiedToDef.
5275 OpFlag |= 0x80000000 | (OpInfo.getMatchedOperand() << 16);
5276 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
5277 TLI.getPointerTy()));
5278 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5283 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5284 assert(!OpInfo.isIndirect &&
5285 "Don't know how to handle indirect other inputs yet!");
5287 std::vector<SDValue> Ops;
5288 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode[0],
5289 hasMemory, Ops, DAG);
5291 llvm_report_error("Invalid operand for inline asm"
5292 " constraint '" + OpInfo.ConstraintCode + "'!");
5295 // Add information to the INLINEASM node to know about this input.
5296 unsigned ResOpType = 3 /*IMM*/ | (Ops.size() << 3);
5297 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5298 TLI.getPointerTy()));
5299 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5301 } else if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5302 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
5303 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
5304 "Memory operands expect pointer values");
5306 // Add information to the INLINEASM node to know about this input.
5307 unsigned ResOpType = 4/*MEM*/ | (1<<3);
5308 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5309 TLI.getPointerTy()));
5310 AsmNodeOperands.push_back(InOperandVal);
5314 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
5315 OpInfo.ConstraintType == TargetLowering::C_Register) &&
5316 "Unknown constraint type!");
5317 assert(!OpInfo.isIndirect &&
5318 "Don't know how to handle indirect register inputs yet!");
5320 // Copy the input into the appropriate registers.
5321 if (OpInfo.AssignedRegs.Regs.empty()) {
5322 llvm_report_error("Couldn't allocate input reg for"
5323 " constraint '"+ OpInfo.ConstraintCode +"'!");
5326 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5329 OpInfo.AssignedRegs.AddInlineAsmOperands(1/*REGUSE*/, false, 0,
5330 DAG, AsmNodeOperands);
5333 case InlineAsm::isClobber: {
5334 // Add the clobbered value to the operand list, so that the register
5335 // allocator is aware that the physreg got clobbered.
5336 if (!OpInfo.AssignedRegs.Regs.empty())
5337 OpInfo.AssignedRegs.AddInlineAsmOperands(6 /* EARLYCLOBBER REGDEF */,
5338 false, 0, DAG,AsmNodeOperands);
5344 // Finish up input operands.
5345 AsmNodeOperands[0] = Chain;
5346 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
5348 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
5349 DAG.getVTList(MVT::Other, MVT::Flag),
5350 &AsmNodeOperands[0], AsmNodeOperands.size());
5351 Flag = Chain.getValue(1);
5353 // If this asm returns a register value, copy the result from that register
5354 // and set it as the value of the call.
5355 if (!RetValRegs.Regs.empty()) {
5356 SDValue Val = RetValRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5359 // FIXME: Why don't we do this for inline asms with MRVs?
5360 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
5361 EVT ResultType = TLI.getValueType(CS.getType());
5363 // If any of the results of the inline asm is a vector, it may have the
5364 // wrong width/num elts. This can happen for register classes that can
5365 // contain multiple different value types. The preg or vreg allocated may
5366 // not have the same VT as was expected. Convert it to the right type
5367 // with bit_convert.
5368 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
5369 Val = DAG.getNode(ISD::BIT_CONVERT, getCurDebugLoc(),
5372 } else if (ResultType != Val.getValueType() &&
5373 ResultType.isInteger() && Val.getValueType().isInteger()) {
5374 // If a result value was tied to an input value, the computed result may
5375 // have a wider width than the expected result. Extract the relevant
5377 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
5380 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
5383 setValue(CS.getInstruction(), Val);
5384 // Don't need to use this as a chain in this case.
5385 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
5389 std::vector<std::pair<SDValue, Value*> > StoresToEmit;
5391 // Process indirect outputs, first output all of the flagged copies out of
5393 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
5394 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
5395 Value *Ptr = IndirectStoresToEmit[i].second;
5396 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, getCurDebugLoc(),
5398 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
5402 // Emit the non-flagged stores from the physregs.
5403 SmallVector<SDValue, 8> OutChains;
5404 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i)
5405 OutChains.push_back(DAG.getStore(Chain, getCurDebugLoc(),
5406 StoresToEmit[i].first,
5407 getValue(StoresToEmit[i].second),
5408 StoresToEmit[i].second, 0));
5409 if (!OutChains.empty())
5410 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
5411 &OutChains[0], OutChains.size());
5415 void SelectionDAGBuilder::visitVAStart(CallInst &I) {
5416 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
5417 MVT::Other, getRoot(),
5418 getValue(I.getOperand(1)),
5419 DAG.getSrcValue(I.getOperand(1))));
5422 void SelectionDAGBuilder::visitVAArg(VAArgInst &I) {
5423 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
5424 getRoot(), getValue(I.getOperand(0)),
5425 DAG.getSrcValue(I.getOperand(0)));
5427 DAG.setRoot(V.getValue(1));
5430 void SelectionDAGBuilder::visitVAEnd(CallInst &I) {
5431 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
5432 MVT::Other, getRoot(),
5433 getValue(I.getOperand(1)),
5434 DAG.getSrcValue(I.getOperand(1))));
5437 void SelectionDAGBuilder::visitVACopy(CallInst &I) {
5438 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
5439 MVT::Other, getRoot(),
5440 getValue(I.getOperand(1)),
5441 getValue(I.getOperand(2)),
5442 DAG.getSrcValue(I.getOperand(1)),
5443 DAG.getSrcValue(I.getOperand(2))));
5446 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
5447 /// implementation, which just calls LowerCall.
5448 /// FIXME: When all targets are
5449 /// migrated to using LowerCall, this hook should be integrated into SDISel.
5450 std::pair<SDValue, SDValue>
5451 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
5452 bool RetSExt, bool RetZExt, bool isVarArg,
5453 bool isInreg, unsigned NumFixedArgs,
5454 CallingConv::ID CallConv, bool isTailCall,
5455 bool isReturnValueUsed,
5457 ArgListTy &Args, SelectionDAG &DAG, DebugLoc dl) {
5459 assert((!isTailCall || PerformTailCallOpt) &&
5460 "isTailCall set when tail-call optimizations are disabled!");
5462 // Handle all of the outgoing arguments.
5463 SmallVector<ISD::OutputArg, 32> Outs;
5464 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5465 SmallVector<EVT, 4> ValueVTs;
5466 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
5467 for (unsigned Value = 0, NumValues = ValueVTs.size();
5468 Value != NumValues; ++Value) {
5469 EVT VT = ValueVTs[Value];
5470 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
5471 SDValue Op = SDValue(Args[i].Node.getNode(),
5472 Args[i].Node.getResNo() + Value);
5473 ISD::ArgFlagsTy Flags;
5474 unsigned OriginalAlignment =
5475 getTargetData()->getABITypeAlignment(ArgTy);
5481 if (Args[i].isInReg)
5485 if (Args[i].isByVal) {
5487 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
5488 const Type *ElementTy = Ty->getElementType();
5489 unsigned FrameAlign = getByValTypeAlignment(ElementTy);
5490 unsigned FrameSize = getTargetData()->getTypeAllocSize(ElementTy);
5491 // For ByVal, alignment should come from FE. BE will guess if this
5492 // info is not there but there are cases it cannot get right.
5493 if (Args[i].Alignment)
5494 FrameAlign = Args[i].Alignment;
5495 Flags.setByValAlign(FrameAlign);
5496 Flags.setByValSize(FrameSize);
5500 Flags.setOrigAlign(OriginalAlignment);
5502 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
5503 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
5504 SmallVector<SDValue, 4> Parts(NumParts);
5505 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
5508 ExtendKind = ISD::SIGN_EXTEND;
5509 else if (Args[i].isZExt)
5510 ExtendKind = ISD::ZERO_EXTEND;
5512 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts, PartVT, ExtendKind);
5514 for (unsigned j = 0; j != NumParts; ++j) {
5515 // if it isn't first piece, alignment must be 1
5516 ISD::OutputArg MyFlags(Flags, Parts[j], i < NumFixedArgs);
5517 if (NumParts > 1 && j == 0)
5518 MyFlags.Flags.setSplit();
5520 MyFlags.Flags.setOrigAlign(1);
5522 Outs.push_back(MyFlags);
5527 // Handle the incoming return values from the call.
5528 SmallVector<ISD::InputArg, 32> Ins;
5529 SmallVector<EVT, 4> RetTys;
5530 ComputeValueVTs(*this, RetTy, RetTys);
5531 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5533 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5534 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
5535 for (unsigned i = 0; i != NumRegs; ++i) {
5536 ISD::InputArg MyFlags;
5537 MyFlags.VT = RegisterVT;
5538 MyFlags.Used = isReturnValueUsed;
5540 MyFlags.Flags.setSExt();
5542 MyFlags.Flags.setZExt();
5544 MyFlags.Flags.setInReg();
5545 Ins.push_back(MyFlags);
5549 // Check if target-dependent constraints permit a tail call here.
5550 // Target-independent constraints should be checked by the caller.
5552 !IsEligibleForTailCallOptimization(Callee, CallConv, isVarArg, Ins, DAG))
5555 SmallVector<SDValue, 4> InVals;
5556 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
5557 Outs, Ins, dl, DAG, InVals);
5559 // Verify that the target's LowerCall behaved as expected.
5560 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
5561 "LowerCall didn't return a valid chain!");
5562 assert((!isTailCall || InVals.empty()) &&
5563 "LowerCall emitted a return value for a tail call!");
5564 assert((isTailCall || InVals.size() == Ins.size()) &&
5565 "LowerCall didn't emit the correct number of values!");
5566 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5567 assert(InVals[i].getNode() &&
5568 "LowerCall emitted a null value!");
5569 assert(Ins[i].VT == InVals[i].getValueType() &&
5570 "LowerCall emitted a value with the wrong type!");
5573 // For a tail call, the return value is merely live-out and there aren't
5574 // any nodes in the DAG representing it. Return a special value to
5575 // indicate that a tail call has been emitted and no more Instructions
5576 // should be processed in the current block.
5579 return std::make_pair(SDValue(), SDValue());
5582 // Collect the legal value parts into potentially illegal values
5583 // that correspond to the original function's return values.
5584 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5586 AssertOp = ISD::AssertSext;
5588 AssertOp = ISD::AssertZext;
5589 SmallVector<SDValue, 4> ReturnValues;
5590 unsigned CurReg = 0;
5591 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5593 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
5594 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
5596 SDValue ReturnValue =
5597 getCopyFromParts(DAG, dl, &InVals[CurReg], NumRegs, RegisterVT, VT,
5599 ReturnValues.push_back(ReturnValue);
5603 // For a function returning void, there is no return value. We can't create
5604 // such a node, so we just return a null return value in that case. In
5605 // that case, nothing will actualy look at the value.
5606 if (ReturnValues.empty())
5607 return std::make_pair(SDValue(), Chain);
5609 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
5610 DAG.getVTList(&RetTys[0], RetTys.size()),
5611 &ReturnValues[0], ReturnValues.size());
5613 return std::make_pair(Res, Chain);
5616 void TargetLowering::LowerOperationWrapper(SDNode *N,
5617 SmallVectorImpl<SDValue> &Results,
5618 SelectionDAG &DAG) {
5619 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
5621 Results.push_back(Res);
5624 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) {
5625 llvm_unreachable("LowerOperation not implemented for this target!");
5630 void SelectionDAGBuilder::CopyValueToVirtualRegister(Value *V, unsigned Reg) {
5631 SDValue Op = getValue(V);
5632 assert((Op.getOpcode() != ISD::CopyFromReg ||
5633 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
5634 "Copy from a reg to the same reg!");
5635 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
5637 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
5638 SDValue Chain = DAG.getEntryNode();
5639 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
5640 PendingExports.push_back(Chain);
5643 #include "llvm/CodeGen/SelectionDAGISel.h"
5645 void SelectionDAGISel::LowerArguments(BasicBlock *LLVMBB) {
5646 // If this is the entry block, emit arguments.
5647 Function &F = *LLVMBB->getParent();
5648 SelectionDAG &DAG = SDB->DAG;
5649 SDValue OldRoot = DAG.getRoot();
5650 DebugLoc dl = SDB->getCurDebugLoc();
5651 const TargetData *TD = TLI.getTargetData();
5652 SmallVector<ISD::InputArg, 16> Ins;
5654 // Check whether the function can return without sret-demotion.
5655 SmallVector<EVT, 4> OutVTs;
5656 SmallVector<ISD::ArgFlagsTy, 4> OutsFlags;
5657 getReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
5658 OutVTs, OutsFlags, TLI);
5659 FunctionLoweringInfo &FLI = DAG.getFunctionLoweringInfo();
5661 FLI.CanLowerReturn = TLI.CanLowerReturn(F.getCallingConv(), F.isVarArg(),
5662 OutVTs, OutsFlags, DAG);
5663 if (!FLI.CanLowerReturn) {
5664 // Put in an sret pointer parameter before all the other parameters.
5665 SmallVector<EVT, 1> ValueVTs;
5666 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5668 // NOTE: Assuming that a pointer will never break down to more than one VT
5670 ISD::ArgFlagsTy Flags;
5672 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), ValueVTs[0]);
5673 ISD::InputArg RetArg(Flags, RegisterVT, true);
5674 Ins.push_back(RetArg);
5677 // Set up the incoming argument description vector.
5679 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end();
5680 I != E; ++I, ++Idx) {
5681 SmallVector<EVT, 4> ValueVTs;
5682 ComputeValueVTs(TLI, I->getType(), ValueVTs);
5683 bool isArgValueUsed = !I->use_empty();
5684 for (unsigned Value = 0, NumValues = ValueVTs.size();
5685 Value != NumValues; ++Value) {
5686 EVT VT = ValueVTs[Value];
5687 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
5688 ISD::ArgFlagsTy Flags;
5689 unsigned OriginalAlignment =
5690 TD->getABITypeAlignment(ArgTy);
5692 if (F.paramHasAttr(Idx, Attribute::ZExt))
5694 if (F.paramHasAttr(Idx, Attribute::SExt))
5696 if (F.paramHasAttr(Idx, Attribute::InReg))
5698 if (F.paramHasAttr(Idx, Attribute::StructRet))
5700 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
5702 const PointerType *Ty = cast<PointerType>(I->getType());
5703 const Type *ElementTy = Ty->getElementType();
5704 unsigned FrameAlign = TLI.getByValTypeAlignment(ElementTy);
5705 unsigned FrameSize = TD->getTypeAllocSize(ElementTy);
5706 // For ByVal, alignment should be passed from FE. BE will guess if
5707 // this info is not there but there are cases it cannot get right.
5708 if (F.getParamAlignment(Idx))
5709 FrameAlign = F.getParamAlignment(Idx);
5710 Flags.setByValAlign(FrameAlign);
5711 Flags.setByValSize(FrameSize);
5713 if (F.paramHasAttr(Idx, Attribute::Nest))
5715 Flags.setOrigAlign(OriginalAlignment);
5717 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5718 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
5719 for (unsigned i = 0; i != NumRegs; ++i) {
5720 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
5721 if (NumRegs > 1 && i == 0)
5722 MyFlags.Flags.setSplit();
5723 // if it isn't first piece, alignment must be 1
5725 MyFlags.Flags.setOrigAlign(1);
5726 Ins.push_back(MyFlags);
5731 // Call the target to set up the argument values.
5732 SmallVector<SDValue, 8> InVals;
5733 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
5737 // Verify that the target's LowerFormalArguments behaved as expected.
5738 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
5739 "LowerFormalArguments didn't return a valid chain!");
5740 assert(InVals.size() == Ins.size() &&
5741 "LowerFormalArguments didn't emit the correct number of values!");
5742 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
5743 assert(InVals[i].getNode() &&
5744 "LowerFormalArguments emitted a null value!");
5745 assert(Ins[i].VT == InVals[i].getValueType() &&
5746 "LowerFormalArguments emitted a value with the wrong type!");
5749 // Update the DAG with the new chain value resulting from argument lowering.
5750 DAG.setRoot(NewRoot);
5752 // Set up the argument values.
5755 if (!FLI.CanLowerReturn) {
5756 // Create a virtual register for the sret pointer, and put in a copy
5757 // from the sret argument into it.
5758 SmallVector<EVT, 1> ValueVTs;
5759 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
5760 EVT VT = ValueVTs[0];
5761 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5762 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5763 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1, RegVT,
5766 MachineFunction& MF = SDB->DAG.getMachineFunction();
5767 MachineRegisterInfo& RegInfo = MF.getRegInfo();
5768 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
5769 FLI.DemoteRegister = SRetReg;
5770 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(), SRetReg, ArgValue);
5771 DAG.setRoot(NewRoot);
5773 // i indexes lowered arguments. Bump it past the hidden sret argument.
5774 // Idx indexes LLVM arguments. Don't touch it.
5777 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
5779 SmallVector<SDValue, 4> ArgValues;
5780 SmallVector<EVT, 4> ValueVTs;
5781 ComputeValueVTs(TLI, I->getType(), ValueVTs);
5782 unsigned NumValues = ValueVTs.size();
5783 for (unsigned Value = 0; Value != NumValues; ++Value) {
5784 EVT VT = ValueVTs[Value];
5785 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
5786 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
5788 if (!I->use_empty()) {
5789 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5790 if (F.paramHasAttr(Idx, Attribute::SExt))
5791 AssertOp = ISD::AssertSext;
5792 else if (F.paramHasAttr(Idx, Attribute::ZExt))
5793 AssertOp = ISD::AssertZext;
5795 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i], NumParts,
5796 PartVT, VT, AssertOp));
5800 if (!I->use_empty()) {
5801 SDB->setValue(I, DAG.getMergeValues(&ArgValues[0], NumValues,
5802 SDB->getCurDebugLoc()));
5803 // If this argument is live outside of the entry block, insert a copy from
5804 // whereever we got it to the vreg that other BB's will reference it as.
5805 SDB->CopyToExportRegsIfNeeded(I);
5808 assert(i == InVals.size() && "Argument register count mismatch!");
5810 // Finally, if the target has anything special to do, allow it to do so.
5811 // FIXME: this should insert code into the DAG!
5812 EmitFunctionEntryCode(F, SDB->DAG.getMachineFunction());
5815 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
5816 /// ensure constants are generated when needed. Remember the virtual registers
5817 /// that need to be added to the Machine PHI nodes as input. We cannot just
5818 /// directly add them, because expansion might result in multiple MBB's for one
5819 /// BB. As such, the start of the BB might correspond to a different MBB than
5823 SelectionDAGISel::HandlePHINodesInSuccessorBlocks(BasicBlock *LLVMBB) {
5824 TerminatorInst *TI = LLVMBB->getTerminator();
5826 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5828 // Check successor nodes' PHI nodes that expect a constant to be available
5830 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5831 BasicBlock *SuccBB = TI->getSuccessor(succ);
5832 if (!isa<PHINode>(SuccBB->begin())) continue;
5833 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5835 // If this terminator has multiple identical successors (common for
5836 // switches), only handle each succ once.
5837 if (!SuccsHandled.insert(SuccMBB)) continue;
5839 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5842 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5843 // nodes and Machine PHI nodes, but the incoming operands have not been
5845 for (BasicBlock::iterator I = SuccBB->begin();
5846 (PN = dyn_cast<PHINode>(I)); ++I) {
5847 // Ignore dead phi's.
5848 if (PN->use_empty()) continue;
5851 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5853 if (Constant *C = dyn_cast<Constant>(PHIOp)) {
5854 unsigned &RegOut = SDB->ConstantsOut[C];
5856 RegOut = FuncInfo->CreateRegForValue(C);
5857 SDB->CopyValueToVirtualRegister(C, RegOut);
5861 Reg = FuncInfo->ValueMap[PHIOp];
5863 assert(isa<AllocaInst>(PHIOp) &&
5864 FuncInfo->StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
5865 "Didn't codegen value into a register!??");
5866 Reg = FuncInfo->CreateRegForValue(PHIOp);
5867 SDB->CopyValueToVirtualRegister(PHIOp, Reg);
5871 // Remember that this register needs to added to the machine PHI node as
5872 // the input for this MBB.
5873 SmallVector<EVT, 4> ValueVTs;
5874 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
5875 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
5876 EVT VT = ValueVTs[vti];
5877 unsigned NumRegisters = TLI.getNumRegisters(*CurDAG->getContext(), VT);
5878 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
5879 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
5880 Reg += NumRegisters;
5884 SDB->ConstantsOut.clear();
5887 /// This is the Fast-ISel version of HandlePHINodesInSuccessorBlocks. It only
5888 /// supports legal types, and it emits MachineInstrs directly instead of
5889 /// creating SelectionDAG nodes.
5892 SelectionDAGISel::HandlePHINodesInSuccessorBlocksFast(BasicBlock *LLVMBB,
5894 TerminatorInst *TI = LLVMBB->getTerminator();
5896 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
5897 unsigned OrigNumPHINodesToUpdate = SDB->PHINodesToUpdate.size();
5899 // Check successor nodes' PHI nodes that expect a constant to be available
5901 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
5902 BasicBlock *SuccBB = TI->getSuccessor(succ);
5903 if (!isa<PHINode>(SuccBB->begin())) continue;
5904 MachineBasicBlock *SuccMBB = FuncInfo->MBBMap[SuccBB];
5906 // If this terminator has multiple identical successors (common for
5907 // switches), only handle each succ once.
5908 if (!SuccsHandled.insert(SuccMBB)) continue;
5910 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
5913 // At this point we know that there is a 1-1 correspondence between LLVM PHI
5914 // nodes and Machine PHI nodes, but the incoming operands have not been
5916 for (BasicBlock::iterator I = SuccBB->begin();
5917 (PN = dyn_cast<PHINode>(I)); ++I) {
5918 // Ignore dead phi's.
5919 if (PN->use_empty()) continue;
5921 // Only handle legal types. Two interesting things to note here. First,
5922 // by bailing out early, we may leave behind some dead instructions,
5923 // since SelectionDAG's HandlePHINodesInSuccessorBlocks will insert its
5924 // own moves. Second, this check is necessary becuase FastISel doesn't
5925 // use CreateRegForValue to create registers, so it always creates
5926 // exactly one register for each non-void instruction.
5927 EVT VT = TLI.getValueType(PN->getType(), /*AllowUnknown=*/true);
5928 if (VT == MVT::Other || !TLI.isTypeLegal(VT)) {
5931 VT = TLI.getTypeToTransformTo(*CurDAG->getContext(), VT);
5933 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5938 Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
5940 unsigned Reg = F->getRegForValue(PHIOp);
5942 SDB->PHINodesToUpdate.resize(OrigNumPHINodesToUpdate);
5945 SDB->PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg));