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 "SDNodeDbgValue.h"
16 #include "SelectionDAGBuilder.h"
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/ADT/PostOrderIterator.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Constants.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Function.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/InlineAsm.h"
28 #include "llvm/Instructions.h"
29 #include "llvm/Intrinsics.h"
30 #include "llvm/IntrinsicInst.h"
31 #include "llvm/LLVMContext.h"
32 #include "llvm/Module.h"
33 #include "llvm/CodeGen/Analysis.h"
34 #include "llvm/CodeGen/FastISel.h"
35 #include "llvm/CodeGen/FunctionLoweringInfo.h"
36 #include "llvm/CodeGen/GCStrategy.h"
37 #include "llvm/CodeGen/GCMetadata.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineFrameInfo.h"
40 #include "llvm/CodeGen/MachineInstrBuilder.h"
41 #include "llvm/CodeGen/MachineJumpTableInfo.h"
42 #include "llvm/CodeGen/MachineModuleInfo.h"
43 #include "llvm/CodeGen/MachineRegisterInfo.h"
44 #include "llvm/CodeGen/PseudoSourceValue.h"
45 #include "llvm/CodeGen/SelectionDAG.h"
46 #include "llvm/Analysis/DebugInfo.h"
47 #include "llvm/Target/TargetData.h"
48 #include "llvm/Target/TargetFrameLowering.h"
49 #include "llvm/Target/TargetInstrInfo.h"
50 #include "llvm/Target/TargetIntrinsicInfo.h"
51 #include "llvm/Target/TargetLowering.h"
52 #include "llvm/Target/TargetOptions.h"
53 #include "llvm/Support/CommandLine.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include "llvm/Support/MathExtras.h"
57 #include "llvm/Support/raw_ostream.h"
61 /// LimitFloatPrecision - Generate low-precision inline sequences for
62 /// some float libcalls (6, 8 or 12 bits).
63 static unsigned LimitFloatPrecision;
65 static cl::opt<unsigned, true>
66 LimitFPPrecision("limit-float-precision",
67 cl::desc("Generate low-precision inline sequences "
68 "for some float libcalls"),
69 cl::location(LimitFloatPrecision),
72 // Limit the width of DAG chains. This is important in general to prevent
73 // prevent DAG-based analysis from blowing up. For example, alias analysis and
74 // load clustering may not complete in reasonable time. It is difficult to
75 // recognize and avoid this situation within each individual analysis, and
76 // future analyses are likely to have the same behavior. Limiting DAG width is
77 // the safe approach, and will be especially important with global DAGs.
79 // MaxParallelChains default is arbitrarily high to avoid affecting
80 // optimization, but could be lowered to improve compile time. Any ld-ld-st-st
81 // sequence over this should have been converted to llvm.memcpy by the
82 // frontend. It easy to induce this behavior with .ll code such as:
83 // %buffer = alloca [4096 x i8]
84 // %data = load [4096 x i8]* %argPtr
85 // store [4096 x i8] %data, [4096 x i8]* %buffer
86 static const unsigned MaxParallelChains = 64;
88 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, DebugLoc DL,
89 const SDValue *Parts, unsigned NumParts,
90 EVT PartVT, EVT ValueVT);
92 /// getCopyFromParts - Create a value that contains the specified legal parts
93 /// combined into the value they represent. If the parts combine to a type
94 /// larger then ValueVT then AssertOp can be used to specify whether the extra
95 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
96 /// (ISD::AssertSext).
97 static SDValue getCopyFromParts(SelectionDAG &DAG, DebugLoc DL,
99 unsigned NumParts, EVT PartVT, EVT ValueVT,
100 ISD::NodeType AssertOp = ISD::DELETED_NODE) {
101 if (ValueVT.isVector())
102 return getCopyFromPartsVector(DAG, DL, Parts, NumParts, PartVT, ValueVT);
104 assert(NumParts > 0 && "No parts to assemble!");
105 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
106 SDValue Val = Parts[0];
109 // Assemble the value from multiple parts.
110 if (ValueVT.isInteger()) {
111 unsigned PartBits = PartVT.getSizeInBits();
112 unsigned ValueBits = ValueVT.getSizeInBits();
114 // Assemble the power of 2 part.
115 unsigned RoundParts = NumParts & (NumParts - 1) ?
116 1 << Log2_32(NumParts) : NumParts;
117 unsigned RoundBits = PartBits * RoundParts;
118 EVT RoundVT = RoundBits == ValueBits ?
119 ValueVT : EVT::getIntegerVT(*DAG.getContext(), RoundBits);
122 EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), RoundBits/2);
124 if (RoundParts > 2) {
125 Lo = getCopyFromParts(DAG, DL, Parts, RoundParts / 2,
127 Hi = getCopyFromParts(DAG, DL, Parts + RoundParts / 2,
128 RoundParts / 2, PartVT, HalfVT);
130 Lo = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[0]);
131 Hi = DAG.getNode(ISD::BITCAST, DL, HalfVT, Parts[1]);
134 if (TLI.isBigEndian())
137 Val = DAG.getNode(ISD::BUILD_PAIR, DL, RoundVT, Lo, Hi);
139 if (RoundParts < NumParts) {
140 // Assemble the trailing non-power-of-2 part.
141 unsigned OddParts = NumParts - RoundParts;
142 EVT OddVT = EVT::getIntegerVT(*DAG.getContext(), OddParts * PartBits);
143 Hi = getCopyFromParts(DAG, DL,
144 Parts + RoundParts, OddParts, PartVT, OddVT);
146 // Combine the round and odd parts.
148 if (TLI.isBigEndian())
150 EVT TotalVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
151 Hi = DAG.getNode(ISD::ANY_EXTEND, DL, TotalVT, Hi);
152 Hi = DAG.getNode(ISD::SHL, DL, TotalVT, Hi,
153 DAG.getConstant(Lo.getValueType().getSizeInBits(),
154 TLI.getPointerTy()));
155 Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, TotalVT, Lo);
156 Val = DAG.getNode(ISD::OR, DL, TotalVT, Lo, Hi);
158 } else if (PartVT.isFloatingPoint()) {
159 // FP split into multiple FP parts (for ppcf128)
160 assert(ValueVT == EVT(MVT::ppcf128) && PartVT == EVT(MVT::f64) &&
163 Lo = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[0]);
164 Hi = DAG.getNode(ISD::BITCAST, DL, EVT(MVT::f64), Parts[1]);
165 if (TLI.isBigEndian())
167 Val = DAG.getNode(ISD::BUILD_PAIR, DL, ValueVT, Lo, Hi);
169 // FP split into integer parts (soft fp)
170 assert(ValueVT.isFloatingPoint() && PartVT.isInteger() &&
171 !PartVT.isVector() && "Unexpected split");
172 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), ValueVT.getSizeInBits());
173 Val = getCopyFromParts(DAG, DL, Parts, NumParts, PartVT, IntVT);
177 // There is now one part, held in Val. Correct it to match ValueVT.
178 PartVT = Val.getValueType();
180 if (PartVT == ValueVT)
183 if (PartVT.isInteger() && ValueVT.isInteger()) {
184 if (ValueVT.bitsLT(PartVT)) {
185 // For a truncate, see if we have any information to
186 // indicate whether the truncated bits will always be
187 // zero or sign-extension.
188 if (AssertOp != ISD::DELETED_NODE)
189 Val = DAG.getNode(AssertOp, DL, PartVT, Val,
190 DAG.getValueType(ValueVT));
191 return DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
193 return DAG.getNode(ISD::ANY_EXTEND, DL, ValueVT, Val);
196 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
197 // FP_ROUND's are always exact here.
198 if (ValueVT.bitsLT(Val.getValueType()))
199 return DAG.getNode(ISD::FP_ROUND, DL, ValueVT, Val,
200 DAG.getIntPtrConstant(1));
202 return DAG.getNode(ISD::FP_EXTEND, DL, ValueVT, Val);
205 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits())
206 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
208 llvm_unreachable("Unknown mismatch!");
212 /// getCopyFromParts - Create a value that contains the specified legal parts
213 /// combined into the value they represent. If the parts combine to a type
214 /// larger then ValueVT then AssertOp can be used to specify whether the extra
215 /// bits are known to be zero (ISD::AssertZext) or sign extended from ValueVT
216 /// (ISD::AssertSext).
217 static SDValue getCopyFromPartsVector(SelectionDAG &DAG, DebugLoc DL,
218 const SDValue *Parts, unsigned NumParts,
219 EVT PartVT, EVT ValueVT) {
220 assert(ValueVT.isVector() && "Not a vector value");
221 assert(NumParts > 0 && "No parts to assemble!");
222 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
223 SDValue Val = Parts[0];
225 // Handle a multi-element vector.
227 EVT IntermediateVT, RegisterVT;
228 unsigned NumIntermediates;
230 TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT, IntermediateVT,
231 NumIntermediates, RegisterVT);
232 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
233 NumParts = NumRegs; // Silence a compiler warning.
234 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
235 assert(RegisterVT == Parts[0].getValueType() &&
236 "Part type doesn't match part!");
238 // Assemble the parts into intermediate operands.
239 SmallVector<SDValue, 8> Ops(NumIntermediates);
240 if (NumIntermediates == NumParts) {
241 // If the register was not expanded, truncate or copy the value,
243 for (unsigned i = 0; i != NumParts; ++i)
244 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i], 1,
245 PartVT, IntermediateVT);
246 } else if (NumParts > 0) {
247 // If the intermediate type was expanded, build the intermediate
248 // operands from the parts.
249 assert(NumParts % NumIntermediates == 0 &&
250 "Must expand into a divisible number of parts!");
251 unsigned Factor = NumParts / NumIntermediates;
252 for (unsigned i = 0; i != NumIntermediates; ++i)
253 Ops[i] = getCopyFromParts(DAG, DL, &Parts[i * Factor], Factor,
254 PartVT, IntermediateVT);
257 // Build a vector with BUILD_VECTOR or CONCAT_VECTORS from the
258 // intermediate operands.
259 Val = DAG.getNode(IntermediateVT.isVector() ?
260 ISD::CONCAT_VECTORS : ISD::BUILD_VECTOR, DL,
261 ValueVT, &Ops[0], NumIntermediates);
264 // There is now one part, held in Val. Correct it to match ValueVT.
265 PartVT = Val.getValueType();
267 if (PartVT == ValueVT)
270 if (PartVT.isVector()) {
271 // If the element type of the source/dest vectors are the same, but the
272 // parts vector has more elements than the value vector, then we have a
273 // vector widening case (e.g. <2 x float> -> <4 x float>). Extract the
275 if (PartVT.getVectorElementType() == ValueVT.getVectorElementType()) {
276 assert(PartVT.getVectorNumElements() > ValueVT.getVectorNumElements() &&
277 "Cannot narrow, it would be a lossy transformation");
278 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
279 DAG.getIntPtrConstant(0));
282 // Vector/Vector bitcast.
283 if (ValueVT.getSizeInBits() == PartVT.getSizeInBits())
284 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
286 assert(PartVT.getVectorNumElements() == ValueVT.getVectorNumElements() &&
287 "Cannot handle this kind of promotion");
288 // Promoted vector extract
289 bool Smaller = ValueVT.bitsLE(PartVT);
290 return DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
295 // Trivial bitcast if the types are the same size and the destination
296 // vector type is legal.
297 if (PartVT.getSizeInBits() == ValueVT.getSizeInBits() &&
298 TLI.isTypeLegal(ValueVT))
299 return DAG.getNode(ISD::BITCAST, DL, ValueVT, Val);
301 // Handle cases such as i8 -> <1 x i1>
302 assert(ValueVT.getVectorNumElements() == 1 &&
303 "Only trivial scalar-to-vector conversions should get here!");
305 if (ValueVT.getVectorNumElements() == 1 &&
306 ValueVT.getVectorElementType() != PartVT) {
307 bool Smaller = ValueVT.bitsLE(PartVT);
308 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
309 DL, ValueVT.getScalarType(), Val);
312 return DAG.getNode(ISD::BUILD_VECTOR, DL, ValueVT, Val);
318 static void getCopyToPartsVector(SelectionDAG &DAG, DebugLoc dl,
319 SDValue Val, SDValue *Parts, unsigned NumParts,
322 /// getCopyToParts - Create a series of nodes that contain the specified value
323 /// split into legal parts. If the parts contain more bits than Val, then, for
324 /// integers, ExtendKind can be used to specify how to generate the extra bits.
325 static void getCopyToParts(SelectionDAG &DAG, DebugLoc DL,
326 SDValue Val, SDValue *Parts, unsigned NumParts,
328 ISD::NodeType ExtendKind = ISD::ANY_EXTEND) {
329 EVT ValueVT = Val.getValueType();
331 // Handle the vector case separately.
332 if (ValueVT.isVector())
333 return getCopyToPartsVector(DAG, DL, Val, Parts, NumParts, PartVT);
335 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
336 unsigned PartBits = PartVT.getSizeInBits();
337 unsigned OrigNumParts = NumParts;
338 assert(TLI.isTypeLegal(PartVT) && "Copying to an illegal type!");
343 assert(!ValueVT.isVector() && "Vector case handled elsewhere");
344 if (PartVT == ValueVT) {
345 assert(NumParts == 1 && "No-op copy with multiple parts!");
350 if (NumParts * PartBits > ValueVT.getSizeInBits()) {
351 // If the parts cover more bits than the value has, promote the value.
352 if (PartVT.isFloatingPoint() && ValueVT.isFloatingPoint()) {
353 assert(NumParts == 1 && "Do not know what to promote to!");
354 Val = DAG.getNode(ISD::FP_EXTEND, DL, PartVT, Val);
356 assert(PartVT.isInteger() && ValueVT.isInteger() &&
357 "Unknown mismatch!");
358 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
359 Val = DAG.getNode(ExtendKind, DL, ValueVT, Val);
361 } else if (PartBits == ValueVT.getSizeInBits()) {
362 // Different types of the same size.
363 assert(NumParts == 1 && PartVT != ValueVT);
364 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
365 } else if (NumParts * PartBits < ValueVT.getSizeInBits()) {
366 // If the parts cover less bits than value has, truncate the value.
367 assert(PartVT.isInteger() && ValueVT.isInteger() &&
368 "Unknown mismatch!");
369 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
370 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
373 // The value may have changed - recompute ValueVT.
374 ValueVT = Val.getValueType();
375 assert(NumParts * PartBits == ValueVT.getSizeInBits() &&
376 "Failed to tile the value with PartVT!");
379 assert(PartVT == ValueVT && "Type conversion failed!");
384 // Expand the value into multiple parts.
385 if (NumParts & (NumParts - 1)) {
386 // The number of parts is not a power of 2. Split off and copy the tail.
387 assert(PartVT.isInteger() && ValueVT.isInteger() &&
388 "Do not know what to expand to!");
389 unsigned RoundParts = 1 << Log2_32(NumParts);
390 unsigned RoundBits = RoundParts * PartBits;
391 unsigned OddParts = NumParts - RoundParts;
392 SDValue OddVal = DAG.getNode(ISD::SRL, DL, ValueVT, Val,
393 DAG.getIntPtrConstant(RoundBits));
394 getCopyToParts(DAG, DL, OddVal, Parts + RoundParts, OddParts, PartVT);
396 if (TLI.isBigEndian())
397 // The odd parts were reversed by getCopyToParts - unreverse them.
398 std::reverse(Parts + RoundParts, Parts + NumParts);
400 NumParts = RoundParts;
401 ValueVT = EVT::getIntegerVT(*DAG.getContext(), NumParts * PartBits);
402 Val = DAG.getNode(ISD::TRUNCATE, DL, ValueVT, Val);
405 // The number of parts is a power of 2. Repeatedly bisect the value using
407 Parts[0] = DAG.getNode(ISD::BITCAST, DL,
408 EVT::getIntegerVT(*DAG.getContext(),
409 ValueVT.getSizeInBits()),
412 for (unsigned StepSize = NumParts; StepSize > 1; StepSize /= 2) {
413 for (unsigned i = 0; i < NumParts; i += StepSize) {
414 unsigned ThisBits = StepSize * PartBits / 2;
415 EVT ThisVT = EVT::getIntegerVT(*DAG.getContext(), ThisBits);
416 SDValue &Part0 = Parts[i];
417 SDValue &Part1 = Parts[i+StepSize/2];
419 Part1 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
420 ThisVT, Part0, DAG.getIntPtrConstant(1));
421 Part0 = DAG.getNode(ISD::EXTRACT_ELEMENT, DL,
422 ThisVT, Part0, DAG.getIntPtrConstant(0));
424 if (ThisBits == PartBits && ThisVT != PartVT) {
425 Part0 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part0);
426 Part1 = DAG.getNode(ISD::BITCAST, DL, PartVT, Part1);
431 if (TLI.isBigEndian())
432 std::reverse(Parts, Parts + OrigNumParts);
436 /// getCopyToPartsVector - Create a series of nodes that contain the specified
437 /// value split into legal parts.
438 static void getCopyToPartsVector(SelectionDAG &DAG, DebugLoc DL,
439 SDValue Val, SDValue *Parts, unsigned NumParts,
441 EVT ValueVT = Val.getValueType();
442 assert(ValueVT.isVector() && "Not a vector");
443 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
446 if (PartVT == ValueVT) {
448 } else if (PartVT.getSizeInBits() == ValueVT.getSizeInBits()) {
449 // Bitconvert vector->vector case.
450 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
451 } else if (PartVT.isVector() &&
452 PartVT.getVectorElementType() == ValueVT.getVectorElementType() &&
453 PartVT.getVectorNumElements() > ValueVT.getVectorNumElements()) {
454 EVT ElementVT = PartVT.getVectorElementType();
455 // Vector widening case, e.g. <2 x float> -> <4 x float>. Shuffle in
457 SmallVector<SDValue, 16> Ops;
458 for (unsigned i = 0, e = ValueVT.getVectorNumElements(); i != e; ++i)
459 Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
460 ElementVT, Val, DAG.getIntPtrConstant(i)));
462 for (unsigned i = ValueVT.getVectorNumElements(),
463 e = PartVT.getVectorNumElements(); i != e; ++i)
464 Ops.push_back(DAG.getUNDEF(ElementVT));
466 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT, &Ops[0], Ops.size());
468 // FIXME: Use CONCAT for 2x -> 4x.
470 //SDValue UndefElts = DAG.getUNDEF(VectorTy);
471 //Val = DAG.getNode(ISD::CONCAT_VECTORS, DL, PartVT, Val, UndefElts);
472 } else if (PartVT.isVector() &&
473 PartVT.getVectorElementType().bitsGE(
474 ValueVT.getVectorElementType()) &&
475 PartVT.getVectorNumElements() == ValueVT.getVectorNumElements()) {
477 // Promoted vector extract
478 unsigned NumElts = ValueVT.getVectorNumElements();
479 SmallVector<SDValue, 8> NewOps;
480 for (unsigned i = 0; i < NumElts; ++i) {
481 SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
482 ValueVT.getScalarType(), Val ,DAG.getIntPtrConstant(i));
483 SDValue Cast = DAG.getNode(ISD::ANY_EXTEND,
484 DL, PartVT.getScalarType(), Ext);
485 NewOps.push_back(Cast);
487 Val = DAG.getNode(ISD::BUILD_VECTOR, DL, PartVT,
488 &NewOps[0], NewOps.size());
490 // Vector -> scalar conversion.
491 assert(ValueVT.getVectorNumElements() == 1 &&
492 "Only trivial vector-to-scalar conversions should get here!");
493 Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
494 PartVT, Val, DAG.getIntPtrConstant(0));
496 bool Smaller = ValueVT.bitsLE(PartVT);
497 Val = DAG.getNode((Smaller ? ISD::TRUNCATE : ISD::ANY_EXTEND),
505 // Handle a multi-element vector.
506 EVT IntermediateVT, RegisterVT;
507 unsigned NumIntermediates;
508 unsigned NumRegs = TLI.getVectorTypeBreakdown(*DAG.getContext(), ValueVT,
510 NumIntermediates, RegisterVT);
511 unsigned NumElements = ValueVT.getVectorNumElements();
513 assert(NumRegs == NumParts && "Part count doesn't match vector breakdown!");
514 NumParts = NumRegs; // Silence a compiler warning.
515 assert(RegisterVT == PartVT && "Part type doesn't match vector breakdown!");
517 // Split the vector into intermediate operands.
518 SmallVector<SDValue, 8> Ops(NumIntermediates);
519 for (unsigned i = 0; i != NumIntermediates; ++i) {
520 if (IntermediateVT.isVector())
521 Ops[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
523 DAG.getIntPtrConstant(i * (NumElements / NumIntermediates)));
525 Ops[i] = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
526 IntermediateVT, Val, DAG.getIntPtrConstant(i));
529 // Split the intermediate operands into legal parts.
530 if (NumParts == NumIntermediates) {
531 // If the register was not expanded, promote or copy the value,
533 for (unsigned i = 0; i != NumParts; ++i)
534 getCopyToParts(DAG, DL, Ops[i], &Parts[i], 1, PartVT);
535 } else if (NumParts > 0) {
536 // If the intermediate type was expanded, split each the value into
538 assert(NumParts % NumIntermediates == 0 &&
539 "Must expand into a divisible number of parts!");
540 unsigned Factor = NumParts / NumIntermediates;
541 for (unsigned i = 0; i != NumIntermediates; ++i)
542 getCopyToParts(DAG, DL, Ops[i], &Parts[i*Factor], Factor, PartVT);
550 /// RegsForValue - This struct represents the registers (physical or virtual)
551 /// that a particular set of values is assigned, and the type information
552 /// about the value. The most common situation is to represent one value at a
553 /// time, but struct or array values are handled element-wise as multiple
554 /// values. The splitting of aggregates is performed recursively, so that we
555 /// never have aggregate-typed registers. The values at this point do not
556 /// necessarily have legal types, so each value may require one or more
557 /// registers of some legal type.
559 struct RegsForValue {
560 /// ValueVTs - The value types of the values, which may not be legal, and
561 /// may need be promoted or synthesized from one or more registers.
563 SmallVector<EVT, 4> ValueVTs;
565 /// RegVTs - The value types of the registers. This is the same size as
566 /// ValueVTs and it records, for each value, what the type of the assigned
567 /// register or registers are. (Individual values are never synthesized
568 /// from more than one type of register.)
570 /// With virtual registers, the contents of RegVTs is redundant with TLI's
571 /// getRegisterType member function, however when with physical registers
572 /// it is necessary to have a separate record of the types.
574 SmallVector<EVT, 4> RegVTs;
576 /// Regs - This list holds the registers assigned to the values.
577 /// Each legal or promoted value requires one register, and each
578 /// expanded value requires multiple registers.
580 SmallVector<unsigned, 4> Regs;
584 RegsForValue(const SmallVector<unsigned, 4> ®s,
585 EVT regvt, EVT valuevt)
586 : ValueVTs(1, valuevt), RegVTs(1, regvt), Regs(regs) {}
588 RegsForValue(LLVMContext &Context, const TargetLowering &tli,
589 unsigned Reg, const Type *Ty) {
590 ComputeValueVTs(tli, Ty, ValueVTs);
592 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
593 EVT ValueVT = ValueVTs[Value];
594 unsigned NumRegs = tli.getNumRegisters(Context, ValueVT);
595 EVT RegisterVT = tli.getRegisterType(Context, ValueVT);
596 for (unsigned i = 0; i != NumRegs; ++i)
597 Regs.push_back(Reg + i);
598 RegVTs.push_back(RegisterVT);
603 /// areValueTypesLegal - Return true if types of all the values are legal.
604 bool areValueTypesLegal(const TargetLowering &TLI) {
605 for (unsigned Value = 0, e = ValueVTs.size(); Value != e; ++Value) {
606 EVT RegisterVT = RegVTs[Value];
607 if (!TLI.isTypeLegal(RegisterVT))
613 /// append - Add the specified values to this one.
614 void append(const RegsForValue &RHS) {
615 ValueVTs.append(RHS.ValueVTs.begin(), RHS.ValueVTs.end());
616 RegVTs.append(RHS.RegVTs.begin(), RHS.RegVTs.end());
617 Regs.append(RHS.Regs.begin(), RHS.Regs.end());
620 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
621 /// this value and returns the result as a ValueVTs value. This uses
622 /// Chain/Flag as the input and updates them for the output Chain/Flag.
623 /// If the Flag pointer is NULL, no flag is used.
624 SDValue getCopyFromRegs(SelectionDAG &DAG, FunctionLoweringInfo &FuncInfo,
626 SDValue &Chain, SDValue *Flag) const;
628 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
629 /// specified value into the registers specified by this object. This uses
630 /// Chain/Flag as the input and updates them for the output Chain/Flag.
631 /// If the Flag pointer is NULL, no flag is used.
632 void getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
633 SDValue &Chain, SDValue *Flag) const;
635 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
636 /// operand list. This adds the code marker, matching input operand index
637 /// (if applicable), and includes the number of values added into it.
638 void AddInlineAsmOperands(unsigned Kind,
639 bool HasMatching, unsigned MatchingIdx,
641 std::vector<SDValue> &Ops) const;
645 /// getCopyFromRegs - Emit a series of CopyFromReg nodes that copies from
646 /// this value and returns the result as a ValueVT value. This uses
647 /// Chain/Flag as the input and updates them for the output Chain/Flag.
648 /// If the Flag pointer is NULL, no flag is used.
649 SDValue RegsForValue::getCopyFromRegs(SelectionDAG &DAG,
650 FunctionLoweringInfo &FuncInfo,
652 SDValue &Chain, SDValue *Flag) const {
653 // A Value with type {} or [0 x %t] needs no registers.
654 if (ValueVTs.empty())
657 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
659 // Assemble the legal parts into the final values.
660 SmallVector<SDValue, 4> Values(ValueVTs.size());
661 SmallVector<SDValue, 8> Parts;
662 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
663 // Copy the legal parts from the registers.
664 EVT ValueVT = ValueVTs[Value];
665 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
666 EVT RegisterVT = RegVTs[Value];
668 Parts.resize(NumRegs);
669 for (unsigned i = 0; i != NumRegs; ++i) {
672 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT);
674 P = DAG.getCopyFromReg(Chain, dl, Regs[Part+i], RegisterVT, *Flag);
675 *Flag = P.getValue(2);
678 Chain = P.getValue(1);
681 // If the source register was virtual and if we know something about it,
682 // add an assert node.
683 if (!TargetRegisterInfo::isVirtualRegister(Regs[Part+i]) ||
684 !RegisterVT.isInteger() || RegisterVT.isVector())
687 const FunctionLoweringInfo::LiveOutInfo *LOI =
688 FuncInfo.GetLiveOutRegInfo(Regs[Part+i]);
692 unsigned RegSize = RegisterVT.getSizeInBits();
693 unsigned NumSignBits = LOI->NumSignBits;
694 unsigned NumZeroBits = LOI->KnownZero.countLeadingOnes();
696 // FIXME: We capture more information than the dag can represent. For
697 // now, just use the tightest assertzext/assertsext possible.
699 EVT FromVT(MVT::Other);
700 if (NumSignBits == RegSize)
701 isSExt = true, FromVT = MVT::i1; // ASSERT SEXT 1
702 else if (NumZeroBits >= RegSize-1)
703 isSExt = false, FromVT = MVT::i1; // ASSERT ZEXT 1
704 else if (NumSignBits > RegSize-8)
705 isSExt = true, FromVT = MVT::i8; // ASSERT SEXT 8
706 else if (NumZeroBits >= RegSize-8)
707 isSExt = false, FromVT = MVT::i8; // ASSERT ZEXT 8
708 else if (NumSignBits > RegSize-16)
709 isSExt = true, FromVT = MVT::i16; // ASSERT SEXT 16
710 else if (NumZeroBits >= RegSize-16)
711 isSExt = false, FromVT = MVT::i16; // ASSERT ZEXT 16
712 else if (NumSignBits > RegSize-32)
713 isSExt = true, FromVT = MVT::i32; // ASSERT SEXT 32
714 else if (NumZeroBits >= RegSize-32)
715 isSExt = false, FromVT = MVT::i32; // ASSERT ZEXT 32
719 // Add an assertion node.
720 assert(FromVT != MVT::Other);
721 Parts[i] = DAG.getNode(isSExt ? ISD::AssertSext : ISD::AssertZext, dl,
722 RegisterVT, P, DAG.getValueType(FromVT));
725 Values[Value] = getCopyFromParts(DAG, dl, Parts.begin(),
726 NumRegs, RegisterVT, ValueVT);
731 return DAG.getNode(ISD::MERGE_VALUES, dl,
732 DAG.getVTList(&ValueVTs[0], ValueVTs.size()),
733 &Values[0], ValueVTs.size());
736 /// getCopyToRegs - Emit a series of CopyToReg nodes that copies the
737 /// specified value into the registers specified by this object. This uses
738 /// Chain/Flag as the input and updates them for the output Chain/Flag.
739 /// If the Flag pointer is NULL, no flag is used.
740 void RegsForValue::getCopyToRegs(SDValue Val, SelectionDAG &DAG, DebugLoc dl,
741 SDValue &Chain, SDValue *Flag) const {
742 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
744 // Get the list of the values's legal parts.
745 unsigned NumRegs = Regs.size();
746 SmallVector<SDValue, 8> Parts(NumRegs);
747 for (unsigned Value = 0, Part = 0, e = ValueVTs.size(); Value != e; ++Value) {
748 EVT ValueVT = ValueVTs[Value];
749 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), ValueVT);
750 EVT RegisterVT = RegVTs[Value];
752 getCopyToParts(DAG, dl, Val.getValue(Val.getResNo() + Value),
753 &Parts[Part], NumParts, RegisterVT);
757 // Copy the parts into the registers.
758 SmallVector<SDValue, 8> Chains(NumRegs);
759 for (unsigned i = 0; i != NumRegs; ++i) {
762 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i]);
764 Part = DAG.getCopyToReg(Chain, dl, Regs[i], Parts[i], *Flag);
765 *Flag = Part.getValue(1);
768 Chains[i] = Part.getValue(0);
771 if (NumRegs == 1 || Flag)
772 // If NumRegs > 1 && Flag is used then the use of the last CopyToReg is
773 // flagged to it. That is the CopyToReg nodes and the user are considered
774 // a single scheduling unit. If we create a TokenFactor and return it as
775 // chain, then the TokenFactor is both a predecessor (operand) of the
776 // user as well as a successor (the TF operands are flagged to the user).
777 // c1, f1 = CopyToReg
778 // c2, f2 = CopyToReg
779 // c3 = TokenFactor c1, c2
782 Chain = Chains[NumRegs-1];
784 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Chains[0], NumRegs);
787 /// AddInlineAsmOperands - Add this value to the specified inlineasm node
788 /// operand list. This adds the code marker and includes the number of
789 /// values added into it.
790 void RegsForValue::AddInlineAsmOperands(unsigned Code, bool HasMatching,
791 unsigned MatchingIdx,
793 std::vector<SDValue> &Ops) const {
794 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
796 unsigned Flag = InlineAsm::getFlagWord(Code, Regs.size());
798 Flag = InlineAsm::getFlagWordForMatchingOp(Flag, MatchingIdx);
799 SDValue Res = DAG.getTargetConstant(Flag, MVT::i32);
802 for (unsigned Value = 0, Reg = 0, e = ValueVTs.size(); Value != e; ++Value) {
803 unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), ValueVTs[Value]);
804 EVT RegisterVT = RegVTs[Value];
805 for (unsigned i = 0; i != NumRegs; ++i) {
806 assert(Reg < Regs.size() && "Mismatch in # registers expected");
807 Ops.push_back(DAG.getRegister(Regs[Reg++], RegisterVT));
812 void SelectionDAGBuilder::init(GCFunctionInfo *gfi, AliasAnalysis &aa) {
815 TD = DAG.getTarget().getTargetData();
818 /// clear - Clear out the current SelectionDAG and the associated
819 /// state and prepare this SelectionDAGBuilder object to be used
820 /// for a new block. This doesn't clear out information about
821 /// additional blocks that are needed to complete switch lowering
822 /// or PHI node updating; that information is cleared out as it is
824 void SelectionDAGBuilder::clear() {
826 UnusedArgNodeMap.clear();
827 PendingLoads.clear();
828 PendingExports.clear();
829 CurDebugLoc = DebugLoc();
833 /// clearDanglingDebugInfo - Clear the dangling debug information
834 /// map. This function is seperated from the clear so that debug
835 /// information that is dangling in a basic block can be properly
836 /// resolved in a different basic block. This allows the
837 /// SelectionDAG to resolve dangling debug information attached
839 void SelectionDAGBuilder::clearDanglingDebugInfo() {
840 DanglingDebugInfoMap.clear();
843 /// getRoot - Return the current virtual root of the Selection DAG,
844 /// flushing any PendingLoad items. This must be done before emitting
845 /// a store or any other node that may need to be ordered after any
846 /// prior load instructions.
848 SDValue SelectionDAGBuilder::getRoot() {
849 if (PendingLoads.empty())
850 return DAG.getRoot();
852 if (PendingLoads.size() == 1) {
853 SDValue Root = PendingLoads[0];
855 PendingLoads.clear();
859 // Otherwise, we have to make a token factor node.
860 SDValue Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
861 &PendingLoads[0], PendingLoads.size());
862 PendingLoads.clear();
867 /// getControlRoot - Similar to getRoot, but instead of flushing all the
868 /// PendingLoad items, flush all the PendingExports items. It is necessary
869 /// to do this before emitting a terminator instruction.
871 SDValue SelectionDAGBuilder::getControlRoot() {
872 SDValue Root = DAG.getRoot();
874 if (PendingExports.empty())
877 // Turn all of the CopyToReg chains into one factored node.
878 if (Root.getOpcode() != ISD::EntryToken) {
879 unsigned i = 0, e = PendingExports.size();
880 for (; i != e; ++i) {
881 assert(PendingExports[i].getNode()->getNumOperands() > 1);
882 if (PendingExports[i].getNode()->getOperand(0) == Root)
883 break; // Don't add the root if we already indirectly depend on it.
887 PendingExports.push_back(Root);
890 Root = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
892 PendingExports.size());
893 PendingExports.clear();
898 void SelectionDAGBuilder::AssignOrderingToNode(const SDNode *Node) {
899 if (DAG.GetOrdering(Node) != 0) return; // Already has ordering.
900 DAG.AssignOrdering(Node, SDNodeOrder);
902 for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I)
903 AssignOrderingToNode(Node->getOperand(I).getNode());
906 void SelectionDAGBuilder::visit(const Instruction &I) {
907 // Set up outgoing PHI node register values before emitting the terminator.
908 if (isa<TerminatorInst>(&I))
909 HandlePHINodesInSuccessorBlocks(I.getParent());
911 CurDebugLoc = I.getDebugLoc();
913 visit(I.getOpcode(), I);
915 if (!isa<TerminatorInst>(&I) && !HasTailCall)
916 CopyToExportRegsIfNeeded(&I);
918 CurDebugLoc = DebugLoc();
921 void SelectionDAGBuilder::visitPHI(const PHINode &) {
922 llvm_unreachable("SelectionDAGBuilder shouldn't visit PHI nodes!");
925 void SelectionDAGBuilder::visit(unsigned Opcode, const User &I) {
926 // Note: this doesn't use InstVisitor, because it has to work with
927 // ConstantExpr's in addition to instructions.
929 default: llvm_unreachable("Unknown instruction type encountered!");
930 // Build the switch statement using the Instruction.def file.
931 #define HANDLE_INST(NUM, OPCODE, CLASS) \
932 case Instruction::OPCODE: visit##OPCODE((CLASS&)I); break;
933 #include "llvm/Instruction.def"
936 // Assign the ordering to the freshly created DAG nodes.
937 if (NodeMap.count(&I)) {
939 AssignOrderingToNode(getValue(&I).getNode());
943 // resolveDanglingDebugInfo - if we saw an earlier dbg_value referring to V,
944 // generate the debug data structures now that we've seen its definition.
945 void SelectionDAGBuilder::resolveDanglingDebugInfo(const Value *V,
947 DanglingDebugInfo &DDI = DanglingDebugInfoMap[V];
949 const DbgValueInst *DI = DDI.getDI();
950 DebugLoc dl = DDI.getdl();
951 unsigned DbgSDNodeOrder = DDI.getSDNodeOrder();
952 MDNode *Variable = DI->getVariable();
953 uint64_t Offset = DI->getOffset();
956 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, Val)) {
957 SDV = DAG.getDbgValue(Variable, Val.getNode(),
958 Val.getResNo(), Offset, dl, DbgSDNodeOrder);
959 DAG.AddDbgValue(SDV, Val.getNode(), false);
962 DEBUG(dbgs() << "Dropping debug info for " << DI);
963 DanglingDebugInfoMap[V] = DanglingDebugInfo();
967 // getValue - Return an SDValue for the given Value.
968 SDValue SelectionDAGBuilder::getValue(const Value *V) {
969 // If we already have an SDValue for this value, use it. It's important
970 // to do this first, so that we don't create a CopyFromReg if we already
971 // have a regular SDValue.
972 SDValue &N = NodeMap[V];
973 if (N.getNode()) return N;
975 // If there's a virtual register allocated and initialized for this
977 DenseMap<const Value *, unsigned>::iterator It = FuncInfo.ValueMap.find(V);
978 if (It != FuncInfo.ValueMap.end()) {
979 unsigned InReg = It->second;
980 RegsForValue RFV(*DAG.getContext(), TLI, InReg, V->getType());
981 SDValue Chain = DAG.getEntryNode();
982 N = RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain,NULL);
983 resolveDanglingDebugInfo(V, N);
987 // Otherwise create a new SDValue and remember it.
988 SDValue Val = getValueImpl(V);
990 resolveDanglingDebugInfo(V, Val);
994 /// getNonRegisterValue - Return an SDValue for the given Value, but
995 /// don't look in FuncInfo.ValueMap for a virtual register.
996 SDValue SelectionDAGBuilder::getNonRegisterValue(const Value *V) {
997 // If we already have an SDValue for this value, use it.
998 SDValue &N = NodeMap[V];
999 if (N.getNode()) return N;
1001 // Otherwise create a new SDValue and remember it.
1002 SDValue Val = getValueImpl(V);
1004 resolveDanglingDebugInfo(V, Val);
1008 /// getValueImpl - Helper function for getValue and getNonRegisterValue.
1009 /// Create an SDValue for the given value.
1010 SDValue SelectionDAGBuilder::getValueImpl(const Value *V) {
1011 if (const Constant *C = dyn_cast<Constant>(V)) {
1012 EVT VT = TLI.getValueType(V->getType(), true);
1014 if (const ConstantInt *CI = dyn_cast<ConstantInt>(C))
1015 return DAG.getConstant(*CI, VT);
1017 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
1018 return DAG.getGlobalAddress(GV, getCurDebugLoc(), VT);
1020 if (isa<ConstantPointerNull>(C))
1021 return DAG.getConstant(0, TLI.getPointerTy());
1023 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
1024 return DAG.getConstantFP(*CFP, VT);
1026 if (isa<UndefValue>(C) && !V->getType()->isAggregateType())
1027 return DAG.getUNDEF(VT);
1029 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
1030 visit(CE->getOpcode(), *CE);
1031 SDValue N1 = NodeMap[V];
1032 assert(N1.getNode() && "visit didn't populate the NodeMap!");
1036 if (isa<ConstantStruct>(C) || isa<ConstantArray>(C)) {
1037 SmallVector<SDValue, 4> Constants;
1038 for (User::const_op_iterator OI = C->op_begin(), OE = C->op_end();
1040 SDNode *Val = getValue(*OI).getNode();
1041 // If the operand is an empty aggregate, there are no values.
1043 // Add each leaf value from the operand to the Constants list
1044 // to form a flattened list of all the values.
1045 for (unsigned i = 0, e = Val->getNumValues(); i != e; ++i)
1046 Constants.push_back(SDValue(Val, i));
1049 return DAG.getMergeValues(&Constants[0], Constants.size(),
1053 if (C->getType()->isStructTy() || C->getType()->isArrayTy()) {
1054 assert((isa<ConstantAggregateZero>(C) || isa<UndefValue>(C)) &&
1055 "Unknown struct or array constant!");
1057 SmallVector<EVT, 4> ValueVTs;
1058 ComputeValueVTs(TLI, C->getType(), ValueVTs);
1059 unsigned NumElts = ValueVTs.size();
1061 return SDValue(); // empty struct
1062 SmallVector<SDValue, 4> Constants(NumElts);
1063 for (unsigned i = 0; i != NumElts; ++i) {
1064 EVT EltVT = ValueVTs[i];
1065 if (isa<UndefValue>(C))
1066 Constants[i] = DAG.getUNDEF(EltVT);
1067 else if (EltVT.isFloatingPoint())
1068 Constants[i] = DAG.getConstantFP(0, EltVT);
1070 Constants[i] = DAG.getConstant(0, EltVT);
1073 return DAG.getMergeValues(&Constants[0], NumElts,
1077 if (const BlockAddress *BA = dyn_cast<BlockAddress>(C))
1078 return DAG.getBlockAddress(BA, VT);
1080 const VectorType *VecTy = cast<VectorType>(V->getType());
1081 unsigned NumElements = VecTy->getNumElements();
1083 // Now that we know the number and type of the elements, get that number of
1084 // elements into the Ops array based on what kind of constant it is.
1085 SmallVector<SDValue, 16> Ops;
1086 if (const ConstantVector *CP = dyn_cast<ConstantVector>(C)) {
1087 for (unsigned i = 0; i != NumElements; ++i)
1088 Ops.push_back(getValue(CP->getOperand(i)));
1090 assert(isa<ConstantAggregateZero>(C) && "Unknown vector constant!");
1091 EVT EltVT = TLI.getValueType(VecTy->getElementType());
1094 if (EltVT.isFloatingPoint())
1095 Op = DAG.getConstantFP(0, EltVT);
1097 Op = DAG.getConstant(0, EltVT);
1098 Ops.assign(NumElements, Op);
1101 // Create a BUILD_VECTOR node.
1102 return NodeMap[V] = DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
1103 VT, &Ops[0], Ops.size());
1106 // If this is a static alloca, generate it as the frameindex instead of
1108 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
1109 DenseMap<const AllocaInst*, int>::iterator SI =
1110 FuncInfo.StaticAllocaMap.find(AI);
1111 if (SI != FuncInfo.StaticAllocaMap.end())
1112 return DAG.getFrameIndex(SI->second, TLI.getPointerTy());
1115 // If this is an instruction which fast-isel has deferred, select it now.
1116 if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
1117 unsigned InReg = FuncInfo.InitializeRegForValue(Inst);
1118 RegsForValue RFV(*DAG.getContext(), TLI, InReg, Inst->getType());
1119 SDValue Chain = DAG.getEntryNode();
1120 return RFV.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(), Chain, NULL);
1123 llvm_unreachable("Can't get register for value!");
1127 void SelectionDAGBuilder::visitRet(const ReturnInst &I) {
1128 SDValue Chain = getControlRoot();
1129 SmallVector<ISD::OutputArg, 8> Outs;
1130 SmallVector<SDValue, 8> OutVals;
1132 if (!FuncInfo.CanLowerReturn) {
1133 unsigned DemoteReg = FuncInfo.DemoteRegister;
1134 const Function *F = I.getParent()->getParent();
1136 // Emit a store of the return value through the virtual register.
1137 // Leave Outs empty so that LowerReturn won't try to load return
1138 // registers the usual way.
1139 SmallVector<EVT, 1> PtrValueVTs;
1140 ComputeValueVTs(TLI, PointerType::getUnqual(F->getReturnType()),
1143 SDValue RetPtr = DAG.getRegister(DemoteReg, PtrValueVTs[0]);
1144 SDValue RetOp = getValue(I.getOperand(0));
1146 SmallVector<EVT, 4> ValueVTs;
1147 SmallVector<uint64_t, 4> Offsets;
1148 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs, &Offsets);
1149 unsigned NumValues = ValueVTs.size();
1151 SmallVector<SDValue, 4> Chains(NumValues);
1152 for (unsigned i = 0; i != NumValues; ++i) {
1153 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(),
1154 RetPtr.getValueType(), RetPtr,
1155 DAG.getIntPtrConstant(Offsets[i]));
1157 DAG.getStore(Chain, getCurDebugLoc(),
1158 SDValue(RetOp.getNode(), RetOp.getResNo() + i),
1159 // FIXME: better loc info would be nice.
1160 Add, MachinePointerInfo(), false, false, 0);
1163 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
1164 MVT::Other, &Chains[0], NumValues);
1165 } else if (I.getNumOperands() != 0) {
1166 SmallVector<EVT, 4> ValueVTs;
1167 ComputeValueVTs(TLI, I.getOperand(0)->getType(), ValueVTs);
1168 unsigned NumValues = ValueVTs.size();
1170 SDValue RetOp = getValue(I.getOperand(0));
1171 for (unsigned j = 0, f = NumValues; j != f; ++j) {
1172 EVT VT = ValueVTs[j];
1174 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
1176 const Function *F = I.getParent()->getParent();
1177 if (F->paramHasAttr(0, Attribute::SExt))
1178 ExtendKind = ISD::SIGN_EXTEND;
1179 else if (F->paramHasAttr(0, Attribute::ZExt))
1180 ExtendKind = ISD::ZERO_EXTEND;
1182 if (ExtendKind != ISD::ANY_EXTEND && VT.isInteger())
1183 VT = TLI.getTypeForExtArgOrReturn(*DAG.getContext(), VT, ExtendKind);
1185 unsigned NumParts = TLI.getNumRegisters(*DAG.getContext(), VT);
1186 EVT PartVT = TLI.getRegisterType(*DAG.getContext(), VT);
1187 SmallVector<SDValue, 4> Parts(NumParts);
1188 getCopyToParts(DAG, getCurDebugLoc(),
1189 SDValue(RetOp.getNode(), RetOp.getResNo() + j),
1190 &Parts[0], NumParts, PartVT, ExtendKind);
1192 // 'inreg' on function refers to return value
1193 ISD::ArgFlagsTy Flags = ISD::ArgFlagsTy();
1194 if (F->paramHasAttr(0, Attribute::InReg))
1197 // Propagate extension type if any
1198 if (ExtendKind == ISD::SIGN_EXTEND)
1200 else if (ExtendKind == ISD::ZERO_EXTEND)
1203 for (unsigned i = 0; i < NumParts; ++i) {
1204 Outs.push_back(ISD::OutputArg(Flags, Parts[i].getValueType(),
1206 OutVals.push_back(Parts[i]);
1212 bool isVarArg = DAG.getMachineFunction().getFunction()->isVarArg();
1213 CallingConv::ID CallConv =
1214 DAG.getMachineFunction().getFunction()->getCallingConv();
1215 Chain = TLI.LowerReturn(Chain, CallConv, isVarArg,
1216 Outs, OutVals, getCurDebugLoc(), DAG);
1218 // Verify that the target's LowerReturn behaved as expected.
1219 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
1220 "LowerReturn didn't return a valid chain!");
1222 // Update the DAG with the new chain value resulting from return lowering.
1226 /// CopyToExportRegsIfNeeded - If the given value has virtual registers
1227 /// created for it, emit nodes to copy the value into the virtual
1229 void SelectionDAGBuilder::CopyToExportRegsIfNeeded(const Value *V) {
1231 if (V->getType()->isEmptyTy())
1234 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
1235 if (VMI != FuncInfo.ValueMap.end()) {
1236 assert(!V->use_empty() && "Unused value assigned virtual registers!");
1237 CopyValueToVirtualRegister(V, VMI->second);
1241 /// ExportFromCurrentBlock - If this condition isn't known to be exported from
1242 /// the current basic block, add it to ValueMap now so that we'll get a
1244 void SelectionDAGBuilder::ExportFromCurrentBlock(const Value *V) {
1245 // No need to export constants.
1246 if (!isa<Instruction>(V) && !isa<Argument>(V)) return;
1248 // Already exported?
1249 if (FuncInfo.isExportedInst(V)) return;
1251 unsigned Reg = FuncInfo.InitializeRegForValue(V);
1252 CopyValueToVirtualRegister(V, Reg);
1255 bool SelectionDAGBuilder::isExportableFromCurrentBlock(const Value *V,
1256 const BasicBlock *FromBB) {
1257 // The operands of the setcc have to be in this block. We don't know
1258 // how to export them from some other block.
1259 if (const Instruction *VI = dyn_cast<Instruction>(V)) {
1260 // Can export from current BB.
1261 if (VI->getParent() == FromBB)
1264 // Is already exported, noop.
1265 return FuncInfo.isExportedInst(V);
1268 // If this is an argument, we can export it if the BB is the entry block or
1269 // if it is already exported.
1270 if (isa<Argument>(V)) {
1271 if (FromBB == &FromBB->getParent()->getEntryBlock())
1274 // Otherwise, can only export this if it is already exported.
1275 return FuncInfo.isExportedInst(V);
1278 // Otherwise, constants can always be exported.
1282 static bool InBlock(const Value *V, const BasicBlock *BB) {
1283 if (const Instruction *I = dyn_cast<Instruction>(V))
1284 return I->getParent() == BB;
1288 /// EmitBranchForMergedCondition - Helper method for FindMergedConditions.
1289 /// This function emits a branch and is used at the leaves of an OR or an
1290 /// AND operator tree.
1293 SelectionDAGBuilder::EmitBranchForMergedCondition(const Value *Cond,
1294 MachineBasicBlock *TBB,
1295 MachineBasicBlock *FBB,
1296 MachineBasicBlock *CurBB,
1297 MachineBasicBlock *SwitchBB) {
1298 const BasicBlock *BB = CurBB->getBasicBlock();
1300 // If the leaf of the tree is a comparison, merge the condition into
1302 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) {
1303 // The operands of the cmp have to be in this block. We don't know
1304 // how to export them from some other block. If this is the first block
1305 // of the sequence, no exporting is needed.
1306 if (CurBB == SwitchBB ||
1307 (isExportableFromCurrentBlock(BOp->getOperand(0), BB) &&
1308 isExportableFromCurrentBlock(BOp->getOperand(1), BB))) {
1309 ISD::CondCode Condition;
1310 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) {
1311 Condition = getICmpCondCode(IC->getPredicate());
1312 } else if (const FCmpInst *FC = dyn_cast<FCmpInst>(Cond)) {
1313 Condition = getFCmpCondCode(FC->getPredicate());
1315 Condition = ISD::SETEQ; // silence warning.
1316 llvm_unreachable("Unknown compare instruction");
1319 CaseBlock CB(Condition, BOp->getOperand(0),
1320 BOp->getOperand(1), NULL, TBB, FBB, CurBB);
1321 SwitchCases.push_back(CB);
1326 // Create a CaseBlock record representing this branch.
1327 CaseBlock CB(ISD::SETEQ, Cond, ConstantInt::getTrue(*DAG.getContext()),
1328 NULL, TBB, FBB, CurBB);
1329 SwitchCases.push_back(CB);
1332 /// FindMergedConditions - If Cond is an expression like
1333 void SelectionDAGBuilder::FindMergedConditions(const Value *Cond,
1334 MachineBasicBlock *TBB,
1335 MachineBasicBlock *FBB,
1336 MachineBasicBlock *CurBB,
1337 MachineBasicBlock *SwitchBB,
1339 // If this node is not part of the or/and tree, emit it as a branch.
1340 const Instruction *BOp = dyn_cast<Instruction>(Cond);
1341 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) ||
1342 (unsigned)BOp->getOpcode() != Opc || !BOp->hasOneUse() ||
1343 BOp->getParent() != CurBB->getBasicBlock() ||
1344 !InBlock(BOp->getOperand(0), CurBB->getBasicBlock()) ||
1345 !InBlock(BOp->getOperand(1), CurBB->getBasicBlock())) {
1346 EmitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB);
1350 // Create TmpBB after CurBB.
1351 MachineFunction::iterator BBI = CurBB;
1352 MachineFunction &MF = DAG.getMachineFunction();
1353 MachineBasicBlock *TmpBB = MF.CreateMachineBasicBlock(CurBB->getBasicBlock());
1354 CurBB->getParent()->insert(++BBI, TmpBB);
1356 if (Opc == Instruction::Or) {
1357 // Codegen X | Y as:
1365 // Emit the LHS condition.
1366 FindMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc);
1368 // Emit the RHS condition into TmpBB.
1369 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
1371 assert(Opc == Instruction::And && "Unknown merge op!");
1372 // Codegen X & Y as:
1379 // This requires creation of TmpBB after CurBB.
1381 // Emit the LHS condition.
1382 FindMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc);
1384 // Emit the RHS condition into TmpBB.
1385 FindMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc);
1389 /// If the set of cases should be emitted as a series of branches, return true.
1390 /// If we should emit this as a bunch of and/or'd together conditions, return
1393 SelectionDAGBuilder::ShouldEmitAsBranches(const std::vector<CaseBlock> &Cases){
1394 if (Cases.size() != 2) return true;
1396 // If this is two comparisons of the same values or'd or and'd together, they
1397 // will get folded into a single comparison, so don't emit two blocks.
1398 if ((Cases[0].CmpLHS == Cases[1].CmpLHS &&
1399 Cases[0].CmpRHS == Cases[1].CmpRHS) ||
1400 (Cases[0].CmpRHS == Cases[1].CmpLHS &&
1401 Cases[0].CmpLHS == Cases[1].CmpRHS)) {
1405 // Handle: (X != null) | (Y != null) --> (X|Y) != 0
1406 // Handle: (X == null) & (Y == null) --> (X|Y) == 0
1407 if (Cases[0].CmpRHS == Cases[1].CmpRHS &&
1408 Cases[0].CC == Cases[1].CC &&
1409 isa<Constant>(Cases[0].CmpRHS) &&
1410 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) {
1411 if (Cases[0].CC == ISD::SETEQ && Cases[0].TrueBB == Cases[1].ThisBB)
1413 if (Cases[0].CC == ISD::SETNE && Cases[0].FalseBB == Cases[1].ThisBB)
1420 void SelectionDAGBuilder::visitBr(const BranchInst &I) {
1421 MachineBasicBlock *BrMBB = FuncInfo.MBB;
1423 // Update machine-CFG edges.
1424 MachineBasicBlock *Succ0MBB = FuncInfo.MBBMap[I.getSuccessor(0)];
1426 // Figure out which block is immediately after the current one.
1427 MachineBasicBlock *NextBlock = 0;
1428 MachineFunction::iterator BBI = BrMBB;
1429 if (++BBI != FuncInfo.MF->end())
1432 if (I.isUnconditional()) {
1433 // Update machine-CFG edges.
1434 BrMBB->addSuccessor(Succ0MBB);
1436 // If this is not a fall-through branch, emit the branch.
1437 if (Succ0MBB != NextBlock)
1438 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1439 MVT::Other, getControlRoot(),
1440 DAG.getBasicBlock(Succ0MBB)));
1445 // If this condition is one of the special cases we handle, do special stuff
1447 const Value *CondVal = I.getCondition();
1448 MachineBasicBlock *Succ1MBB = FuncInfo.MBBMap[I.getSuccessor(1)];
1450 // If this is a series of conditions that are or'd or and'd together, emit
1451 // this as a sequence of branches instead of setcc's with and/or operations.
1452 // As long as jumps are not expensive, this should improve performance.
1453 // For example, instead of something like:
1466 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) {
1467 if (!TLI.isJumpExpensive() &&
1469 (BOp->getOpcode() == Instruction::And ||
1470 BOp->getOpcode() == Instruction::Or)) {
1471 FindMergedConditions(BOp, Succ0MBB, Succ1MBB, BrMBB, BrMBB,
1473 // If the compares in later blocks need to use values not currently
1474 // exported from this block, export them now. This block should always
1475 // be the first entry.
1476 assert(SwitchCases[0].ThisBB == BrMBB && "Unexpected lowering!");
1478 // Allow some cases to be rejected.
1479 if (ShouldEmitAsBranches(SwitchCases)) {
1480 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i) {
1481 ExportFromCurrentBlock(SwitchCases[i].CmpLHS);
1482 ExportFromCurrentBlock(SwitchCases[i].CmpRHS);
1485 // Emit the branch for this block.
1486 visitSwitchCase(SwitchCases[0], BrMBB);
1487 SwitchCases.erase(SwitchCases.begin());
1491 // Okay, we decided not to do this, remove any inserted MBB's and clear
1493 for (unsigned i = 1, e = SwitchCases.size(); i != e; ++i)
1494 FuncInfo.MF->erase(SwitchCases[i].ThisBB);
1496 SwitchCases.clear();
1500 // Create a CaseBlock record representing this branch.
1501 CaseBlock CB(ISD::SETEQ, CondVal, ConstantInt::getTrue(*DAG.getContext()),
1502 NULL, Succ0MBB, Succ1MBB, BrMBB);
1504 // Use visitSwitchCase to actually insert the fast branch sequence for this
1506 visitSwitchCase(CB, BrMBB);
1509 /// visitSwitchCase - Emits the necessary code to represent a single node in
1510 /// the binary search tree resulting from lowering a switch instruction.
1511 void SelectionDAGBuilder::visitSwitchCase(CaseBlock &CB,
1512 MachineBasicBlock *SwitchBB) {
1514 SDValue CondLHS = getValue(CB.CmpLHS);
1515 DebugLoc dl = getCurDebugLoc();
1517 // Build the setcc now.
1518 if (CB.CmpMHS == NULL) {
1519 // Fold "(X == true)" to X and "(X == false)" to !X to
1520 // handle common cases produced by branch lowering.
1521 if (CB.CmpRHS == ConstantInt::getTrue(*DAG.getContext()) &&
1522 CB.CC == ISD::SETEQ)
1524 else if (CB.CmpRHS == ConstantInt::getFalse(*DAG.getContext()) &&
1525 CB.CC == ISD::SETEQ) {
1526 SDValue True = DAG.getConstant(1, CondLHS.getValueType());
1527 Cond = DAG.getNode(ISD::XOR, dl, CondLHS.getValueType(), CondLHS, True);
1529 Cond = DAG.getSetCC(dl, MVT::i1, CondLHS, getValue(CB.CmpRHS), CB.CC);
1531 assert(CB.CC == ISD::SETLE && "Can handle only LE ranges now");
1533 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue();
1534 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue();
1536 SDValue CmpOp = getValue(CB.CmpMHS);
1537 EVT VT = CmpOp.getValueType();
1539 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) {
1540 Cond = DAG.getSetCC(dl, MVT::i1, CmpOp, DAG.getConstant(High, VT),
1543 SDValue SUB = DAG.getNode(ISD::SUB, dl,
1544 VT, CmpOp, DAG.getConstant(Low, VT));
1545 Cond = DAG.getSetCC(dl, MVT::i1, SUB,
1546 DAG.getConstant(High-Low, VT), ISD::SETULE);
1550 // Update successor info
1551 SwitchBB->addSuccessor(CB.TrueBB);
1552 SwitchBB->addSuccessor(CB.FalseBB);
1554 // Set NextBlock to be the MBB immediately after the current one, if any.
1555 // This is used to avoid emitting unnecessary branches to the next block.
1556 MachineBasicBlock *NextBlock = 0;
1557 MachineFunction::iterator BBI = SwitchBB;
1558 if (++BBI != FuncInfo.MF->end())
1561 // If the lhs block is the next block, invert the condition so that we can
1562 // fall through to the lhs instead of the rhs block.
1563 if (CB.TrueBB == NextBlock) {
1564 std::swap(CB.TrueBB, CB.FalseBB);
1565 SDValue True = DAG.getConstant(1, Cond.getValueType());
1566 Cond = DAG.getNode(ISD::XOR, dl, Cond.getValueType(), Cond, True);
1569 SDValue BrCond = DAG.getNode(ISD::BRCOND, dl,
1570 MVT::Other, getControlRoot(), Cond,
1571 DAG.getBasicBlock(CB.TrueBB));
1573 // Insert the false branch. Do this even if it's a fall through branch,
1574 // this makes it easier to do DAG optimizations which require inverting
1575 // the branch condition.
1576 BrCond = DAG.getNode(ISD::BR, dl, MVT::Other, BrCond,
1577 DAG.getBasicBlock(CB.FalseBB));
1579 DAG.setRoot(BrCond);
1582 /// visitJumpTable - Emit JumpTable node in the current MBB
1583 void SelectionDAGBuilder::visitJumpTable(JumpTable &JT) {
1584 // Emit the code for the jump table
1585 assert(JT.Reg != -1U && "Should lower JT Header first!");
1586 EVT PTy = TLI.getPointerTy();
1587 SDValue Index = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1589 SDValue Table = DAG.getJumpTable(JT.JTI, PTy);
1590 SDValue BrJumpTable = DAG.getNode(ISD::BR_JT, getCurDebugLoc(),
1591 MVT::Other, Index.getValue(1),
1593 DAG.setRoot(BrJumpTable);
1596 /// visitJumpTableHeader - This function emits necessary code to produce index
1597 /// in the JumpTable from switch case.
1598 void SelectionDAGBuilder::visitJumpTableHeader(JumpTable &JT,
1599 JumpTableHeader &JTH,
1600 MachineBasicBlock *SwitchBB) {
1601 // Subtract the lowest switch case value from the value being switched on and
1602 // conditional branch to default mbb if the result is greater than the
1603 // difference between smallest and largest cases.
1604 SDValue SwitchOp = getValue(JTH.SValue);
1605 EVT VT = SwitchOp.getValueType();
1606 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1607 DAG.getConstant(JTH.First, VT));
1609 // The SDNode we just created, which holds the value being switched on minus
1610 // the smallest case value, needs to be copied to a virtual register so it
1611 // can be used as an index into the jump table in a subsequent basic block.
1612 // This value may be smaller or larger than the target's pointer type, and
1613 // therefore require extension or truncating.
1614 SwitchOp = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), TLI.getPointerTy());
1616 unsigned JumpTableReg = FuncInfo.CreateReg(TLI.getPointerTy());
1617 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1618 JumpTableReg, SwitchOp);
1619 JT.Reg = JumpTableReg;
1621 // Emit the range check for the jump table, and branch to the default block
1622 // for the switch statement if the value being switched on exceeds the largest
1623 // case in the switch.
1624 SDValue CMP = DAG.getSetCC(getCurDebugLoc(),
1625 TLI.getSetCCResultType(Sub.getValueType()), Sub,
1626 DAG.getConstant(JTH.Last-JTH.First,VT),
1629 // Set NextBlock to be the MBB immediately after the current one, if any.
1630 // This is used to avoid emitting unnecessary branches to the next block.
1631 MachineBasicBlock *NextBlock = 0;
1632 MachineFunction::iterator BBI = SwitchBB;
1634 if (++BBI != FuncInfo.MF->end())
1637 SDValue BrCond = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1638 MVT::Other, CopyTo, CMP,
1639 DAG.getBasicBlock(JT.Default));
1641 if (JT.MBB != NextBlock)
1642 BrCond = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrCond,
1643 DAG.getBasicBlock(JT.MBB));
1645 DAG.setRoot(BrCond);
1648 /// visitBitTestHeader - This function emits necessary code to produce value
1649 /// suitable for "bit tests"
1650 void SelectionDAGBuilder::visitBitTestHeader(BitTestBlock &B,
1651 MachineBasicBlock *SwitchBB) {
1652 // Subtract the minimum value
1653 SDValue SwitchOp = getValue(B.SValue);
1654 EVT VT = SwitchOp.getValueType();
1655 SDValue Sub = DAG.getNode(ISD::SUB, getCurDebugLoc(), VT, SwitchOp,
1656 DAG.getConstant(B.First, VT));
1659 SDValue RangeCmp = DAG.getSetCC(getCurDebugLoc(),
1660 TLI.getSetCCResultType(Sub.getValueType()),
1661 Sub, DAG.getConstant(B.Range, VT),
1664 // Determine the type of the test operands.
1665 bool UsePtrType = false;
1666 if (!TLI.isTypeLegal(VT))
1669 for (unsigned i = 0, e = B.Cases.size(); i != e; ++i)
1670 if ((uint64_t)((int64_t)B.Cases[i].Mask >> VT.getSizeInBits()) + 1 >= 2) {
1671 // Switch table case range are encoded into series of masks.
1672 // Just use pointer type, it's guaranteed to fit.
1678 VT = TLI.getPointerTy();
1679 Sub = DAG.getZExtOrTrunc(Sub, getCurDebugLoc(), VT);
1683 B.Reg = FuncInfo.CreateReg(VT);
1684 SDValue CopyTo = DAG.getCopyToReg(getControlRoot(), getCurDebugLoc(),
1687 // Set NextBlock to be the MBB immediately after the current one, if any.
1688 // This is used to avoid emitting unnecessary branches to the next block.
1689 MachineBasicBlock *NextBlock = 0;
1690 MachineFunction::iterator BBI = SwitchBB;
1691 if (++BBI != FuncInfo.MF->end())
1694 MachineBasicBlock* MBB = B.Cases[0].ThisBB;
1696 SwitchBB->addSuccessor(B.Default);
1697 SwitchBB->addSuccessor(MBB);
1699 SDValue BrRange = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1700 MVT::Other, CopyTo, RangeCmp,
1701 DAG.getBasicBlock(B.Default));
1703 if (MBB != NextBlock)
1704 BrRange = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, CopyTo,
1705 DAG.getBasicBlock(MBB));
1707 DAG.setRoot(BrRange);
1710 /// visitBitTestCase - this function produces one "bit test"
1711 void SelectionDAGBuilder::visitBitTestCase(BitTestBlock &BB,
1712 MachineBasicBlock* NextMBB,
1715 MachineBasicBlock *SwitchBB) {
1717 SDValue ShiftOp = DAG.getCopyFromReg(getControlRoot(), getCurDebugLoc(),
1720 if (CountPopulation_64(B.Mask) == 1) {
1721 // Testing for a single bit; just compare the shift count with what it
1722 // would need to be to shift a 1 bit in that position.
1723 Cmp = DAG.getSetCC(getCurDebugLoc(),
1724 TLI.getSetCCResultType(VT),
1726 DAG.getConstant(CountTrailingZeros_64(B.Mask), VT),
1729 // Make desired shift
1730 SDValue SwitchVal = DAG.getNode(ISD::SHL, getCurDebugLoc(), VT,
1731 DAG.getConstant(1, VT), ShiftOp);
1733 // Emit bit tests and jumps
1734 SDValue AndOp = DAG.getNode(ISD::AND, getCurDebugLoc(),
1735 VT, SwitchVal, DAG.getConstant(B.Mask, VT));
1736 Cmp = DAG.getSetCC(getCurDebugLoc(),
1737 TLI.getSetCCResultType(VT),
1738 AndOp, DAG.getConstant(0, VT),
1742 SwitchBB->addSuccessor(B.TargetBB);
1743 SwitchBB->addSuccessor(NextMBB);
1745 SDValue BrAnd = DAG.getNode(ISD::BRCOND, getCurDebugLoc(),
1746 MVT::Other, getControlRoot(),
1747 Cmp, DAG.getBasicBlock(B.TargetBB));
1749 // Set NextBlock to be the MBB immediately after the current one, if any.
1750 // This is used to avoid emitting unnecessary branches to the next block.
1751 MachineBasicBlock *NextBlock = 0;
1752 MachineFunction::iterator BBI = SwitchBB;
1753 if (++BBI != FuncInfo.MF->end())
1756 if (NextMBB != NextBlock)
1757 BrAnd = DAG.getNode(ISD::BR, getCurDebugLoc(), MVT::Other, BrAnd,
1758 DAG.getBasicBlock(NextMBB));
1763 void SelectionDAGBuilder::visitInvoke(const InvokeInst &I) {
1764 MachineBasicBlock *InvokeMBB = FuncInfo.MBB;
1766 // Retrieve successors.
1767 MachineBasicBlock *Return = FuncInfo.MBBMap[I.getSuccessor(0)];
1768 MachineBasicBlock *LandingPad = FuncInfo.MBBMap[I.getSuccessor(1)];
1770 const Value *Callee(I.getCalledValue());
1771 if (isa<InlineAsm>(Callee))
1774 LowerCallTo(&I, getValue(Callee), false, LandingPad);
1776 // If the value of the invoke is used outside of its defining block, make it
1777 // available as a virtual register.
1778 CopyToExportRegsIfNeeded(&I);
1780 // Update successor info
1781 InvokeMBB->addSuccessor(Return);
1782 InvokeMBB->addSuccessor(LandingPad);
1784 // Drop into normal successor.
1785 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
1786 MVT::Other, getControlRoot(),
1787 DAG.getBasicBlock(Return)));
1790 void SelectionDAGBuilder::visitUnwind(const UnwindInst &I) {
1793 /// handleSmallSwitchCaseRange - Emit a series of specific tests (suitable for
1794 /// small case ranges).
1795 bool SelectionDAGBuilder::handleSmallSwitchRange(CaseRec& CR,
1796 CaseRecVector& WorkList,
1798 MachineBasicBlock *Default,
1799 MachineBasicBlock *SwitchBB) {
1800 Case& BackCase = *(CR.Range.second-1);
1802 // Size is the number of Cases represented by this range.
1803 size_t Size = CR.Range.second - CR.Range.first;
1807 // Get the MachineFunction which holds the current MBB. This is used when
1808 // inserting any additional MBBs necessary to represent the switch.
1809 MachineFunction *CurMF = FuncInfo.MF;
1811 // Figure out which block is immediately after the current one.
1812 MachineBasicBlock *NextBlock = 0;
1813 MachineFunction::iterator BBI = CR.CaseBB;
1815 if (++BBI != FuncInfo.MF->end())
1818 // If any two of the cases has the same destination, and if one value
1819 // is the same as the other, but has one bit unset that the other has set,
1820 // use bit manipulation to do two compares at once. For example:
1821 // "if (X == 6 || X == 4)" -> "if ((X|2) == 6)"
1822 // TODO: This could be extended to merge any 2 cases in switches with 3 cases.
1823 // TODO: Handle cases where CR.CaseBB != SwitchBB.
1824 if (Size == 2 && CR.CaseBB == SwitchBB) {
1825 Case &Small = *CR.Range.first;
1826 Case &Big = *(CR.Range.second-1);
1828 if (Small.Low == Small.High && Big.Low == Big.High && Small.BB == Big.BB) {
1829 const APInt& SmallValue = cast<ConstantInt>(Small.Low)->getValue();
1830 const APInt& BigValue = cast<ConstantInt>(Big.Low)->getValue();
1832 // Check that there is only one bit different.
1833 if (BigValue.countPopulation() == SmallValue.countPopulation() + 1 &&
1834 (SmallValue | BigValue) == BigValue) {
1835 // Isolate the common bit.
1836 APInt CommonBit = BigValue & ~SmallValue;
1837 assert((SmallValue | CommonBit) == BigValue &&
1838 CommonBit.countPopulation() == 1 && "Not a common bit?");
1840 SDValue CondLHS = getValue(SV);
1841 EVT VT = CondLHS.getValueType();
1842 DebugLoc DL = getCurDebugLoc();
1844 SDValue Or = DAG.getNode(ISD::OR, DL, VT, CondLHS,
1845 DAG.getConstant(CommonBit, VT));
1846 SDValue Cond = DAG.getSetCC(DL, MVT::i1,
1847 Or, DAG.getConstant(BigValue, VT),
1850 // Update successor info.
1851 SwitchBB->addSuccessor(Small.BB);
1852 SwitchBB->addSuccessor(Default);
1854 // Insert the true branch.
1855 SDValue BrCond = DAG.getNode(ISD::BRCOND, DL, MVT::Other,
1856 getControlRoot(), Cond,
1857 DAG.getBasicBlock(Small.BB));
1859 // Insert the false branch.
1860 BrCond = DAG.getNode(ISD::BR, DL, MVT::Other, BrCond,
1861 DAG.getBasicBlock(Default));
1863 DAG.setRoot(BrCond);
1869 // Rearrange the case blocks so that the last one falls through if possible.
1870 if (NextBlock && Default != NextBlock && BackCase.BB != NextBlock) {
1871 // The last case block won't fall through into 'NextBlock' if we emit the
1872 // branches in this order. See if rearranging a case value would help.
1873 for (CaseItr I = CR.Range.first, E = CR.Range.second-1; I != E; ++I) {
1874 if (I->BB == NextBlock) {
1875 std::swap(*I, BackCase);
1881 // Create a CaseBlock record representing a conditional branch to
1882 // the Case's target mbb if the value being switched on SV is equal
1884 MachineBasicBlock *CurBlock = CR.CaseBB;
1885 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++I) {
1886 MachineBasicBlock *FallThrough;
1888 FallThrough = CurMF->CreateMachineBasicBlock(CurBlock->getBasicBlock());
1889 CurMF->insert(BBI, FallThrough);
1891 // Put SV in a virtual register to make it available from the new blocks.
1892 ExportFromCurrentBlock(SV);
1894 // If the last case doesn't match, go to the default block.
1895 FallThrough = Default;
1898 const Value *RHS, *LHS, *MHS;
1900 if (I->High == I->Low) {
1901 // This is just small small case range :) containing exactly 1 case
1903 LHS = SV; RHS = I->High; MHS = NULL;
1906 LHS = I->Low; MHS = SV; RHS = I->High;
1908 CaseBlock CB(CC, LHS, RHS, MHS, I->BB, FallThrough, CurBlock);
1910 // If emitting the first comparison, just call visitSwitchCase to emit the
1911 // code into the current block. Otherwise, push the CaseBlock onto the
1912 // vector to be later processed by SDISel, and insert the node's MBB
1913 // before the next MBB.
1914 if (CurBlock == SwitchBB)
1915 visitSwitchCase(CB, SwitchBB);
1917 SwitchCases.push_back(CB);
1919 CurBlock = FallThrough;
1925 static inline bool areJTsAllowed(const TargetLowering &TLI) {
1926 return !DisableJumpTables &&
1927 (TLI.isOperationLegalOrCustom(ISD::BR_JT, MVT::Other) ||
1928 TLI.isOperationLegalOrCustom(ISD::BRIND, MVT::Other));
1931 static APInt ComputeRange(const APInt &First, const APInt &Last) {
1932 uint32_t BitWidth = std::max(Last.getBitWidth(), First.getBitWidth()) + 1;
1933 APInt LastExt = Last.sext(BitWidth), FirstExt = First.sext(BitWidth);
1934 return (LastExt - FirstExt + 1ULL);
1937 /// handleJTSwitchCase - Emit jumptable for current switch case range
1938 bool SelectionDAGBuilder::handleJTSwitchCase(CaseRec& CR,
1939 CaseRecVector& WorkList,
1941 MachineBasicBlock* Default,
1942 MachineBasicBlock *SwitchBB) {
1943 Case& FrontCase = *CR.Range.first;
1944 Case& BackCase = *(CR.Range.second-1);
1946 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
1947 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
1949 APInt TSize(First.getBitWidth(), 0);
1950 for (CaseItr I = CR.Range.first, E = CR.Range.second;
1954 if (!areJTsAllowed(TLI) || TSize.ult(4))
1957 APInt Range = ComputeRange(First, Last);
1958 double Density = TSize.roundToDouble() / Range.roundToDouble();
1962 DEBUG(dbgs() << "Lowering jump table\n"
1963 << "First entry: " << First << ". Last entry: " << Last << '\n'
1964 << "Range: " << Range
1965 << ". Size: " << TSize << ". Density: " << Density << "\n\n");
1967 // Get the MachineFunction which holds the current MBB. This is used when
1968 // inserting any additional MBBs necessary to represent the switch.
1969 MachineFunction *CurMF = FuncInfo.MF;
1971 // Figure out which block is immediately after the current one.
1972 MachineFunction::iterator BBI = CR.CaseBB;
1975 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
1977 // Create a new basic block to hold the code for loading the address
1978 // of the jump table, and jumping to it. Update successor information;
1979 // we will either branch to the default case for the switch, or the jump
1981 MachineBasicBlock *JumpTableBB = CurMF->CreateMachineBasicBlock(LLVMBB);
1982 CurMF->insert(BBI, JumpTableBB);
1983 CR.CaseBB->addSuccessor(Default);
1984 CR.CaseBB->addSuccessor(JumpTableBB);
1986 // Build a vector of destination BBs, corresponding to each target
1987 // of the jump table. If the value of the jump table slot corresponds to
1988 // a case statement, push the case's BB onto the vector, otherwise, push
1990 std::vector<MachineBasicBlock*> DestBBs;
1992 for (CaseItr I = CR.Range.first, E = CR.Range.second; I != E; ++TEI) {
1993 const APInt &Low = cast<ConstantInt>(I->Low)->getValue();
1994 const APInt &High = cast<ConstantInt>(I->High)->getValue();
1996 if (Low.sle(TEI) && TEI.sle(High)) {
1997 DestBBs.push_back(I->BB);
2001 DestBBs.push_back(Default);
2005 // Update successor info. Add one edge to each unique successor.
2006 BitVector SuccsHandled(CR.CaseBB->getParent()->getNumBlockIDs());
2007 for (std::vector<MachineBasicBlock*>::iterator I = DestBBs.begin(),
2008 E = DestBBs.end(); I != E; ++I) {
2009 if (!SuccsHandled[(*I)->getNumber()]) {
2010 SuccsHandled[(*I)->getNumber()] = true;
2011 JumpTableBB->addSuccessor(*I);
2015 // Create a jump table index for this jump table.
2016 unsigned JTEncoding = TLI.getJumpTableEncoding();
2017 unsigned JTI = CurMF->getOrCreateJumpTableInfo(JTEncoding)
2018 ->createJumpTableIndex(DestBBs);
2020 // Set the jump table information so that we can codegen it as a second
2021 // MachineBasicBlock
2022 JumpTable JT(-1U, JTI, JumpTableBB, Default);
2023 JumpTableHeader JTH(First, Last, SV, CR.CaseBB, (CR.CaseBB == SwitchBB));
2024 if (CR.CaseBB == SwitchBB)
2025 visitJumpTableHeader(JT, JTH, SwitchBB);
2027 JTCases.push_back(JumpTableBlock(JTH, JT));
2032 /// handleBTSplitSwitchCase - emit comparison and split binary search tree into
2034 bool SelectionDAGBuilder::handleBTSplitSwitchCase(CaseRec& CR,
2035 CaseRecVector& WorkList,
2037 MachineBasicBlock *Default,
2038 MachineBasicBlock *SwitchBB) {
2039 // Get the MachineFunction which holds the current MBB. This is used when
2040 // inserting any additional MBBs necessary to represent the switch.
2041 MachineFunction *CurMF = FuncInfo.MF;
2043 // Figure out which block is immediately after the current one.
2044 MachineFunction::iterator BBI = CR.CaseBB;
2047 Case& FrontCase = *CR.Range.first;
2048 Case& BackCase = *(CR.Range.second-1);
2049 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2051 // Size is the number of Cases represented by this range.
2052 unsigned Size = CR.Range.second - CR.Range.first;
2054 const APInt &First = cast<ConstantInt>(FrontCase.Low)->getValue();
2055 const APInt &Last = cast<ConstantInt>(BackCase.High)->getValue();
2057 CaseItr Pivot = CR.Range.first + Size/2;
2059 // Select optimal pivot, maximizing sum density of LHS and RHS. This will
2060 // (heuristically) allow us to emit JumpTable's later.
2061 APInt TSize(First.getBitWidth(), 0);
2062 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2066 APInt LSize = FrontCase.size();
2067 APInt RSize = TSize-LSize;
2068 DEBUG(dbgs() << "Selecting best pivot: \n"
2069 << "First: " << First << ", Last: " << Last <<'\n'
2070 << "LSize: " << LSize << ", RSize: " << RSize << '\n');
2071 for (CaseItr I = CR.Range.first, J=I+1, E = CR.Range.second;
2073 const APInt &LEnd = cast<ConstantInt>(I->High)->getValue();
2074 const APInt &RBegin = cast<ConstantInt>(J->Low)->getValue();
2075 APInt Range = ComputeRange(LEnd, RBegin);
2076 assert((Range - 2ULL).isNonNegative() &&
2077 "Invalid case distance");
2078 // Use volatile double here to avoid excess precision issues on some hosts,
2079 // e.g. that use 80-bit X87 registers.
2080 volatile double LDensity =
2081 (double)LSize.roundToDouble() /
2082 (LEnd - First + 1ULL).roundToDouble();
2083 volatile double RDensity =
2084 (double)RSize.roundToDouble() /
2085 (Last - RBegin + 1ULL).roundToDouble();
2086 double Metric = Range.logBase2()*(LDensity+RDensity);
2087 // Should always split in some non-trivial place
2088 DEBUG(dbgs() <<"=>Step\n"
2089 << "LEnd: " << LEnd << ", RBegin: " << RBegin << '\n'
2090 << "LDensity: " << LDensity
2091 << ", RDensity: " << RDensity << '\n'
2092 << "Metric: " << Metric << '\n');
2093 if (FMetric < Metric) {
2096 DEBUG(dbgs() << "Current metric set to: " << FMetric << '\n');
2102 if (areJTsAllowed(TLI)) {
2103 // If our case is dense we *really* should handle it earlier!
2104 assert((FMetric > 0) && "Should handle dense range earlier!");
2106 Pivot = CR.Range.first + Size/2;
2109 CaseRange LHSR(CR.Range.first, Pivot);
2110 CaseRange RHSR(Pivot, CR.Range.second);
2111 Constant *C = Pivot->Low;
2112 MachineBasicBlock *FalseBB = 0, *TrueBB = 0;
2114 // We know that we branch to the LHS if the Value being switched on is
2115 // less than the Pivot value, C. We use this to optimize our binary
2116 // tree a bit, by recognizing that if SV is greater than or equal to the
2117 // LHS's Case Value, and that Case Value is exactly one less than the
2118 // Pivot's Value, then we can branch directly to the LHS's Target,
2119 // rather than creating a leaf node for it.
2120 if ((LHSR.second - LHSR.first) == 1 &&
2121 LHSR.first->High == CR.GE &&
2122 cast<ConstantInt>(C)->getValue() ==
2123 (cast<ConstantInt>(CR.GE)->getValue() + 1LL)) {
2124 TrueBB = LHSR.first->BB;
2126 TrueBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2127 CurMF->insert(BBI, TrueBB);
2128 WorkList.push_back(CaseRec(TrueBB, C, CR.GE, LHSR));
2130 // Put SV in a virtual register to make it available from the new blocks.
2131 ExportFromCurrentBlock(SV);
2134 // Similar to the optimization above, if the Value being switched on is
2135 // known to be less than the Constant CR.LT, and the current Case Value
2136 // is CR.LT - 1, then we can branch directly to the target block for
2137 // the current Case Value, rather than emitting a RHS leaf node for it.
2138 if ((RHSR.second - RHSR.first) == 1 && CR.LT &&
2139 cast<ConstantInt>(RHSR.first->Low)->getValue() ==
2140 (cast<ConstantInt>(CR.LT)->getValue() - 1LL)) {
2141 FalseBB = RHSR.first->BB;
2143 FalseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2144 CurMF->insert(BBI, FalseBB);
2145 WorkList.push_back(CaseRec(FalseBB,CR.LT,C,RHSR));
2147 // Put SV in a virtual register to make it available from the new blocks.
2148 ExportFromCurrentBlock(SV);
2151 // Create a CaseBlock record representing a conditional branch to
2152 // the LHS node if the value being switched on SV is less than C.
2153 // Otherwise, branch to LHS.
2154 CaseBlock CB(ISD::SETLT, SV, C, NULL, TrueBB, FalseBB, CR.CaseBB);
2156 if (CR.CaseBB == SwitchBB)
2157 visitSwitchCase(CB, SwitchBB);
2159 SwitchCases.push_back(CB);
2164 /// handleBitTestsSwitchCase - if current case range has few destination and
2165 /// range span less, than machine word bitwidth, encode case range into series
2166 /// of masks and emit bit tests with these masks.
2167 bool SelectionDAGBuilder::handleBitTestsSwitchCase(CaseRec& CR,
2168 CaseRecVector& WorkList,
2170 MachineBasicBlock* Default,
2171 MachineBasicBlock *SwitchBB){
2172 EVT PTy = TLI.getPointerTy();
2173 unsigned IntPtrBits = PTy.getSizeInBits();
2175 Case& FrontCase = *CR.Range.first;
2176 Case& BackCase = *(CR.Range.second-1);
2178 // Get the MachineFunction which holds the current MBB. This is used when
2179 // inserting any additional MBBs necessary to represent the switch.
2180 MachineFunction *CurMF = FuncInfo.MF;
2182 // If target does not have legal shift left, do not emit bit tests at all.
2183 if (!TLI.isOperationLegal(ISD::SHL, TLI.getPointerTy()))
2187 for (CaseItr I = CR.Range.first, E = CR.Range.second;
2189 // Single case counts one, case range - two.
2190 numCmps += (I->Low == I->High ? 1 : 2);
2193 // Count unique destinations
2194 SmallSet<MachineBasicBlock*, 4> Dests;
2195 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2196 Dests.insert(I->BB);
2197 if (Dests.size() > 3)
2198 // Don't bother the code below, if there are too much unique destinations
2201 DEBUG(dbgs() << "Total number of unique destinations: "
2202 << Dests.size() << '\n'
2203 << "Total number of comparisons: " << numCmps << '\n');
2205 // Compute span of values.
2206 const APInt& minValue = cast<ConstantInt>(FrontCase.Low)->getValue();
2207 const APInt& maxValue = cast<ConstantInt>(BackCase.High)->getValue();
2208 APInt cmpRange = maxValue - minValue;
2210 DEBUG(dbgs() << "Compare range: " << cmpRange << '\n'
2211 << "Low bound: " << minValue << '\n'
2212 << "High bound: " << maxValue << '\n');
2214 if (cmpRange.uge(IntPtrBits) ||
2215 (!(Dests.size() == 1 && numCmps >= 3) &&
2216 !(Dests.size() == 2 && numCmps >= 5) &&
2217 !(Dests.size() >= 3 && numCmps >= 6)))
2220 DEBUG(dbgs() << "Emitting bit tests\n");
2221 APInt lowBound = APInt::getNullValue(cmpRange.getBitWidth());
2223 // Optimize the case where all the case values fit in a
2224 // word without having to subtract minValue. In this case,
2225 // we can optimize away the subtraction.
2226 if (minValue.isNonNegative() && maxValue.slt(IntPtrBits)) {
2227 cmpRange = maxValue;
2229 lowBound = minValue;
2232 CaseBitsVector CasesBits;
2233 unsigned i, count = 0;
2235 for (CaseItr I = CR.Range.first, E = CR.Range.second; I!=E; ++I) {
2236 MachineBasicBlock* Dest = I->BB;
2237 for (i = 0; i < count; ++i)
2238 if (Dest == CasesBits[i].BB)
2242 assert((count < 3) && "Too much destinations to test!");
2243 CasesBits.push_back(CaseBits(0, Dest, 0));
2247 const APInt& lowValue = cast<ConstantInt>(I->Low)->getValue();
2248 const APInt& highValue = cast<ConstantInt>(I->High)->getValue();
2250 uint64_t lo = (lowValue - lowBound).getZExtValue();
2251 uint64_t hi = (highValue - lowBound).getZExtValue();
2253 for (uint64_t j = lo; j <= hi; j++) {
2254 CasesBits[i].Mask |= 1ULL << j;
2255 CasesBits[i].Bits++;
2259 std::sort(CasesBits.begin(), CasesBits.end(), CaseBitsCmp());
2263 // Figure out which block is immediately after the current one.
2264 MachineFunction::iterator BBI = CR.CaseBB;
2267 const BasicBlock *LLVMBB = CR.CaseBB->getBasicBlock();
2269 DEBUG(dbgs() << "Cases:\n");
2270 for (unsigned i = 0, e = CasesBits.size(); i!=e; ++i) {
2271 DEBUG(dbgs() << "Mask: " << CasesBits[i].Mask
2272 << ", Bits: " << CasesBits[i].Bits
2273 << ", BB: " << CasesBits[i].BB << '\n');
2275 MachineBasicBlock *CaseBB = CurMF->CreateMachineBasicBlock(LLVMBB);
2276 CurMF->insert(BBI, CaseBB);
2277 BTC.push_back(BitTestCase(CasesBits[i].Mask,
2281 // Put SV in a virtual register to make it available from the new blocks.
2282 ExportFromCurrentBlock(SV);
2285 BitTestBlock BTB(lowBound, cmpRange, SV,
2286 -1U, MVT::Other, (CR.CaseBB == SwitchBB),
2287 CR.CaseBB, Default, BTC);
2289 if (CR.CaseBB == SwitchBB)
2290 visitBitTestHeader(BTB, SwitchBB);
2292 BitTestCases.push_back(BTB);
2297 /// Clusterify - Transform simple list of Cases into list of CaseRange's
2298 size_t SelectionDAGBuilder::Clusterify(CaseVector& Cases,
2299 const SwitchInst& SI) {
2302 // Start with "simple" cases
2303 for (size_t i = 1; i < SI.getNumSuccessors(); ++i) {
2304 MachineBasicBlock *SMBB = FuncInfo.MBBMap[SI.getSuccessor(i)];
2305 Cases.push_back(Case(SI.getSuccessorValue(i),
2306 SI.getSuccessorValue(i),
2309 std::sort(Cases.begin(), Cases.end(), CaseCmp());
2311 // Merge case into clusters
2312 if (Cases.size() >= 2)
2313 // Must recompute end() each iteration because it may be
2314 // invalidated by erase if we hold on to it
2315 for (CaseItr I = Cases.begin(), J = llvm::next(Cases.begin());
2316 J != Cases.end(); ) {
2317 const APInt& nextValue = cast<ConstantInt>(J->Low)->getValue();
2318 const APInt& currentValue = cast<ConstantInt>(I->High)->getValue();
2319 MachineBasicBlock* nextBB = J->BB;
2320 MachineBasicBlock* currentBB = I->BB;
2322 // If the two neighboring cases go to the same destination, merge them
2323 // into a single case.
2324 if ((nextValue - currentValue == 1) && (currentBB == nextBB)) {
2332 for (CaseItr I=Cases.begin(), E=Cases.end(); I!=E; ++I, ++numCmps) {
2333 if (I->Low != I->High)
2334 // A range counts double, since it requires two compares.
2341 void SelectionDAGBuilder::UpdateSplitBlock(MachineBasicBlock *First,
2342 MachineBasicBlock *Last) {
2344 for (unsigned i = 0, e = JTCases.size(); i != e; ++i)
2345 if (JTCases[i].first.HeaderBB == First)
2346 JTCases[i].first.HeaderBB = Last;
2348 // Update BitTestCases.
2349 for (unsigned i = 0, e = BitTestCases.size(); i != e; ++i)
2350 if (BitTestCases[i].Parent == First)
2351 BitTestCases[i].Parent = Last;
2354 void SelectionDAGBuilder::visitSwitch(const SwitchInst &SI) {
2355 MachineBasicBlock *SwitchMBB = FuncInfo.MBB;
2357 // Figure out which block is immediately after the current one.
2358 MachineBasicBlock *NextBlock = 0;
2359 MachineBasicBlock *Default = FuncInfo.MBBMap[SI.getDefaultDest()];
2361 // If there is only the default destination, branch to it if it is not the
2362 // next basic block. Otherwise, just fall through.
2363 if (SI.getNumOperands() == 2) {
2364 // Update machine-CFG edges.
2366 // If this is not a fall-through branch, emit the branch.
2367 SwitchMBB->addSuccessor(Default);
2368 if (Default != NextBlock)
2369 DAG.setRoot(DAG.getNode(ISD::BR, getCurDebugLoc(),
2370 MVT::Other, getControlRoot(),
2371 DAG.getBasicBlock(Default)));
2376 // If there are any non-default case statements, create a vector of Cases
2377 // representing each one, and sort the vector so that we can efficiently
2378 // create a binary search tree from them.
2380 size_t numCmps = Clusterify(Cases, SI);
2381 DEBUG(dbgs() << "Clusterify finished. Total clusters: " << Cases.size()
2382 << ". Total compares: " << numCmps << '\n');
2385 // Get the Value to be switched on and default basic blocks, which will be
2386 // inserted into CaseBlock records, representing basic blocks in the binary
2388 const Value *SV = SI.getOperand(0);
2390 // Push the initial CaseRec onto the worklist
2391 CaseRecVector WorkList;
2392 WorkList.push_back(CaseRec(SwitchMBB,0,0,
2393 CaseRange(Cases.begin(),Cases.end())));
2395 while (!WorkList.empty()) {
2396 // Grab a record representing a case range to process off the worklist
2397 CaseRec CR = WorkList.back();
2398 WorkList.pop_back();
2400 if (handleBitTestsSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2403 // If the range has few cases (two or less) emit a series of specific
2405 if (handleSmallSwitchRange(CR, WorkList, SV, Default, SwitchMBB))
2408 // If the switch has more than 5 blocks, and at least 40% dense, and the
2409 // target supports indirect branches, then emit a jump table rather than
2410 // lowering the switch to a binary tree of conditional branches.
2411 if (handleJTSwitchCase(CR, WorkList, SV, Default, SwitchMBB))
2414 // Emit binary tree. We need to pick a pivot, and push left and right ranges
2415 // onto the worklist. Leafs are handled via handleSmallSwitchRange() call.
2416 handleBTSplitSwitchCase(CR, WorkList, SV, Default, SwitchMBB);
2420 void SelectionDAGBuilder::visitIndirectBr(const IndirectBrInst &I) {
2421 MachineBasicBlock *IndirectBrMBB = FuncInfo.MBB;
2423 // Update machine-CFG edges with unique successors.
2424 SmallVector<BasicBlock*, 32> succs;
2425 succs.reserve(I.getNumSuccessors());
2426 for (unsigned i = 0, e = I.getNumSuccessors(); i != e; ++i)
2427 succs.push_back(I.getSuccessor(i));
2428 array_pod_sort(succs.begin(), succs.end());
2429 succs.erase(std::unique(succs.begin(), succs.end()), succs.end());
2430 for (unsigned i = 0, e = succs.size(); i != e; ++i)
2431 IndirectBrMBB->addSuccessor(FuncInfo.MBBMap[succs[i]]);
2433 DAG.setRoot(DAG.getNode(ISD::BRIND, getCurDebugLoc(),
2434 MVT::Other, getControlRoot(),
2435 getValue(I.getAddress())));
2438 void SelectionDAGBuilder::visitFSub(const User &I) {
2439 // -0.0 - X --> fneg
2440 const Type *Ty = I.getType();
2441 if (isa<Constant>(I.getOperand(0)) &&
2442 I.getOperand(0) == ConstantFP::getZeroValueForNegation(Ty)) {
2443 SDValue Op2 = getValue(I.getOperand(1));
2444 setValue(&I, DAG.getNode(ISD::FNEG, getCurDebugLoc(),
2445 Op2.getValueType(), Op2));
2449 visitBinary(I, ISD::FSUB);
2452 void SelectionDAGBuilder::visitBinary(const User &I, unsigned OpCode) {
2453 SDValue Op1 = getValue(I.getOperand(0));
2454 SDValue Op2 = getValue(I.getOperand(1));
2455 setValue(&I, DAG.getNode(OpCode, getCurDebugLoc(),
2456 Op1.getValueType(), Op1, Op2));
2459 void SelectionDAGBuilder::visitShift(const User &I, unsigned Opcode) {
2460 SDValue Op1 = getValue(I.getOperand(0));
2461 SDValue Op2 = getValue(I.getOperand(1));
2463 MVT ShiftTy = TLI.getShiftAmountTy(Op2.getValueType());
2465 // Coerce the shift amount to the right type if we can.
2466 if (!I.getType()->isVectorTy() && Op2.getValueType() != ShiftTy) {
2467 unsigned ShiftSize = ShiftTy.getSizeInBits();
2468 unsigned Op2Size = Op2.getValueType().getSizeInBits();
2469 DebugLoc DL = getCurDebugLoc();
2471 // If the operand is smaller than the shift count type, promote it.
2472 if (ShiftSize > Op2Size)
2473 Op2 = DAG.getNode(ISD::ZERO_EXTEND, DL, ShiftTy, Op2);
2475 // If the operand is larger than the shift count type but the shift
2476 // count type has enough bits to represent any shift value, truncate
2477 // it now. This is a common case and it exposes the truncate to
2478 // optimization early.
2479 else if (ShiftSize >= Log2_32_Ceil(Op2.getValueType().getSizeInBits()))
2480 Op2 = DAG.getNode(ISD::TRUNCATE, DL, ShiftTy, Op2);
2481 // Otherwise we'll need to temporarily settle for some other convenient
2482 // type. Type legalization will make adjustments once the shiftee is split.
2484 Op2 = DAG.getZExtOrTrunc(Op2, DL, MVT::i32);
2487 setValue(&I, DAG.getNode(Opcode, getCurDebugLoc(),
2488 Op1.getValueType(), Op1, Op2));
2491 void SelectionDAGBuilder::visitICmp(const User &I) {
2492 ICmpInst::Predicate predicate = ICmpInst::BAD_ICMP_PREDICATE;
2493 if (const ICmpInst *IC = dyn_cast<ICmpInst>(&I))
2494 predicate = IC->getPredicate();
2495 else if (const ConstantExpr *IC = dyn_cast<ConstantExpr>(&I))
2496 predicate = ICmpInst::Predicate(IC->getPredicate());
2497 SDValue Op1 = getValue(I.getOperand(0));
2498 SDValue Op2 = getValue(I.getOperand(1));
2499 ISD::CondCode Opcode = getICmpCondCode(predicate);
2501 EVT DestVT = TLI.getValueType(I.getType());
2502 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Opcode));
2505 void SelectionDAGBuilder::visitFCmp(const User &I) {
2506 FCmpInst::Predicate predicate = FCmpInst::BAD_FCMP_PREDICATE;
2507 if (const FCmpInst *FC = dyn_cast<FCmpInst>(&I))
2508 predicate = FC->getPredicate();
2509 else if (const ConstantExpr *FC = dyn_cast<ConstantExpr>(&I))
2510 predicate = FCmpInst::Predicate(FC->getPredicate());
2511 SDValue Op1 = getValue(I.getOperand(0));
2512 SDValue Op2 = getValue(I.getOperand(1));
2513 ISD::CondCode Condition = getFCmpCondCode(predicate);
2514 EVT DestVT = TLI.getValueType(I.getType());
2515 setValue(&I, DAG.getSetCC(getCurDebugLoc(), DestVT, Op1, Op2, Condition));
2518 void SelectionDAGBuilder::visitSelect(const User &I) {
2519 SmallVector<EVT, 4> ValueVTs;
2520 ComputeValueVTs(TLI, I.getType(), ValueVTs);
2521 unsigned NumValues = ValueVTs.size();
2522 if (NumValues == 0) return;
2524 SmallVector<SDValue, 4> Values(NumValues);
2525 SDValue Cond = getValue(I.getOperand(0));
2526 SDValue TrueVal = getValue(I.getOperand(1));
2527 SDValue FalseVal = getValue(I.getOperand(2));
2529 for (unsigned i = 0; i != NumValues; ++i)
2530 Values[i] = DAG.getNode(ISD::SELECT, getCurDebugLoc(),
2531 TrueVal.getNode()->getValueType(TrueVal.getResNo()+i),
2533 SDValue(TrueVal.getNode(),
2534 TrueVal.getResNo() + i),
2535 SDValue(FalseVal.getNode(),
2536 FalseVal.getResNo() + i));
2538 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2539 DAG.getVTList(&ValueVTs[0], NumValues),
2540 &Values[0], NumValues));
2543 void SelectionDAGBuilder::visitTrunc(const User &I) {
2544 // TruncInst cannot be a no-op cast because sizeof(src) > sizeof(dest).
2545 SDValue N = getValue(I.getOperand(0));
2546 EVT DestVT = TLI.getValueType(I.getType());
2547 setValue(&I, DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), DestVT, N));
2550 void SelectionDAGBuilder::visitZExt(const User &I) {
2551 // ZExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2552 // ZExt also can't be a cast to bool for same reason. So, nothing much to do
2553 SDValue N = getValue(I.getOperand(0));
2554 EVT DestVT = TLI.getValueType(I.getType());
2555 setValue(&I, DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(), DestVT, N));
2558 void SelectionDAGBuilder::visitSExt(const User &I) {
2559 // SExt cannot be a no-op cast because sizeof(src) < sizeof(dest).
2560 // SExt also can't be a cast to bool for same reason. So, nothing much to do
2561 SDValue N = getValue(I.getOperand(0));
2562 EVT DestVT = TLI.getValueType(I.getType());
2563 setValue(&I, DAG.getNode(ISD::SIGN_EXTEND, getCurDebugLoc(), DestVT, N));
2566 void SelectionDAGBuilder::visitFPTrunc(const User &I) {
2567 // FPTrunc is never a no-op cast, no need to check
2568 SDValue N = getValue(I.getOperand(0));
2569 EVT DestVT = TLI.getValueType(I.getType());
2570 setValue(&I, DAG.getNode(ISD::FP_ROUND, getCurDebugLoc(),
2571 DestVT, N, DAG.getIntPtrConstant(0)));
2574 void SelectionDAGBuilder::visitFPExt(const User &I){
2575 // FPTrunc is never a no-op cast, no need to check
2576 SDValue N = getValue(I.getOperand(0));
2577 EVT DestVT = TLI.getValueType(I.getType());
2578 setValue(&I, DAG.getNode(ISD::FP_EXTEND, getCurDebugLoc(), DestVT, N));
2581 void SelectionDAGBuilder::visitFPToUI(const User &I) {
2582 // FPToUI is never a no-op cast, no need to check
2583 SDValue N = getValue(I.getOperand(0));
2584 EVT DestVT = TLI.getValueType(I.getType());
2585 setValue(&I, DAG.getNode(ISD::FP_TO_UINT, getCurDebugLoc(), DestVT, N));
2588 void SelectionDAGBuilder::visitFPToSI(const User &I) {
2589 // FPToSI is never a no-op cast, no need to check
2590 SDValue N = getValue(I.getOperand(0));
2591 EVT DestVT = TLI.getValueType(I.getType());
2592 setValue(&I, DAG.getNode(ISD::FP_TO_SINT, getCurDebugLoc(), DestVT, N));
2595 void SelectionDAGBuilder::visitUIToFP(const User &I) {
2596 // UIToFP is never a no-op cast, no need to check
2597 SDValue N = getValue(I.getOperand(0));
2598 EVT DestVT = TLI.getValueType(I.getType());
2599 setValue(&I, DAG.getNode(ISD::UINT_TO_FP, getCurDebugLoc(), DestVT, N));
2602 void SelectionDAGBuilder::visitSIToFP(const User &I){
2603 // SIToFP is never a no-op cast, no need to check
2604 SDValue N = getValue(I.getOperand(0));
2605 EVT DestVT = TLI.getValueType(I.getType());
2606 setValue(&I, DAG.getNode(ISD::SINT_TO_FP, getCurDebugLoc(), DestVT, N));
2609 void SelectionDAGBuilder::visitPtrToInt(const User &I) {
2610 // What to do depends on the size of the integer and the size of the pointer.
2611 // We can either truncate, zero extend, or no-op, accordingly.
2612 SDValue N = getValue(I.getOperand(0));
2613 EVT DestVT = TLI.getValueType(I.getType());
2614 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2617 void SelectionDAGBuilder::visitIntToPtr(const User &I) {
2618 // What to do depends on the size of the integer and the size of the pointer.
2619 // We can either truncate, zero extend, or no-op, accordingly.
2620 SDValue N = getValue(I.getOperand(0));
2621 EVT DestVT = TLI.getValueType(I.getType());
2622 setValue(&I, DAG.getZExtOrTrunc(N, getCurDebugLoc(), DestVT));
2625 void SelectionDAGBuilder::visitBitCast(const User &I) {
2626 SDValue N = getValue(I.getOperand(0));
2627 EVT DestVT = TLI.getValueType(I.getType());
2629 // BitCast assures us that source and destination are the same size so this is
2630 // either a BITCAST or a no-op.
2631 if (DestVT != N.getValueType())
2632 setValue(&I, DAG.getNode(ISD::BITCAST, getCurDebugLoc(),
2633 DestVT, N)); // convert types.
2635 setValue(&I, N); // noop cast.
2638 void SelectionDAGBuilder::visitInsertElement(const User &I) {
2639 SDValue InVec = getValue(I.getOperand(0));
2640 SDValue InVal = getValue(I.getOperand(1));
2641 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2643 getValue(I.getOperand(2)));
2644 setValue(&I, DAG.getNode(ISD::INSERT_VECTOR_ELT, getCurDebugLoc(),
2645 TLI.getValueType(I.getType()),
2646 InVec, InVal, InIdx));
2649 void SelectionDAGBuilder::visitExtractElement(const User &I) {
2650 SDValue InVec = getValue(I.getOperand(0));
2651 SDValue InIdx = DAG.getNode(ISD::ZERO_EXTEND, getCurDebugLoc(),
2653 getValue(I.getOperand(1)));
2654 setValue(&I, DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2655 TLI.getValueType(I.getType()), InVec, InIdx));
2658 // Utility for visitShuffleVector - Returns true if the mask is mask starting
2659 // from SIndx and increasing to the element length (undefs are allowed).
2660 static bool SequentialMask(SmallVectorImpl<int> &Mask, unsigned SIndx) {
2661 unsigned MaskNumElts = Mask.size();
2662 for (unsigned i = 0; i != MaskNumElts; ++i)
2663 if ((Mask[i] >= 0) && (Mask[i] != (int)(i + SIndx)))
2668 void SelectionDAGBuilder::visitShuffleVector(const User &I) {
2669 SmallVector<int, 8> Mask;
2670 SDValue Src1 = getValue(I.getOperand(0));
2671 SDValue Src2 = getValue(I.getOperand(1));
2673 // Convert the ConstantVector mask operand into an array of ints, with -1
2674 // representing undef values.
2675 SmallVector<Constant*, 8> MaskElts;
2676 cast<Constant>(I.getOperand(2))->getVectorElements(MaskElts);
2677 unsigned MaskNumElts = MaskElts.size();
2678 for (unsigned i = 0; i != MaskNumElts; ++i) {
2679 if (isa<UndefValue>(MaskElts[i]))
2682 Mask.push_back(cast<ConstantInt>(MaskElts[i])->getSExtValue());
2685 EVT VT = TLI.getValueType(I.getType());
2686 EVT SrcVT = Src1.getValueType();
2687 unsigned SrcNumElts = SrcVT.getVectorNumElements();
2689 if (SrcNumElts == MaskNumElts) {
2690 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2695 // Normalize the shuffle vector since mask and vector length don't match.
2696 if (SrcNumElts < MaskNumElts && MaskNumElts % SrcNumElts == 0) {
2697 // Mask is longer than the source vectors and is a multiple of the source
2698 // vectors. We can use concatenate vector to make the mask and vectors
2700 if (SrcNumElts*2 == MaskNumElts && SequentialMask(Mask, 0)) {
2701 // The shuffle is concatenating two vectors together.
2702 setValue(&I, DAG.getNode(ISD::CONCAT_VECTORS, getCurDebugLoc(),
2707 // Pad both vectors with undefs to make them the same length as the mask.
2708 unsigned NumConcat = MaskNumElts / SrcNumElts;
2709 bool Src1U = Src1.getOpcode() == ISD::UNDEF;
2710 bool Src2U = Src2.getOpcode() == ISD::UNDEF;
2711 SDValue UndefVal = DAG.getUNDEF(SrcVT);
2713 SmallVector<SDValue, 8> MOps1(NumConcat, UndefVal);
2714 SmallVector<SDValue, 8> MOps2(NumConcat, UndefVal);
2718 Src1 = Src1U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2719 getCurDebugLoc(), VT,
2720 &MOps1[0], NumConcat);
2721 Src2 = Src2U ? DAG.getUNDEF(VT) : DAG.getNode(ISD::CONCAT_VECTORS,
2722 getCurDebugLoc(), VT,
2723 &MOps2[0], NumConcat);
2725 // Readjust mask for new input vector length.
2726 SmallVector<int, 8> MappedOps;
2727 for (unsigned i = 0; i != MaskNumElts; ++i) {
2729 if (Idx < (int)SrcNumElts)
2730 MappedOps.push_back(Idx);
2732 MappedOps.push_back(Idx + MaskNumElts - SrcNumElts);
2735 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2740 if (SrcNumElts > MaskNumElts) {
2741 // Analyze the access pattern of the vector to see if we can extract
2742 // two subvectors and do the shuffle. The analysis is done by calculating
2743 // the range of elements the mask access on both vectors.
2744 int MinRange[2] = { SrcNumElts+1, SrcNumElts+1};
2745 int MaxRange[2] = {-1, -1};
2747 for (unsigned i = 0; i != MaskNumElts; ++i) {
2753 if (Idx >= (int)SrcNumElts) {
2757 if (Idx > MaxRange[Input])
2758 MaxRange[Input] = Idx;
2759 if (Idx < MinRange[Input])
2760 MinRange[Input] = Idx;
2763 // Check if the access is smaller than the vector size and can we find
2764 // a reasonable extract index.
2765 int RangeUse[2] = { 2, 2 }; // 0 = Unused, 1 = Extract, 2 = Can not
2767 int StartIdx[2]; // StartIdx to extract from
2768 for (int Input=0; Input < 2; ++Input) {
2769 if (MinRange[Input] == (int)(SrcNumElts+1) && MaxRange[Input] == -1) {
2770 RangeUse[Input] = 0; // Unused
2771 StartIdx[Input] = 0;
2772 } else if (MaxRange[Input] - MinRange[Input] < (int)MaskNumElts) {
2773 // Fits within range but we should see if we can find a good
2774 // start index that is a multiple of the mask length.
2775 if (MaxRange[Input] < (int)MaskNumElts) {
2776 RangeUse[Input] = 1; // Extract from beginning of the vector
2777 StartIdx[Input] = 0;
2779 StartIdx[Input] = (MinRange[Input]/MaskNumElts)*MaskNumElts;
2780 if (MaxRange[Input] - StartIdx[Input] < (int)MaskNumElts &&
2781 StartIdx[Input] + MaskNumElts <= SrcNumElts)
2782 RangeUse[Input] = 1; // Extract from a multiple of the mask length.
2787 if (RangeUse[0] == 0 && RangeUse[1] == 0) {
2788 setValue(&I, DAG.getUNDEF(VT)); // Vectors are not used.
2791 else if (RangeUse[0] < 2 && RangeUse[1] < 2) {
2792 // Extract appropriate subvector and generate a vector shuffle
2793 for (int Input=0; Input < 2; ++Input) {
2794 SDValue &Src = Input == 0 ? Src1 : Src2;
2795 if (RangeUse[Input] == 0)
2796 Src = DAG.getUNDEF(VT);
2798 Src = DAG.getNode(ISD::EXTRACT_SUBVECTOR, getCurDebugLoc(), VT,
2799 Src, DAG.getIntPtrConstant(StartIdx[Input]));
2802 // Calculate new mask.
2803 SmallVector<int, 8> MappedOps;
2804 for (unsigned i = 0; i != MaskNumElts; ++i) {
2807 MappedOps.push_back(Idx);
2808 else if (Idx < (int)SrcNumElts)
2809 MappedOps.push_back(Idx - StartIdx[0]);
2811 MappedOps.push_back(Idx - SrcNumElts - StartIdx[1] + MaskNumElts);
2814 setValue(&I, DAG.getVectorShuffle(VT, getCurDebugLoc(), Src1, Src2,
2820 // We can't use either concat vectors or extract subvectors so fall back to
2821 // replacing the shuffle with extract and build vector.
2822 // to insert and build vector.
2823 EVT EltVT = VT.getVectorElementType();
2824 EVT PtrVT = TLI.getPointerTy();
2825 SmallVector<SDValue,8> Ops;
2826 for (unsigned i = 0; i != MaskNumElts; ++i) {
2828 Ops.push_back(DAG.getUNDEF(EltVT));
2833 if (Idx < (int)SrcNumElts)
2834 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2835 EltVT, Src1, DAG.getConstant(Idx, PtrVT));
2837 Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, getCurDebugLoc(),
2839 DAG.getConstant(Idx - SrcNumElts, PtrVT));
2845 setValue(&I, DAG.getNode(ISD::BUILD_VECTOR, getCurDebugLoc(),
2846 VT, &Ops[0], Ops.size()));
2849 void SelectionDAGBuilder::visitInsertValue(const InsertValueInst &I) {
2850 const Value *Op0 = I.getOperand(0);
2851 const Value *Op1 = I.getOperand(1);
2852 const Type *AggTy = I.getType();
2853 const Type *ValTy = Op1->getType();
2854 bool IntoUndef = isa<UndefValue>(Op0);
2855 bool FromUndef = isa<UndefValue>(Op1);
2857 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.idx_begin(), I.idx_end());
2859 SmallVector<EVT, 4> AggValueVTs;
2860 ComputeValueVTs(TLI, AggTy, AggValueVTs);
2861 SmallVector<EVT, 4> ValValueVTs;
2862 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2864 unsigned NumAggValues = AggValueVTs.size();
2865 unsigned NumValValues = ValValueVTs.size();
2866 SmallVector<SDValue, 4> Values(NumAggValues);
2868 SDValue Agg = getValue(Op0);
2870 // Copy the beginning value(s) from the original aggregate.
2871 for (; i != LinearIndex; ++i)
2872 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2873 SDValue(Agg.getNode(), Agg.getResNo() + i);
2874 // Copy values from the inserted value(s).
2876 SDValue Val = getValue(Op1);
2877 for (; i != LinearIndex + NumValValues; ++i)
2878 Values[i] = FromUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2879 SDValue(Val.getNode(), Val.getResNo() + i - LinearIndex);
2881 // Copy remaining value(s) from the original aggregate.
2882 for (; i != NumAggValues; ++i)
2883 Values[i] = IntoUndef ? DAG.getUNDEF(AggValueVTs[i]) :
2884 SDValue(Agg.getNode(), Agg.getResNo() + i);
2886 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2887 DAG.getVTList(&AggValueVTs[0], NumAggValues),
2888 &Values[0], NumAggValues));
2891 void SelectionDAGBuilder::visitExtractValue(const ExtractValueInst &I) {
2892 const Value *Op0 = I.getOperand(0);
2893 const Type *AggTy = Op0->getType();
2894 const Type *ValTy = I.getType();
2895 bool OutOfUndef = isa<UndefValue>(Op0);
2897 unsigned LinearIndex = ComputeLinearIndex(AggTy, I.idx_begin(), I.idx_end());
2899 SmallVector<EVT, 4> ValValueVTs;
2900 ComputeValueVTs(TLI, ValTy, ValValueVTs);
2902 unsigned NumValValues = ValValueVTs.size();
2904 // Ignore a extractvalue that produces an empty object
2905 if (!NumValValues) {
2906 setValue(&I, DAG.getUNDEF(MVT(MVT::Other)));
2910 SmallVector<SDValue, 4> Values(NumValValues);
2912 SDValue Agg = getValue(Op0);
2913 // Copy out the selected value(s).
2914 for (unsigned i = LinearIndex; i != LinearIndex + NumValValues; ++i)
2915 Values[i - LinearIndex] =
2917 DAG.getUNDEF(Agg.getNode()->getValueType(Agg.getResNo() + i)) :
2918 SDValue(Agg.getNode(), Agg.getResNo() + i);
2920 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
2921 DAG.getVTList(&ValValueVTs[0], NumValValues),
2922 &Values[0], NumValValues));
2925 void SelectionDAGBuilder::visitGetElementPtr(const User &I) {
2926 SDValue N = getValue(I.getOperand(0));
2927 const Type *Ty = I.getOperand(0)->getType();
2929 for (GetElementPtrInst::const_op_iterator OI = I.op_begin()+1, E = I.op_end();
2931 const Value *Idx = *OI;
2932 if (const StructType *StTy = dyn_cast<StructType>(Ty)) {
2933 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
2936 uint64_t Offset = TD->getStructLayout(StTy)->getElementOffset(Field);
2937 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2938 DAG.getIntPtrConstant(Offset));
2941 Ty = StTy->getElementType(Field);
2943 Ty = cast<SequentialType>(Ty)->getElementType();
2945 // If this is a constant subscript, handle it quickly.
2946 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Idx)) {
2947 if (CI->isZero()) continue;
2949 TD->getTypeAllocSize(Ty)*cast<ConstantInt>(CI)->getSExtValue();
2951 EVT PTy = TLI.getPointerTy();
2952 unsigned PtrBits = PTy.getSizeInBits();
2954 OffsVal = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(),
2956 DAG.getConstant(Offs, MVT::i64));
2958 OffsVal = DAG.getIntPtrConstant(Offs);
2960 N = DAG.getNode(ISD::ADD, getCurDebugLoc(), N.getValueType(), N,
2965 // N = N + Idx * ElementSize;
2966 APInt ElementSize = APInt(TLI.getPointerTy().getSizeInBits(),
2967 TD->getTypeAllocSize(Ty));
2968 SDValue IdxN = getValue(Idx);
2970 // If the index is smaller or larger than intptr_t, truncate or extend
2972 IdxN = DAG.getSExtOrTrunc(IdxN, getCurDebugLoc(), N.getValueType());
2974 // If this is a multiply by a power of two, turn it into a shl
2975 // immediately. This is a very common case.
2976 if (ElementSize != 1) {
2977 if (ElementSize.isPowerOf2()) {
2978 unsigned Amt = ElementSize.logBase2();
2979 IdxN = DAG.getNode(ISD::SHL, getCurDebugLoc(),
2980 N.getValueType(), IdxN,
2981 DAG.getConstant(Amt, TLI.getPointerTy()));
2983 SDValue Scale = DAG.getConstant(ElementSize, TLI.getPointerTy());
2984 IdxN = DAG.getNode(ISD::MUL, getCurDebugLoc(),
2985 N.getValueType(), IdxN, Scale);
2989 N = DAG.getNode(ISD::ADD, getCurDebugLoc(),
2990 N.getValueType(), N, IdxN);
2997 void SelectionDAGBuilder::visitAlloca(const AllocaInst &I) {
2998 // If this is a fixed sized alloca in the entry block of the function,
2999 // allocate it statically on the stack.
3000 if (FuncInfo.StaticAllocaMap.count(&I))
3001 return; // getValue will auto-populate this.
3003 const Type *Ty = I.getAllocatedType();
3004 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
3006 std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty),
3009 SDValue AllocSize = getValue(I.getArraySize());
3011 EVT IntPtr = TLI.getPointerTy();
3012 if (AllocSize.getValueType() != IntPtr)
3013 AllocSize = DAG.getZExtOrTrunc(AllocSize, getCurDebugLoc(), IntPtr);
3015 AllocSize = DAG.getNode(ISD::MUL, getCurDebugLoc(), IntPtr,
3017 DAG.getConstant(TySize, IntPtr));
3019 // Handle alignment. If the requested alignment is less than or equal to
3020 // the stack alignment, ignore it. If the size is greater than or equal to
3021 // the stack alignment, we note this in the DYNAMIC_STACKALLOC node.
3022 unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
3023 if (Align <= StackAlign)
3026 // Round the size of the allocation up to the stack alignment size
3027 // by add SA-1 to the size.
3028 AllocSize = DAG.getNode(ISD::ADD, getCurDebugLoc(),
3029 AllocSize.getValueType(), AllocSize,
3030 DAG.getIntPtrConstant(StackAlign-1));
3032 // Mask out the low bits for alignment purposes.
3033 AllocSize = DAG.getNode(ISD::AND, getCurDebugLoc(),
3034 AllocSize.getValueType(), AllocSize,
3035 DAG.getIntPtrConstant(~(uint64_t)(StackAlign-1)));
3037 SDValue Ops[] = { getRoot(), AllocSize, DAG.getIntPtrConstant(Align) };
3038 SDVTList VTs = DAG.getVTList(AllocSize.getValueType(), MVT::Other);
3039 SDValue DSA = DAG.getNode(ISD::DYNAMIC_STACKALLOC, getCurDebugLoc(),
3042 DAG.setRoot(DSA.getValue(1));
3044 // Inform the Frame Information that we have just allocated a variable-sized
3046 FuncInfo.MF->getFrameInfo()->CreateVariableSizedObject(Align ? Align : 1);
3049 void SelectionDAGBuilder::visitLoad(const LoadInst &I) {
3050 const Value *SV = I.getOperand(0);
3051 SDValue Ptr = getValue(SV);
3053 const Type *Ty = I.getType();
3055 bool isVolatile = I.isVolatile();
3056 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
3057 unsigned Alignment = I.getAlignment();
3058 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
3060 SmallVector<EVT, 4> ValueVTs;
3061 SmallVector<uint64_t, 4> Offsets;
3062 ComputeValueVTs(TLI, Ty, ValueVTs, &Offsets);
3063 unsigned NumValues = ValueVTs.size();
3068 bool ConstantMemory = false;
3069 if (I.isVolatile() || NumValues > MaxParallelChains)
3070 // Serialize volatile loads with other side effects.
3072 else if (AA->pointsToConstantMemory(
3073 AliasAnalysis::Location(SV, AA->getTypeStoreSize(Ty), TBAAInfo))) {
3074 // Do not serialize (non-volatile) loads of constant memory with anything.
3075 Root = DAG.getEntryNode();
3076 ConstantMemory = true;
3078 // Do not serialize non-volatile loads against each other.
3079 Root = DAG.getRoot();
3082 SmallVector<SDValue, 4> Values(NumValues);
3083 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3085 EVT PtrVT = Ptr.getValueType();
3086 unsigned ChainI = 0;
3087 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3088 // Serializing loads here may result in excessive register pressure, and
3089 // TokenFactor places arbitrary choke points on the scheduler. SD scheduling
3090 // could recover a bit by hoisting nodes upward in the chain by recognizing
3091 // they are side-effect free or do not alias. The optimizer should really
3092 // avoid this case by converting large object/array copies to llvm.memcpy
3093 // (MaxParallelChains should always remain as failsafe).
3094 if (ChainI == MaxParallelChains) {
3095 assert(PendingLoads.empty() && "PendingLoads must be serialized first");
3096 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3097 MVT::Other, &Chains[0], ChainI);
3101 SDValue A = DAG.getNode(ISD::ADD, getCurDebugLoc(),
3103 DAG.getConstant(Offsets[i], PtrVT));
3104 SDValue L = DAG.getLoad(ValueVTs[i], getCurDebugLoc(), Root,
3105 A, MachinePointerInfo(SV, Offsets[i]), isVolatile,
3106 isNonTemporal, Alignment, TBAAInfo);
3109 Chains[ChainI] = L.getValue(1);
3112 if (!ConstantMemory) {
3113 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3114 MVT::Other, &Chains[0], ChainI);
3118 PendingLoads.push_back(Chain);
3121 setValue(&I, DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
3122 DAG.getVTList(&ValueVTs[0], NumValues),
3123 &Values[0], NumValues));
3126 void SelectionDAGBuilder::visitStore(const StoreInst &I) {
3127 const Value *SrcV = I.getOperand(0);
3128 const Value *PtrV = I.getOperand(1);
3130 SmallVector<EVT, 4> ValueVTs;
3131 SmallVector<uint64_t, 4> Offsets;
3132 ComputeValueVTs(TLI, SrcV->getType(), ValueVTs, &Offsets);
3133 unsigned NumValues = ValueVTs.size();
3137 // Get the lowered operands. Note that we do this after
3138 // checking if NumResults is zero, because with zero results
3139 // the operands won't have values in the map.
3140 SDValue Src = getValue(SrcV);
3141 SDValue Ptr = getValue(PtrV);
3143 SDValue Root = getRoot();
3144 SmallVector<SDValue, 4> Chains(std::min(unsigned(MaxParallelChains),
3146 EVT PtrVT = Ptr.getValueType();
3147 bool isVolatile = I.isVolatile();
3148 bool isNonTemporal = I.getMetadata("nontemporal") != 0;
3149 unsigned Alignment = I.getAlignment();
3150 const MDNode *TBAAInfo = I.getMetadata(LLVMContext::MD_tbaa);
3152 unsigned ChainI = 0;
3153 for (unsigned i = 0; i != NumValues; ++i, ++ChainI) {
3154 // See visitLoad comments.
3155 if (ChainI == MaxParallelChains) {
3156 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3157 MVT::Other, &Chains[0], ChainI);
3161 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT, Ptr,
3162 DAG.getConstant(Offsets[i], PtrVT));
3163 SDValue St = DAG.getStore(Root, getCurDebugLoc(),
3164 SDValue(Src.getNode(), Src.getResNo() + i),
3165 Add, MachinePointerInfo(PtrV, Offsets[i]),
3166 isVolatile, isNonTemporal, Alignment, TBAAInfo);
3167 Chains[ChainI] = St;
3170 SDValue StoreNode = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
3171 MVT::Other, &Chains[0], ChainI);
3173 AssignOrderingToNode(StoreNode.getNode());
3174 DAG.setRoot(StoreNode);
3177 /// visitTargetIntrinsic - Lower a call of a target intrinsic to an INTRINSIC
3179 void SelectionDAGBuilder::visitTargetIntrinsic(const CallInst &I,
3180 unsigned Intrinsic) {
3181 bool HasChain = !I.doesNotAccessMemory();
3182 bool OnlyLoad = HasChain && I.onlyReadsMemory();
3184 // Build the operand list.
3185 SmallVector<SDValue, 8> Ops;
3186 if (HasChain) { // If this intrinsic has side-effects, chainify it.
3188 // We don't need to serialize loads against other loads.
3189 Ops.push_back(DAG.getRoot());
3191 Ops.push_back(getRoot());
3195 // Info is set by getTgtMemInstrinsic
3196 TargetLowering::IntrinsicInfo Info;
3197 bool IsTgtIntrinsic = TLI.getTgtMemIntrinsic(Info, I, Intrinsic);
3199 // Add the intrinsic ID as an integer operand if it's not a target intrinsic.
3200 if (!IsTgtIntrinsic || Info.opc == ISD::INTRINSIC_VOID ||
3201 Info.opc == ISD::INTRINSIC_W_CHAIN)
3202 Ops.push_back(DAG.getConstant(Intrinsic, TLI.getPointerTy()));
3204 // Add all operands of the call to the operand list.
3205 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
3206 SDValue Op = getValue(I.getArgOperand(i));
3207 assert(TLI.isTypeLegal(Op.getValueType()) &&
3208 "Intrinsic uses a non-legal type?");
3212 SmallVector<EVT, 4> ValueVTs;
3213 ComputeValueVTs(TLI, I.getType(), ValueVTs);
3215 for (unsigned Val = 0, E = ValueVTs.size(); Val != E; ++Val) {
3216 assert(TLI.isTypeLegal(ValueVTs[Val]) &&
3217 "Intrinsic uses a non-legal type?");
3222 ValueVTs.push_back(MVT::Other);
3224 SDVTList VTs = DAG.getVTList(ValueVTs.data(), ValueVTs.size());
3228 if (IsTgtIntrinsic) {
3229 // This is target intrinsic that touches memory
3230 Result = DAG.getMemIntrinsicNode(Info.opc, getCurDebugLoc(),
3231 VTs, &Ops[0], Ops.size(),
3233 MachinePointerInfo(Info.ptrVal, Info.offset),
3234 Info.align, Info.vol,
3235 Info.readMem, Info.writeMem);
3236 } else if (!HasChain) {
3237 Result = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, getCurDebugLoc(),
3238 VTs, &Ops[0], Ops.size());
3239 } else if (!I.getType()->isVoidTy()) {
3240 Result = DAG.getNode(ISD::INTRINSIC_W_CHAIN, getCurDebugLoc(),
3241 VTs, &Ops[0], Ops.size());
3243 Result = DAG.getNode(ISD::INTRINSIC_VOID, getCurDebugLoc(),
3244 VTs, &Ops[0], Ops.size());
3248 SDValue Chain = Result.getValue(Result.getNode()->getNumValues()-1);
3250 PendingLoads.push_back(Chain);
3255 if (!I.getType()->isVoidTy()) {
3256 if (const VectorType *PTy = dyn_cast<VectorType>(I.getType())) {
3257 EVT VT = TLI.getValueType(PTy);
3258 Result = DAG.getNode(ISD::BITCAST, getCurDebugLoc(), VT, Result);
3261 setValue(&I, Result);
3265 /// GetSignificand - Get the significand and build it into a floating-point
3266 /// number with exponent of 1:
3268 /// Op = (Op & 0x007fffff) | 0x3f800000;
3270 /// where Op is the hexidecimal representation of floating point value.
3272 GetSignificand(SelectionDAG &DAG, SDValue Op, DebugLoc dl) {
3273 SDValue t1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3274 DAG.getConstant(0x007fffff, MVT::i32));
3275 SDValue t2 = DAG.getNode(ISD::OR, dl, MVT::i32, t1,
3276 DAG.getConstant(0x3f800000, MVT::i32));
3277 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, t2);
3280 /// GetExponent - Get the exponent:
3282 /// (float)(int)(((Op & 0x7f800000) >> 23) - 127);
3284 /// where Op is the hexidecimal representation of floating point value.
3286 GetExponent(SelectionDAG &DAG, SDValue Op, const TargetLowering &TLI,
3288 SDValue t0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op,
3289 DAG.getConstant(0x7f800000, MVT::i32));
3290 SDValue t1 = DAG.getNode(ISD::SRL, dl, MVT::i32, t0,
3291 DAG.getConstant(23, TLI.getPointerTy()));
3292 SDValue t2 = DAG.getNode(ISD::SUB, dl, MVT::i32, t1,
3293 DAG.getConstant(127, MVT::i32));
3294 return DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, t2);
3297 /// getF32Constant - Get 32-bit floating point constant.
3299 getF32Constant(SelectionDAG &DAG, unsigned Flt) {
3300 return DAG.getConstantFP(APFloat(APInt(32, Flt)), MVT::f32);
3303 /// Inlined utility function to implement binary input atomic intrinsics for
3304 /// visitIntrinsicCall: I is a call instruction
3305 /// Op is the associated NodeType for I
3307 SelectionDAGBuilder::implVisitBinaryAtomic(const CallInst& I,
3309 SDValue Root = getRoot();
3311 DAG.getAtomic(Op, getCurDebugLoc(),
3312 getValue(I.getArgOperand(1)).getValueType().getSimpleVT(),
3314 getValue(I.getArgOperand(0)),
3315 getValue(I.getArgOperand(1)),
3316 I.getArgOperand(0));
3318 DAG.setRoot(L.getValue(1));
3322 // implVisitAluOverflow - Lower arithmetic overflow instrinsics.
3324 SelectionDAGBuilder::implVisitAluOverflow(const CallInst &I, ISD::NodeType Op) {
3325 SDValue Op1 = getValue(I.getArgOperand(0));
3326 SDValue Op2 = getValue(I.getArgOperand(1));
3328 SDVTList VTs = DAG.getVTList(Op1.getValueType(), MVT::i1);
3329 setValue(&I, DAG.getNode(Op, getCurDebugLoc(), VTs, Op1, Op2));
3333 /// visitExp - Lower an exp intrinsic. Handles the special sequences for
3334 /// limited-precision mode.
3336 SelectionDAGBuilder::visitExp(const CallInst &I) {
3338 DebugLoc dl = getCurDebugLoc();
3340 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3341 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3342 SDValue Op = getValue(I.getArgOperand(0));
3344 // Put the exponent in the right bit position for later addition to the
3347 // #define LOG2OFe 1.4426950f
3348 // IntegerPartOfX = ((int32_t)(X * LOG2OFe));
3349 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3350 getF32Constant(DAG, 0x3fb8aa3b));
3351 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3353 // FractionalPartOfX = (X * LOG2OFe) - (float)IntegerPartOfX;
3354 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3355 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3357 // IntegerPartOfX <<= 23;
3358 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3359 DAG.getConstant(23, TLI.getPointerTy()));
3361 if (LimitFloatPrecision <= 6) {
3362 // For floating-point precision of 6:
3364 // TwoToFractionalPartOfX =
3366 // (0.735607626f + 0.252464424f * x) * x;
3368 // error 0.0144103317, which is 6 bits
3369 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3370 getF32Constant(DAG, 0x3e814304));
3371 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3372 getF32Constant(DAG, 0x3f3c50c8));
3373 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3374 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3375 getF32Constant(DAG, 0x3f7f5e7e));
3376 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,MVT::i32, t5);
3378 // Add the exponent into the result in integer domain.
3379 SDValue t6 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3380 TwoToFracPartOfX, IntegerPartOfX);
3382 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t6);
3383 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3384 // For floating-point precision of 12:
3386 // TwoToFractionalPartOfX =
3389 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3391 // 0.000107046256 error, which is 13 to 14 bits
3392 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3393 getF32Constant(DAG, 0x3da235e3));
3394 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3395 getF32Constant(DAG, 0x3e65b8f3));
3396 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3397 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3398 getF32Constant(DAG, 0x3f324b07));
3399 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3400 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3401 getF32Constant(DAG, 0x3f7ff8fd));
3402 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,MVT::i32, t7);
3404 // Add the exponent into the result in integer domain.
3405 SDValue t8 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3406 TwoToFracPartOfX, IntegerPartOfX);
3408 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t8);
3409 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3410 // For floating-point precision of 18:
3412 // TwoToFractionalPartOfX =
3416 // (0.554906021e-1f +
3417 // (0.961591928e-2f +
3418 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3420 // error 2.47208000*10^(-7), which is better than 18 bits
3421 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3422 getF32Constant(DAG, 0x3924b03e));
3423 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3424 getF32Constant(DAG, 0x3ab24b87));
3425 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3426 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3427 getF32Constant(DAG, 0x3c1d8c17));
3428 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3429 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3430 getF32Constant(DAG, 0x3d634a1d));
3431 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3432 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3433 getF32Constant(DAG, 0x3e75fe14));
3434 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3435 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3436 getF32Constant(DAG, 0x3f317234));
3437 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3438 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3439 getF32Constant(DAG, 0x3f800000));
3440 SDValue TwoToFracPartOfX = DAG.getNode(ISD::BITCAST, dl,
3443 // Add the exponent into the result in integer domain.
3444 SDValue t14 = DAG.getNode(ISD::ADD, dl, MVT::i32,
3445 TwoToFracPartOfX, IntegerPartOfX);
3447 result = DAG.getNode(ISD::BITCAST, dl, MVT::f32, t14);
3450 // No special expansion.
3451 result = DAG.getNode(ISD::FEXP, dl,
3452 getValue(I.getArgOperand(0)).getValueType(),
3453 getValue(I.getArgOperand(0)));
3456 setValue(&I, result);
3459 /// visitLog - Lower a log intrinsic. Handles the special sequences for
3460 /// limited-precision mode.
3462 SelectionDAGBuilder::visitLog(const CallInst &I) {
3464 DebugLoc dl = getCurDebugLoc();
3466 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3467 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3468 SDValue Op = getValue(I.getArgOperand(0));
3469 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3471 // Scale the exponent by log(2) [0.69314718f].
3472 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3473 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3474 getF32Constant(DAG, 0x3f317218));
3476 // Get the significand and build it into a floating-point number with
3478 SDValue X = GetSignificand(DAG, Op1, dl);
3480 if (LimitFloatPrecision <= 6) {
3481 // For floating-point precision of 6:
3485 // (1.4034025f - 0.23903021f * x) * x;
3487 // error 0.0034276066, which is better than 8 bits
3488 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3489 getF32Constant(DAG, 0xbe74c456));
3490 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3491 getF32Constant(DAG, 0x3fb3a2b1));
3492 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3493 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3494 getF32Constant(DAG, 0x3f949a29));
3496 result = DAG.getNode(ISD::FADD, dl,
3497 MVT::f32, LogOfExponent, LogOfMantissa);
3498 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3499 // For floating-point precision of 12:
3505 // (0.44717955f - 0.56570851e-1f * x) * x) * x) * x;
3507 // error 0.000061011436, which is 14 bits
3508 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3509 getF32Constant(DAG, 0xbd67b6d6));
3510 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3511 getF32Constant(DAG, 0x3ee4f4b8));
3512 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3513 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3514 getF32Constant(DAG, 0x3fbc278b));
3515 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3516 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3517 getF32Constant(DAG, 0x40348e95));
3518 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3519 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3520 getF32Constant(DAG, 0x3fdef31a));
3522 result = DAG.getNode(ISD::FADD, dl,
3523 MVT::f32, LogOfExponent, LogOfMantissa);
3524 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3525 // For floating-point precision of 18:
3533 // (0.19073739f - 0.17809712e-1f * x) * x) * x) * x) * x)*x;
3535 // error 0.0000023660568, which is better than 18 bits
3536 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3537 getF32Constant(DAG, 0xbc91e5ac));
3538 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3539 getF32Constant(DAG, 0x3e4350aa));
3540 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3541 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3542 getF32Constant(DAG, 0x3f60d3e3));
3543 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3544 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3545 getF32Constant(DAG, 0x4011cdf0));
3546 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3547 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3548 getF32Constant(DAG, 0x406cfd1c));
3549 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3550 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3551 getF32Constant(DAG, 0x408797cb));
3552 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3553 SDValue LogOfMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3554 getF32Constant(DAG, 0x4006dcab));
3556 result = DAG.getNode(ISD::FADD, dl,
3557 MVT::f32, LogOfExponent, LogOfMantissa);
3560 // No special expansion.
3561 result = DAG.getNode(ISD::FLOG, dl,
3562 getValue(I.getArgOperand(0)).getValueType(),
3563 getValue(I.getArgOperand(0)));
3566 setValue(&I, result);
3569 /// visitLog2 - Lower a log2 intrinsic. Handles the special sequences for
3570 /// limited-precision mode.
3572 SelectionDAGBuilder::visitLog2(const CallInst &I) {
3574 DebugLoc dl = getCurDebugLoc();
3576 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3577 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3578 SDValue Op = getValue(I.getArgOperand(0));
3579 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3581 // Get the exponent.
3582 SDValue LogOfExponent = GetExponent(DAG, Op1, TLI, dl);
3584 // Get the significand and build it into a floating-point number with
3586 SDValue X = GetSignificand(DAG, Op1, dl);
3588 // Different possible minimax approximations of significand in
3589 // floating-point for various degrees of accuracy over [1,2].
3590 if (LimitFloatPrecision <= 6) {
3591 // For floating-point precision of 6:
3593 // Log2ofMantissa = -1.6749035f + (2.0246817f - .34484768f * x) * x;
3595 // error 0.0049451742, which is more than 7 bits
3596 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3597 getF32Constant(DAG, 0xbeb08fe0));
3598 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3599 getF32Constant(DAG, 0x40019463));
3600 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3601 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3602 getF32Constant(DAG, 0x3fd6633d));
3604 result = DAG.getNode(ISD::FADD, dl,
3605 MVT::f32, LogOfExponent, Log2ofMantissa);
3606 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3607 // For floating-point precision of 12:
3613 // (.645142248f - 0.816157886e-1f * x) * x) * x) * x;
3615 // error 0.0000876136000, which is better than 13 bits
3616 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3617 getF32Constant(DAG, 0xbda7262e));
3618 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3619 getF32Constant(DAG, 0x3f25280b));
3620 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3621 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3622 getF32Constant(DAG, 0x4007b923));
3623 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3624 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3625 getF32Constant(DAG, 0x40823e2f));
3626 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3627 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3628 getF32Constant(DAG, 0x4020d29c));
3630 result = DAG.getNode(ISD::FADD, dl,
3631 MVT::f32, LogOfExponent, Log2ofMantissa);
3632 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3633 // For floating-point precision of 18:
3642 // 0.25691327e-1f * x) * x) * x) * x) * x) * x;
3644 // error 0.0000018516, which is better than 18 bits
3645 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3646 getF32Constant(DAG, 0xbcd2769e));
3647 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3648 getF32Constant(DAG, 0x3e8ce0b9));
3649 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3650 SDValue t3 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3651 getF32Constant(DAG, 0x3fa22ae7));
3652 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3653 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3654 getF32Constant(DAG, 0x40525723));
3655 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3656 SDValue t7 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t6,
3657 getF32Constant(DAG, 0x40aaf200));
3658 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3659 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3660 getF32Constant(DAG, 0x40c39dad));
3661 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3662 SDValue Log2ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t10,
3663 getF32Constant(DAG, 0x4042902c));
3665 result = DAG.getNode(ISD::FADD, dl,
3666 MVT::f32, LogOfExponent, Log2ofMantissa);
3669 // No special expansion.
3670 result = DAG.getNode(ISD::FLOG2, dl,
3671 getValue(I.getArgOperand(0)).getValueType(),
3672 getValue(I.getArgOperand(0)));
3675 setValue(&I, result);
3678 /// visitLog10 - Lower a log10 intrinsic. Handles the special sequences for
3679 /// limited-precision mode.
3681 SelectionDAGBuilder::visitLog10(const CallInst &I) {
3683 DebugLoc dl = getCurDebugLoc();
3685 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3686 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3687 SDValue Op = getValue(I.getArgOperand(0));
3688 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
3690 // Scale the exponent by log10(2) [0.30102999f].
3691 SDValue Exp = GetExponent(DAG, Op1, TLI, dl);
3692 SDValue LogOfExponent = DAG.getNode(ISD::FMUL, dl, MVT::f32, Exp,
3693 getF32Constant(DAG, 0x3e9a209a));
3695 // Get the significand and build it into a floating-point number with
3697 SDValue X = GetSignificand(DAG, Op1, dl);
3699 if (LimitFloatPrecision <= 6) {
3700 // For floating-point precision of 6:
3702 // Log10ofMantissa =
3704 // (0.60948995f - 0.10380950f * x) * x;
3706 // error 0.0014886165, which is 6 bits
3707 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3708 getF32Constant(DAG, 0xbdd49a13));
3709 SDValue t1 = DAG.getNode(ISD::FADD, dl, MVT::f32, t0,
3710 getF32Constant(DAG, 0x3f1c0789));
3711 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3712 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t2,
3713 getF32Constant(DAG, 0x3f011300));
3715 result = DAG.getNode(ISD::FADD, dl,
3716 MVT::f32, LogOfExponent, Log10ofMantissa);
3717 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3718 // For floating-point precision of 12:
3720 // Log10ofMantissa =
3723 // (-0.31664806f + 0.47637168e-1f * x) * x) * x;
3725 // error 0.00019228036, which is better than 12 bits
3726 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3727 getF32Constant(DAG, 0x3d431f31));
3728 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3729 getF32Constant(DAG, 0x3ea21fb2));
3730 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3731 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3732 getF32Constant(DAG, 0x3f6ae232));
3733 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3734 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3735 getF32Constant(DAG, 0x3f25f7c3));
3737 result = DAG.getNode(ISD::FADD, dl,
3738 MVT::f32, LogOfExponent, Log10ofMantissa);
3739 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3740 // For floating-point precision of 18:
3742 // Log10ofMantissa =
3747 // (-0.12539807f + 0.13508273e-1f * x) * x) * x) * x) * x;
3749 // error 0.0000037995730, which is better than 18 bits
3750 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3751 getF32Constant(DAG, 0x3c5d51ce));
3752 SDValue t1 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0,
3753 getF32Constant(DAG, 0x3e00685a));
3754 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t1, X);
3755 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3756 getF32Constant(DAG, 0x3efb6798));
3757 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3758 SDValue t5 = DAG.getNode(ISD::FSUB, dl, MVT::f32, t4,
3759 getF32Constant(DAG, 0x3f88d192));
3760 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3761 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3762 getF32Constant(DAG, 0x3fc4316c));
3763 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3764 SDValue Log10ofMantissa = DAG.getNode(ISD::FSUB, dl, MVT::f32, t8,
3765 getF32Constant(DAG, 0x3f57ce70));
3767 result = DAG.getNode(ISD::FADD, dl,
3768 MVT::f32, LogOfExponent, Log10ofMantissa);
3771 // No special expansion.
3772 result = DAG.getNode(ISD::FLOG10, dl,
3773 getValue(I.getArgOperand(0)).getValueType(),
3774 getValue(I.getArgOperand(0)));
3777 setValue(&I, result);
3780 /// visitExp2 - Lower an exp2 intrinsic. Handles the special sequences for
3781 /// limited-precision mode.
3783 SelectionDAGBuilder::visitExp2(const CallInst &I) {
3785 DebugLoc dl = getCurDebugLoc();
3787 if (getValue(I.getArgOperand(0)).getValueType() == MVT::f32 &&
3788 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3789 SDValue Op = getValue(I.getArgOperand(0));
3791 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, Op);
3793 // FractionalPartOfX = x - (float)IntegerPartOfX;
3794 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3795 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, Op, t1);
3797 // IntegerPartOfX <<= 23;
3798 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3799 DAG.getConstant(23, TLI.getPointerTy()));
3801 if (LimitFloatPrecision <= 6) {
3802 // For floating-point precision of 6:
3804 // TwoToFractionalPartOfX =
3806 // (0.735607626f + 0.252464424f * x) * x;
3808 // error 0.0144103317, which is 6 bits
3809 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3810 getF32Constant(DAG, 0x3e814304));
3811 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3812 getF32Constant(DAG, 0x3f3c50c8));
3813 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3814 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3815 getF32Constant(DAG, 0x3f7f5e7e));
3816 SDValue t6 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t5);
3817 SDValue TwoToFractionalPartOfX =
3818 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3820 result = DAG.getNode(ISD::BITCAST, dl,
3821 MVT::f32, TwoToFractionalPartOfX);
3822 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3823 // For floating-point precision of 12:
3825 // TwoToFractionalPartOfX =
3828 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3830 // error 0.000107046256, which is 13 to 14 bits
3831 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3832 getF32Constant(DAG, 0x3da235e3));
3833 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3834 getF32Constant(DAG, 0x3e65b8f3));
3835 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3836 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3837 getF32Constant(DAG, 0x3f324b07));
3838 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3839 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3840 getF32Constant(DAG, 0x3f7ff8fd));
3841 SDValue t8 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t7);
3842 SDValue TwoToFractionalPartOfX =
3843 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3845 result = DAG.getNode(ISD::BITCAST, dl,
3846 MVT::f32, TwoToFractionalPartOfX);
3847 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3848 // For floating-point precision of 18:
3850 // TwoToFractionalPartOfX =
3854 // (0.554906021e-1f +
3855 // (0.961591928e-2f +
3856 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3857 // error 2.47208000*10^(-7), which is better than 18 bits
3858 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3859 getF32Constant(DAG, 0x3924b03e));
3860 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3861 getF32Constant(DAG, 0x3ab24b87));
3862 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3863 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3864 getF32Constant(DAG, 0x3c1d8c17));
3865 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3866 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3867 getF32Constant(DAG, 0x3d634a1d));
3868 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
3869 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
3870 getF32Constant(DAG, 0x3e75fe14));
3871 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
3872 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
3873 getF32Constant(DAG, 0x3f317234));
3874 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
3875 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
3876 getF32Constant(DAG, 0x3f800000));
3877 SDValue t14 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t13);
3878 SDValue TwoToFractionalPartOfX =
3879 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
3881 result = DAG.getNode(ISD::BITCAST, dl,
3882 MVT::f32, TwoToFractionalPartOfX);
3885 // No special expansion.
3886 result = DAG.getNode(ISD::FEXP2, dl,
3887 getValue(I.getArgOperand(0)).getValueType(),
3888 getValue(I.getArgOperand(0)));
3891 setValue(&I, result);
3894 /// visitPow - Lower a pow intrinsic. Handles the special sequences for
3895 /// limited-precision mode with x == 10.0f.
3897 SelectionDAGBuilder::visitPow(const CallInst &I) {
3899 const Value *Val = I.getArgOperand(0);
3900 DebugLoc dl = getCurDebugLoc();
3901 bool IsExp10 = false;
3903 if (getValue(Val).getValueType() == MVT::f32 &&
3904 getValue(I.getArgOperand(1)).getValueType() == MVT::f32 &&
3905 LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3906 if (Constant *C = const_cast<Constant*>(dyn_cast<Constant>(Val))) {
3907 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
3909 IsExp10 = CFP->getValueAPF().bitwiseIsEqual(Ten);
3914 if (IsExp10 && LimitFloatPrecision > 0 && LimitFloatPrecision <= 18) {
3915 SDValue Op = getValue(I.getArgOperand(1));
3917 // Put the exponent in the right bit position for later addition to the
3920 // #define LOG2OF10 3.3219281f
3921 // IntegerPartOfX = (int32_t)(x * LOG2OF10);
3922 SDValue t0 = DAG.getNode(ISD::FMUL, dl, MVT::f32, Op,
3923 getF32Constant(DAG, 0x40549a78));
3924 SDValue IntegerPartOfX = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::i32, t0);
3926 // FractionalPartOfX = x - (float)IntegerPartOfX;
3927 SDValue t1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, IntegerPartOfX);
3928 SDValue X = DAG.getNode(ISD::FSUB, dl, MVT::f32, t0, t1);
3930 // IntegerPartOfX <<= 23;
3931 IntegerPartOfX = DAG.getNode(ISD::SHL, dl, MVT::i32, IntegerPartOfX,
3932 DAG.getConstant(23, TLI.getPointerTy()));
3934 if (LimitFloatPrecision <= 6) {
3935 // For floating-point precision of 6:
3937 // twoToFractionalPartOfX =
3939 // (0.735607626f + 0.252464424f * x) * x;
3941 // error 0.0144103317, which is 6 bits
3942 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3943 getF32Constant(DAG, 0x3e814304));
3944 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3945 getF32Constant(DAG, 0x3f3c50c8));
3946 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3947 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3948 getF32Constant(DAG, 0x3f7f5e7e));
3949 SDValue t6 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t5);
3950 SDValue TwoToFractionalPartOfX =
3951 DAG.getNode(ISD::ADD, dl, MVT::i32, t6, IntegerPartOfX);
3953 result = DAG.getNode(ISD::BITCAST, dl,
3954 MVT::f32, TwoToFractionalPartOfX);
3955 } else if (LimitFloatPrecision > 6 && LimitFloatPrecision <= 12) {
3956 // For floating-point precision of 12:
3958 // TwoToFractionalPartOfX =
3961 // (0.224338339f + 0.792043434e-1f * x) * x) * x;
3963 // error 0.000107046256, which is 13 to 14 bits
3964 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3965 getF32Constant(DAG, 0x3da235e3));
3966 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3967 getF32Constant(DAG, 0x3e65b8f3));
3968 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3969 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3970 getF32Constant(DAG, 0x3f324b07));
3971 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3972 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
3973 getF32Constant(DAG, 0x3f7ff8fd));
3974 SDValue t8 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t7);
3975 SDValue TwoToFractionalPartOfX =
3976 DAG.getNode(ISD::ADD, dl, MVT::i32, t8, IntegerPartOfX);
3978 result = DAG.getNode(ISD::BITCAST, dl,
3979 MVT::f32, TwoToFractionalPartOfX);
3980 } else { // LimitFloatPrecision > 12 && LimitFloatPrecision <= 18
3981 // For floating-point precision of 18:
3983 // TwoToFractionalPartOfX =
3987 // (0.554906021e-1f +
3988 // (0.961591928e-2f +
3989 // (0.136028312e-2f + 0.157059148e-3f *x)*x)*x)*x)*x)*x;
3990 // error 2.47208000*10^(-7), which is better than 18 bits
3991 SDValue t2 = DAG.getNode(ISD::FMUL, dl, MVT::f32, X,
3992 getF32Constant(DAG, 0x3924b03e));
3993 SDValue t3 = DAG.getNode(ISD::FADD, dl, MVT::f32, t2,
3994 getF32Constant(DAG, 0x3ab24b87));
3995 SDValue t4 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t3, X);
3996 SDValue t5 = DAG.getNode(ISD::FADD, dl, MVT::f32, t4,
3997 getF32Constant(DAG, 0x3c1d8c17));
3998 SDValue t6 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t5, X);
3999 SDValue t7 = DAG.getNode(ISD::FADD, dl, MVT::f32, t6,
4000 getF32Constant(DAG, 0x3d634a1d));
4001 SDValue t8 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t7, X);
4002 SDValue t9 = DAG.getNode(ISD::FADD, dl, MVT::f32, t8,
4003 getF32Constant(DAG, 0x3e75fe14));
4004 SDValue t10 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t9, X);
4005 SDValue t11 = DAG.getNode(ISD::FADD, dl, MVT::f32, t10,
4006 getF32Constant(DAG, 0x3f317234));
4007 SDValue t12 = DAG.getNode(ISD::FMUL, dl, MVT::f32, t11, X);
4008 SDValue t13 = DAG.getNode(ISD::FADD, dl, MVT::f32, t12,
4009 getF32Constant(DAG, 0x3f800000));
4010 SDValue t14 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, t13);
4011 SDValue TwoToFractionalPartOfX =
4012 DAG.getNode(ISD::ADD, dl, MVT::i32, t14, IntegerPartOfX);
4014 result = DAG.getNode(ISD::BITCAST, dl,
4015 MVT::f32, TwoToFractionalPartOfX);
4018 // No special expansion.
4019 result = DAG.getNode(ISD::FPOW, dl,
4020 getValue(I.getArgOperand(0)).getValueType(),
4021 getValue(I.getArgOperand(0)),
4022 getValue(I.getArgOperand(1)));
4025 setValue(&I, result);
4029 /// ExpandPowI - Expand a llvm.powi intrinsic.
4030 static SDValue ExpandPowI(DebugLoc DL, SDValue LHS, SDValue RHS,
4031 SelectionDAG &DAG) {
4032 // If RHS is a constant, we can expand this out to a multiplication tree,
4033 // otherwise we end up lowering to a call to __powidf2 (for example). When
4034 // optimizing for size, we only want to do this if the expansion would produce
4035 // a small number of multiplies, otherwise we do the full expansion.
4036 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
4037 // Get the exponent as a positive value.
4038 unsigned Val = RHSC->getSExtValue();
4039 if ((int)Val < 0) Val = -Val;
4041 // powi(x, 0) -> 1.0
4043 return DAG.getConstantFP(1.0, LHS.getValueType());
4045 const Function *F = DAG.getMachineFunction().getFunction();
4046 if (!F->hasFnAttr(Attribute::OptimizeForSize) ||
4047 // If optimizing for size, don't insert too many multiplies. This
4048 // inserts up to 5 multiplies.
4049 CountPopulation_32(Val)+Log2_32(Val) < 7) {
4050 // We use the simple binary decomposition method to generate the multiply
4051 // sequence. There are more optimal ways to do this (for example,
4052 // powi(x,15) generates one more multiply than it should), but this has
4053 // the benefit of being both really simple and much better than a libcall.
4054 SDValue Res; // Logically starts equal to 1.0
4055 SDValue CurSquare = LHS;
4059 Res = DAG.getNode(ISD::FMUL, DL,Res.getValueType(), Res, CurSquare);
4061 Res = CurSquare; // 1.0*CurSquare.
4064 CurSquare = DAG.getNode(ISD::FMUL, DL, CurSquare.getValueType(),
4065 CurSquare, CurSquare);
4069 // If the original was negative, invert the result, producing 1/(x*x*x).
4070 if (RHSC->getSExtValue() < 0)
4071 Res = DAG.getNode(ISD::FDIV, DL, LHS.getValueType(),
4072 DAG.getConstantFP(1.0, LHS.getValueType()), Res);
4077 // Otherwise, expand to a libcall.
4078 return DAG.getNode(ISD::FPOWI, DL, LHS.getValueType(), LHS, RHS);
4081 // getTruncatedArgReg - Find underlying register used for an truncated
4083 static unsigned getTruncatedArgReg(const SDValue &N) {
4084 if (N.getOpcode() != ISD::TRUNCATE)
4087 const SDValue &Ext = N.getOperand(0);
4088 if (Ext.getOpcode() == ISD::AssertZext || Ext.getOpcode() == ISD::AssertSext){
4089 const SDValue &CFR = Ext.getOperand(0);
4090 if (CFR.getOpcode() == ISD::CopyFromReg)
4091 return cast<RegisterSDNode>(CFR.getOperand(1))->getReg();
4093 if (CFR.getOpcode() == ISD::TRUNCATE)
4094 return getTruncatedArgReg(CFR);
4099 /// EmitFuncArgumentDbgValue - If the DbgValueInst is a dbg_value of a function
4100 /// argument, create the corresponding DBG_VALUE machine instruction for it now.
4101 /// At the end of instruction selection, they will be inserted to the entry BB.
4103 SelectionDAGBuilder::EmitFuncArgumentDbgValue(const Value *V, MDNode *Variable,
4106 const Argument *Arg = dyn_cast<Argument>(V);
4110 MachineFunction &MF = DAG.getMachineFunction();
4111 const TargetInstrInfo *TII = DAG.getTarget().getInstrInfo();
4112 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
4114 // Ignore inlined function arguments here.
4115 DIVariable DV(Variable);
4116 if (DV.isInlinedFnArgument(MF.getFunction()))
4120 if (Arg->hasByValAttr()) {
4121 // Byval arguments' frame index is recorded during argument lowering.
4122 // Use this info directly.
4123 Reg = TRI->getFrameRegister(MF);
4124 Offset = FuncInfo.getByValArgumentFrameIndex(Arg);
4125 // If byval argument ofset is not recorded then ignore this.
4131 if (N.getOpcode() == ISD::CopyFromReg)
4132 Reg = cast<RegisterSDNode>(N.getOperand(1))->getReg();
4134 Reg = getTruncatedArgReg(N);
4135 if (Reg && TargetRegisterInfo::isVirtualRegister(Reg)) {
4136 MachineRegisterInfo &RegInfo = MF.getRegInfo();
4137 unsigned PR = RegInfo.getLiveInPhysReg(Reg);
4144 // Check if ValueMap has reg number.
4145 DenseMap<const Value *, unsigned>::iterator VMI = FuncInfo.ValueMap.find(V);
4146 if (VMI != FuncInfo.ValueMap.end())
4150 if (!Reg && N.getNode()) {
4151 // Check if frame index is available.
4152 if (LoadSDNode *LNode = dyn_cast<LoadSDNode>(N.getNode()))
4153 if (FrameIndexSDNode *FINode =
4154 dyn_cast<FrameIndexSDNode>(LNode->getBasePtr().getNode())) {
4155 Reg = TRI->getFrameRegister(MF);
4156 Offset = FINode->getIndex();
4163 MachineInstrBuilder MIB = BuildMI(MF, getCurDebugLoc(),
4164 TII->get(TargetOpcode::DBG_VALUE))
4165 .addReg(Reg, RegState::Debug).addImm(Offset).addMetadata(Variable);
4166 FuncInfo.ArgDbgValues.push_back(&*MIB);
4170 // VisualStudio defines setjmp as _setjmp
4171 #if defined(_MSC_VER) && defined(setjmp) && \
4172 !defined(setjmp_undefined_for_msvc)
4173 # pragma push_macro("setjmp")
4175 # define setjmp_undefined_for_msvc
4178 /// visitIntrinsicCall - Lower the call to the specified intrinsic function. If
4179 /// we want to emit this as a call to a named external function, return the name
4180 /// otherwise lower it and return null.
4182 SelectionDAGBuilder::visitIntrinsicCall(const CallInst &I, unsigned Intrinsic) {
4183 DebugLoc dl = getCurDebugLoc();
4186 switch (Intrinsic) {
4188 // By default, turn this into a target intrinsic node.
4189 visitTargetIntrinsic(I, Intrinsic);
4191 case Intrinsic::vastart: visitVAStart(I); return 0;
4192 case Intrinsic::vaend: visitVAEnd(I); return 0;
4193 case Intrinsic::vacopy: visitVACopy(I); return 0;
4194 case Intrinsic::returnaddress:
4195 setValue(&I, DAG.getNode(ISD::RETURNADDR, dl, TLI.getPointerTy(),
4196 getValue(I.getArgOperand(0))));
4198 case Intrinsic::frameaddress:
4199 setValue(&I, DAG.getNode(ISD::FRAMEADDR, dl, TLI.getPointerTy(),
4200 getValue(I.getArgOperand(0))));
4202 case Intrinsic::setjmp:
4203 return "_setjmp"+!TLI.usesUnderscoreSetJmp();
4204 case Intrinsic::longjmp:
4205 return "_longjmp"+!TLI.usesUnderscoreLongJmp();
4206 case Intrinsic::memcpy: {
4207 // Assert for address < 256 since we support only user defined address
4209 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4211 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4213 "Unknown address space");
4214 SDValue Op1 = getValue(I.getArgOperand(0));
4215 SDValue Op2 = getValue(I.getArgOperand(1));
4216 SDValue Op3 = getValue(I.getArgOperand(2));
4217 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4218 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4219 DAG.setRoot(DAG.getMemcpy(getRoot(), dl, Op1, Op2, Op3, Align, isVol, false,
4220 MachinePointerInfo(I.getArgOperand(0)),
4221 MachinePointerInfo(I.getArgOperand(1))));
4224 case Intrinsic::memset: {
4225 // Assert for address < 256 since we support only user defined address
4227 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4229 "Unknown address space");
4230 SDValue Op1 = getValue(I.getArgOperand(0));
4231 SDValue Op2 = getValue(I.getArgOperand(1));
4232 SDValue Op3 = getValue(I.getArgOperand(2));
4233 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4234 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4235 DAG.setRoot(DAG.getMemset(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
4236 MachinePointerInfo(I.getArgOperand(0))));
4239 case Intrinsic::memmove: {
4240 // Assert for address < 256 since we support only user defined address
4242 assert(cast<PointerType>(I.getArgOperand(0)->getType())->getAddressSpace()
4244 cast<PointerType>(I.getArgOperand(1)->getType())->getAddressSpace()
4246 "Unknown address space");
4247 SDValue Op1 = getValue(I.getArgOperand(0));
4248 SDValue Op2 = getValue(I.getArgOperand(1));
4249 SDValue Op3 = getValue(I.getArgOperand(2));
4250 unsigned Align = cast<ConstantInt>(I.getArgOperand(3))->getZExtValue();
4251 bool isVol = cast<ConstantInt>(I.getArgOperand(4))->getZExtValue();
4252 DAG.setRoot(DAG.getMemmove(getRoot(), dl, Op1, Op2, Op3, Align, isVol,
4253 MachinePointerInfo(I.getArgOperand(0)),
4254 MachinePointerInfo(I.getArgOperand(1))));
4257 case Intrinsic::dbg_declare: {
4258 const DbgDeclareInst &DI = cast<DbgDeclareInst>(I);
4259 MDNode *Variable = DI.getVariable();
4260 const Value *Address = DI.getAddress();
4261 if (!Address || !DIVariable(DI.getVariable()).Verify())
4264 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
4265 // but do not always have a corresponding SDNode built. The SDNodeOrder
4266 // absolute, but not relative, values are different depending on whether
4267 // debug info exists.
4270 // Check if address has undef value.
4271 if (isa<UndefValue>(Address) ||
4272 (Address->use_empty() && !isa<Argument>(Address))) {
4273 DEBUG(dbgs() << "Dropping debug info for " << DI);
4277 SDValue &N = NodeMap[Address];
4278 if (!N.getNode() && isa<Argument>(Address))
4279 // Check unused arguments map.
4280 N = UnusedArgNodeMap[Address];
4283 // Parameters are handled specially.
4285 DIVariable(Variable).getTag() == dwarf::DW_TAG_arg_variable;
4286 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Address))
4287 Address = BCI->getOperand(0);
4288 const AllocaInst *AI = dyn_cast<AllocaInst>(Address);
4290 if (isParameter && !AI) {
4291 FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(N.getNode());
4293 // Byval parameter. We have a frame index at this point.
4294 SDV = DAG.getDbgValue(Variable, FINode->getIndex(),
4295 0, dl, SDNodeOrder);
4297 // Address is an argument, so try to emit its dbg value using
4298 // virtual register info from the FuncInfo.ValueMap.
4299 EmitFuncArgumentDbgValue(Address, Variable, 0, N);
4303 SDV = DAG.getDbgValue(Variable, N.getNode(), N.getResNo(),
4304 0, dl, SDNodeOrder);
4306 // Can't do anything with other non-AI cases yet.
4307 DEBUG(dbgs() << "Dropping debug info for " << DI);
4310 DAG.AddDbgValue(SDV, N.getNode(), isParameter);
4312 // If Address is an argument then try to emit its dbg value using
4313 // virtual register info from the FuncInfo.ValueMap.
4314 if (!EmitFuncArgumentDbgValue(Address, Variable, 0, N)) {
4315 // If variable is pinned by a alloca in dominating bb then
4316 // use StaticAllocaMap.
4317 if (const AllocaInst *AI = dyn_cast<AllocaInst>(Address)) {
4318 if (AI->getParent() != DI.getParent()) {
4319 DenseMap<const AllocaInst*, int>::iterator SI =
4320 FuncInfo.StaticAllocaMap.find(AI);
4321 if (SI != FuncInfo.StaticAllocaMap.end()) {
4322 SDV = DAG.getDbgValue(Variable, SI->second,
4323 0, dl, SDNodeOrder);
4324 DAG.AddDbgValue(SDV, 0, false);
4329 DEBUG(dbgs() << "Dropping debug info for " << DI);
4334 case Intrinsic::dbg_value: {
4335 const DbgValueInst &DI = cast<DbgValueInst>(I);
4336 if (!DIVariable(DI.getVariable()).Verify())
4339 MDNode *Variable = DI.getVariable();
4340 uint64_t Offset = DI.getOffset();
4341 const Value *V = DI.getValue();
4345 // Build an entry in DbgOrdering. Debug info input nodes get an SDNodeOrder
4346 // but do not always have a corresponding SDNode built. The SDNodeOrder
4347 // absolute, but not relative, values are different depending on whether
4348 // debug info exists.
4351 if (isa<ConstantInt>(V) || isa<ConstantFP>(V)) {
4352 SDV = DAG.getDbgValue(Variable, V, Offset, dl, SDNodeOrder);
4353 DAG.AddDbgValue(SDV, 0, false);
4355 // Do not use getValue() in here; we don't want to generate code at
4356 // this point if it hasn't been done yet.
4357 SDValue N = NodeMap[V];
4358 if (!N.getNode() && isa<Argument>(V))
4359 // Check unused arguments map.
4360 N = UnusedArgNodeMap[V];
4362 if (!EmitFuncArgumentDbgValue(V, Variable, Offset, N)) {
4363 SDV = DAG.getDbgValue(Variable, N.getNode(),
4364 N.getResNo(), Offset, dl, SDNodeOrder);
4365 DAG.AddDbgValue(SDV, N.getNode(), false);
4367 } else if (!V->use_empty() ) {
4368 // Do not call getValue(V) yet, as we don't want to generate code.
4369 // Remember it for later.
4370 DanglingDebugInfo DDI(&DI, dl, SDNodeOrder);
4371 DanglingDebugInfoMap[V] = DDI;
4373 // We may expand this to cover more cases. One case where we have no
4374 // data available is an unreferenced parameter.
4375 DEBUG(dbgs() << "Dropping debug info for " << DI);
4379 // Build a debug info table entry.
4380 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(V))
4381 V = BCI->getOperand(0);
4382 const AllocaInst *AI = dyn_cast<AllocaInst>(V);
4383 // Don't handle byval struct arguments or VLAs, for example.
4386 DenseMap<const AllocaInst*, int>::iterator SI =
4387 FuncInfo.StaticAllocaMap.find(AI);
4388 if (SI == FuncInfo.StaticAllocaMap.end())
4390 int FI = SI->second;
4392 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4393 if (!DI.getDebugLoc().isUnknown() && MMI.hasDebugInfo())
4394 MMI.setVariableDbgInfo(Variable, FI, DI.getDebugLoc());
4397 case Intrinsic::eh_exception: {
4398 // Insert the EXCEPTIONADDR instruction.
4399 assert(FuncInfo.MBB->isLandingPad() &&
4400 "Call to eh.exception not in landing pad!");
4401 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4403 Ops[0] = DAG.getRoot();
4404 SDValue Op = DAG.getNode(ISD::EXCEPTIONADDR, dl, VTs, Ops, 1);
4406 DAG.setRoot(Op.getValue(1));
4410 case Intrinsic::eh_selector: {
4411 MachineBasicBlock *CallMBB = FuncInfo.MBB;
4412 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4413 if (CallMBB->isLandingPad())
4414 AddCatchInfo(I, &MMI, CallMBB);
4417 FuncInfo.CatchInfoLost.insert(&I);
4419 // FIXME: Mark exception selector register as live in. Hack for PR1508.
4420 unsigned Reg = TLI.getExceptionSelectorRegister();
4421 if (Reg) FuncInfo.MBB->addLiveIn(Reg);
4424 // Insert the EHSELECTION instruction.
4425 SDVTList VTs = DAG.getVTList(TLI.getPointerTy(), MVT::Other);
4427 Ops[0] = getValue(I.getArgOperand(0));
4429 SDValue Op = DAG.getNode(ISD::EHSELECTION, dl, VTs, Ops, 2);
4430 DAG.setRoot(Op.getValue(1));
4431 setValue(&I, DAG.getSExtOrTrunc(Op, dl, MVT::i32));
4435 case Intrinsic::eh_typeid_for: {
4436 // Find the type id for the given typeinfo.
4437 GlobalVariable *GV = ExtractTypeInfo(I.getArgOperand(0));
4438 unsigned TypeID = DAG.getMachineFunction().getMMI().getTypeIDFor(GV);
4439 Res = DAG.getConstant(TypeID, MVT::i32);
4444 case Intrinsic::eh_return_i32:
4445 case Intrinsic::eh_return_i64:
4446 DAG.getMachineFunction().getMMI().setCallsEHReturn(true);
4447 DAG.setRoot(DAG.getNode(ISD::EH_RETURN, dl,
4450 getValue(I.getArgOperand(0)),
4451 getValue(I.getArgOperand(1))));
4453 case Intrinsic::eh_unwind_init:
4454 DAG.getMachineFunction().getMMI().setCallsUnwindInit(true);
4456 case Intrinsic::eh_dwarf_cfa: {
4457 SDValue CfaArg = DAG.getSExtOrTrunc(getValue(I.getArgOperand(0)), dl,
4458 TLI.getPointerTy());
4459 SDValue Offset = DAG.getNode(ISD::ADD, dl,
4461 DAG.getNode(ISD::FRAME_TO_ARGS_OFFSET, dl,
4462 TLI.getPointerTy()),
4464 SDValue FA = DAG.getNode(ISD::FRAMEADDR, dl,
4466 DAG.getConstant(0, TLI.getPointerTy()));
4467 setValue(&I, DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
4471 case Intrinsic::eh_sjlj_callsite: {
4472 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4473 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(0));
4474 assert(CI && "Non-constant call site value in eh.sjlj.callsite!");
4475 assert(MMI.getCurrentCallSite() == 0 && "Overlapping call sites!");
4477 MMI.setCurrentCallSite(CI->getZExtValue());
4480 case Intrinsic::eh_sjlj_setjmp: {
4481 setValue(&I, DAG.getNode(ISD::EH_SJLJ_SETJMP, dl, MVT::i32, getRoot(),
4482 getValue(I.getArgOperand(0))));
4485 case Intrinsic::eh_sjlj_longjmp: {
4486 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_LONGJMP, dl, MVT::Other,
4487 getRoot(), getValue(I.getArgOperand(0))));
4490 case Intrinsic::eh_sjlj_dispatch_setup: {
4491 DAG.setRoot(DAG.getNode(ISD::EH_SJLJ_DISPATCHSETUP, dl, MVT::Other,
4492 getRoot(), getValue(I.getArgOperand(0))));
4496 case Intrinsic::x86_mmx_pslli_w:
4497 case Intrinsic::x86_mmx_pslli_d:
4498 case Intrinsic::x86_mmx_pslli_q:
4499 case Intrinsic::x86_mmx_psrli_w:
4500 case Intrinsic::x86_mmx_psrli_d:
4501 case Intrinsic::x86_mmx_psrli_q:
4502 case Intrinsic::x86_mmx_psrai_w:
4503 case Intrinsic::x86_mmx_psrai_d: {
4504 SDValue ShAmt = getValue(I.getArgOperand(1));
4505 if (isa<ConstantSDNode>(ShAmt)) {
4506 visitTargetIntrinsic(I, Intrinsic);
4509 unsigned NewIntrinsic = 0;
4510 EVT ShAmtVT = MVT::v2i32;
4511 switch (Intrinsic) {
4512 case Intrinsic::x86_mmx_pslli_w:
4513 NewIntrinsic = Intrinsic::x86_mmx_psll_w;
4515 case Intrinsic::x86_mmx_pslli_d:
4516 NewIntrinsic = Intrinsic::x86_mmx_psll_d;
4518 case Intrinsic::x86_mmx_pslli_q:
4519 NewIntrinsic = Intrinsic::x86_mmx_psll_q;
4521 case Intrinsic::x86_mmx_psrli_w:
4522 NewIntrinsic = Intrinsic::x86_mmx_psrl_w;
4524 case Intrinsic::x86_mmx_psrli_d:
4525 NewIntrinsic = Intrinsic::x86_mmx_psrl_d;
4527 case Intrinsic::x86_mmx_psrli_q:
4528 NewIntrinsic = Intrinsic::x86_mmx_psrl_q;
4530 case Intrinsic::x86_mmx_psrai_w:
4531 NewIntrinsic = Intrinsic::x86_mmx_psra_w;
4533 case Intrinsic::x86_mmx_psrai_d:
4534 NewIntrinsic = Intrinsic::x86_mmx_psra_d;
4536 default: llvm_unreachable("Impossible intrinsic"); // Can't reach here.
4539 // The vector shift intrinsics with scalars uses 32b shift amounts but
4540 // the sse2/mmx shift instructions reads 64 bits. Set the upper 32 bits
4542 // We must do this early because v2i32 is not a legal type.
4543 DebugLoc dl = getCurDebugLoc();
4546 ShOps[1] = DAG.getConstant(0, MVT::i32);
4547 ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, ShAmtVT, &ShOps[0], 2);
4548 EVT DestVT = TLI.getValueType(I.getType());
4549 ShAmt = DAG.getNode(ISD::BITCAST, dl, DestVT, ShAmt);
4550 Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, DestVT,
4551 DAG.getConstant(NewIntrinsic, MVT::i32),
4552 getValue(I.getArgOperand(0)), ShAmt);
4556 case Intrinsic::convertff:
4557 case Intrinsic::convertfsi:
4558 case Intrinsic::convertfui:
4559 case Intrinsic::convertsif:
4560 case Intrinsic::convertuif:
4561 case Intrinsic::convertss:
4562 case Intrinsic::convertsu:
4563 case Intrinsic::convertus:
4564 case Intrinsic::convertuu: {
4565 ISD::CvtCode Code = ISD::CVT_INVALID;
4566 switch (Intrinsic) {
4567 case Intrinsic::convertff: Code = ISD::CVT_FF; break;
4568 case Intrinsic::convertfsi: Code = ISD::CVT_FS; break;
4569 case Intrinsic::convertfui: Code = ISD::CVT_FU; break;
4570 case Intrinsic::convertsif: Code = ISD::CVT_SF; break;
4571 case Intrinsic::convertuif: Code = ISD::CVT_UF; break;
4572 case Intrinsic::convertss: Code = ISD::CVT_SS; break;
4573 case Intrinsic::convertsu: Code = ISD::CVT_SU; break;
4574 case Intrinsic::convertus: Code = ISD::CVT_US; break;
4575 case Intrinsic::convertuu: Code = ISD::CVT_UU; break;
4577 EVT DestVT = TLI.getValueType(I.getType());
4578 const Value *Op1 = I.getArgOperand(0);
4579 Res = DAG.getConvertRndSat(DestVT, getCurDebugLoc(), getValue(Op1),
4580 DAG.getValueType(DestVT),
4581 DAG.getValueType(getValue(Op1).getValueType()),
4582 getValue(I.getArgOperand(1)),
4583 getValue(I.getArgOperand(2)),
4588 case Intrinsic::sqrt:
4589 setValue(&I, DAG.getNode(ISD::FSQRT, dl,
4590 getValue(I.getArgOperand(0)).getValueType(),
4591 getValue(I.getArgOperand(0))));
4593 case Intrinsic::powi:
4594 setValue(&I, ExpandPowI(dl, getValue(I.getArgOperand(0)),
4595 getValue(I.getArgOperand(1)), DAG));
4597 case Intrinsic::sin:
4598 setValue(&I, DAG.getNode(ISD::FSIN, dl,
4599 getValue(I.getArgOperand(0)).getValueType(),
4600 getValue(I.getArgOperand(0))));
4602 case Intrinsic::cos:
4603 setValue(&I, DAG.getNode(ISD::FCOS, dl,
4604 getValue(I.getArgOperand(0)).getValueType(),
4605 getValue(I.getArgOperand(0))));
4607 case Intrinsic::log:
4610 case Intrinsic::log2:
4613 case Intrinsic::log10:
4616 case Intrinsic::exp:
4619 case Intrinsic::exp2:
4622 case Intrinsic::pow:
4625 case Intrinsic::convert_to_fp16:
4626 setValue(&I, DAG.getNode(ISD::FP32_TO_FP16, dl,
4627 MVT::i16, getValue(I.getArgOperand(0))));
4629 case Intrinsic::convert_from_fp16:
4630 setValue(&I, DAG.getNode(ISD::FP16_TO_FP32, dl,
4631 MVT::f32, getValue(I.getArgOperand(0))));
4633 case Intrinsic::pcmarker: {
4634 SDValue Tmp = getValue(I.getArgOperand(0));
4635 DAG.setRoot(DAG.getNode(ISD::PCMARKER, dl, MVT::Other, getRoot(), Tmp));
4638 case Intrinsic::readcyclecounter: {
4639 SDValue Op = getRoot();
4640 Res = DAG.getNode(ISD::READCYCLECOUNTER, dl,
4641 DAG.getVTList(MVT::i64, MVT::Other),
4644 DAG.setRoot(Res.getValue(1));
4647 case Intrinsic::bswap:
4648 setValue(&I, DAG.getNode(ISD::BSWAP, dl,
4649 getValue(I.getArgOperand(0)).getValueType(),
4650 getValue(I.getArgOperand(0))));
4652 case Intrinsic::cttz: {
4653 SDValue Arg = getValue(I.getArgOperand(0));
4654 EVT Ty = Arg.getValueType();
4655 setValue(&I, DAG.getNode(ISD::CTTZ, dl, Ty, Arg));
4658 case Intrinsic::ctlz: {
4659 SDValue Arg = getValue(I.getArgOperand(0));
4660 EVT Ty = Arg.getValueType();
4661 setValue(&I, DAG.getNode(ISD::CTLZ, dl, Ty, Arg));
4664 case Intrinsic::ctpop: {
4665 SDValue Arg = getValue(I.getArgOperand(0));
4666 EVT Ty = Arg.getValueType();
4667 setValue(&I, DAG.getNode(ISD::CTPOP, dl, Ty, Arg));
4670 case Intrinsic::stacksave: {
4671 SDValue Op = getRoot();
4672 Res = DAG.getNode(ISD::STACKSAVE, dl,
4673 DAG.getVTList(TLI.getPointerTy(), MVT::Other), &Op, 1);
4675 DAG.setRoot(Res.getValue(1));
4678 case Intrinsic::stackrestore: {
4679 Res = getValue(I.getArgOperand(0));
4680 DAG.setRoot(DAG.getNode(ISD::STACKRESTORE, dl, MVT::Other, getRoot(), Res));
4683 case Intrinsic::stackprotector: {
4684 // Emit code into the DAG to store the stack guard onto the stack.
4685 MachineFunction &MF = DAG.getMachineFunction();
4686 MachineFrameInfo *MFI = MF.getFrameInfo();
4687 EVT PtrTy = TLI.getPointerTy();
4689 SDValue Src = getValue(I.getArgOperand(0)); // The guard's value.
4690 AllocaInst *Slot = cast<AllocaInst>(I.getArgOperand(1));
4692 int FI = FuncInfo.StaticAllocaMap[Slot];
4693 MFI->setStackProtectorIndex(FI);
4695 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4697 // Store the stack protector onto the stack.
4698 Res = DAG.getStore(getRoot(), getCurDebugLoc(), Src, FIN,
4699 MachinePointerInfo::getFixedStack(FI),
4705 case Intrinsic::objectsize: {
4706 // If we don't know by now, we're never going to know.
4707 ConstantInt *CI = dyn_cast<ConstantInt>(I.getArgOperand(1));
4709 assert(CI && "Non-constant type in __builtin_object_size?");
4711 SDValue Arg = getValue(I.getCalledValue());
4712 EVT Ty = Arg.getValueType();
4715 Res = DAG.getConstant(-1ULL, Ty);
4717 Res = DAG.getConstant(0, Ty);
4722 case Intrinsic::var_annotation:
4723 // Discard annotate attributes
4726 case Intrinsic::init_trampoline: {
4727 const Function *F = cast<Function>(I.getArgOperand(1)->stripPointerCasts());
4731 Ops[1] = getValue(I.getArgOperand(0));
4732 Ops[2] = getValue(I.getArgOperand(1));
4733 Ops[3] = getValue(I.getArgOperand(2));
4734 Ops[4] = DAG.getSrcValue(I.getArgOperand(0));
4735 Ops[5] = DAG.getSrcValue(F);
4737 Res = DAG.getNode(ISD::TRAMPOLINE, dl,
4738 DAG.getVTList(TLI.getPointerTy(), MVT::Other),
4742 DAG.setRoot(Res.getValue(1));
4745 case Intrinsic::gcroot:
4747 const Value *Alloca = I.getArgOperand(0);
4748 const Constant *TypeMap = cast<Constant>(I.getArgOperand(1));
4750 FrameIndexSDNode *FI = cast<FrameIndexSDNode>(getValue(Alloca).getNode());
4751 GFI->addStackRoot(FI->getIndex(), TypeMap);
4754 case Intrinsic::gcread:
4755 case Intrinsic::gcwrite:
4756 llvm_unreachable("GC failed to lower gcread/gcwrite intrinsics!");
4758 case Intrinsic::flt_rounds:
4759 setValue(&I, DAG.getNode(ISD::FLT_ROUNDS_, dl, MVT::i32));
4761 case Intrinsic::trap: {
4762 StringRef TrapFuncName = getTrapFunctionName();
4763 if (TrapFuncName.empty()) {
4764 DAG.setRoot(DAG.getNode(ISD::TRAP, dl,MVT::Other, getRoot()));
4767 TargetLowering::ArgListTy Args;
4768 std::pair<SDValue, SDValue> Result =
4769 TLI.LowerCallTo(getRoot(), I.getType(),
4770 false, false, false, false, 0, CallingConv::C,
4771 /*isTailCall=*/false, /*isReturnValueUsed=*/true,
4772 DAG.getExternalSymbol(TrapFuncName.data(), TLI.getPointerTy()),
4773 Args, DAG, getCurDebugLoc());
4774 DAG.setRoot(Result.second);
4777 case Intrinsic::uadd_with_overflow:
4778 return implVisitAluOverflow(I, ISD::UADDO);
4779 case Intrinsic::sadd_with_overflow:
4780 return implVisitAluOverflow(I, ISD::SADDO);
4781 case Intrinsic::usub_with_overflow:
4782 return implVisitAluOverflow(I, ISD::USUBO);
4783 case Intrinsic::ssub_with_overflow:
4784 return implVisitAluOverflow(I, ISD::SSUBO);
4785 case Intrinsic::umul_with_overflow:
4786 return implVisitAluOverflow(I, ISD::UMULO);
4787 case Intrinsic::smul_with_overflow:
4788 return implVisitAluOverflow(I, ISD::SMULO);
4790 case Intrinsic::prefetch: {
4792 unsigned rw = cast<ConstantInt>(I.getArgOperand(1))->getZExtValue();
4794 Ops[1] = getValue(I.getArgOperand(0));
4795 Ops[2] = getValue(I.getArgOperand(1));
4796 Ops[3] = getValue(I.getArgOperand(2));
4797 Ops[4] = getValue(I.getArgOperand(3));
4798 DAG.setRoot(DAG.getMemIntrinsicNode(ISD::PREFETCH, dl,
4799 DAG.getVTList(MVT::Other),
4801 EVT::getIntegerVT(*Context, 8),
4802 MachinePointerInfo(I.getArgOperand(0)),
4804 false, /* volatile */
4806 rw==1)); /* write */
4809 case Intrinsic::memory_barrier: {
4812 for (int x = 1; x < 6; ++x)
4813 Ops[x] = getValue(I.getArgOperand(x - 1));
4815 DAG.setRoot(DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, &Ops[0], 6));
4818 case Intrinsic::atomic_cmp_swap: {
4819 SDValue Root = getRoot();
4821 DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, getCurDebugLoc(),
4822 getValue(I.getArgOperand(1)).getValueType().getSimpleVT(),
4824 getValue(I.getArgOperand(0)),
4825 getValue(I.getArgOperand(1)),
4826 getValue(I.getArgOperand(2)),
4827 MachinePointerInfo(I.getArgOperand(0)));
4829 DAG.setRoot(L.getValue(1));
4832 case Intrinsic::atomic_load_add:
4833 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_ADD);
4834 case Intrinsic::atomic_load_sub:
4835 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_SUB);
4836 case Intrinsic::atomic_load_or:
4837 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_OR);
4838 case Intrinsic::atomic_load_xor:
4839 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_XOR);
4840 case Intrinsic::atomic_load_and:
4841 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_AND);
4842 case Intrinsic::atomic_load_nand:
4843 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_NAND);
4844 case Intrinsic::atomic_load_max:
4845 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MAX);
4846 case Intrinsic::atomic_load_min:
4847 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_MIN);
4848 case Intrinsic::atomic_load_umin:
4849 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMIN);
4850 case Intrinsic::atomic_load_umax:
4851 return implVisitBinaryAtomic(I, ISD::ATOMIC_LOAD_UMAX);
4852 case Intrinsic::atomic_swap:
4853 return implVisitBinaryAtomic(I, ISD::ATOMIC_SWAP);
4855 case Intrinsic::invariant_start:
4856 case Intrinsic::lifetime_start:
4857 // Discard region information.
4858 setValue(&I, DAG.getUNDEF(TLI.getPointerTy()));
4860 case Intrinsic::invariant_end:
4861 case Intrinsic::lifetime_end:
4862 // Discard region information.
4867 void SelectionDAGBuilder::LowerCallTo(ImmutableCallSite CS, SDValue Callee,
4869 MachineBasicBlock *LandingPad) {
4870 const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
4871 const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
4872 const Type *RetTy = FTy->getReturnType();
4873 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
4874 MCSymbol *BeginLabel = 0;
4876 TargetLowering::ArgListTy Args;
4877 TargetLowering::ArgListEntry Entry;
4878 Args.reserve(CS.arg_size());
4880 // Check whether the function can return without sret-demotion.
4881 SmallVector<ISD::OutputArg, 4> Outs;
4882 SmallVector<uint64_t, 4> Offsets;
4883 GetReturnInfo(RetTy, CS.getAttributes().getRetAttributes(),
4884 Outs, TLI, &Offsets);
4886 bool CanLowerReturn = TLI.CanLowerReturn(CS.getCallingConv(),
4887 DAG.getMachineFunction(),
4888 FTy->isVarArg(), Outs,
4891 SDValue DemoteStackSlot;
4892 int DemoteStackIdx = -100;
4894 if (!CanLowerReturn) {
4895 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(
4896 FTy->getReturnType());
4897 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(
4898 FTy->getReturnType());
4899 MachineFunction &MF = DAG.getMachineFunction();
4900 DemoteStackIdx = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
4901 const Type *StackSlotPtrType = PointerType::getUnqual(FTy->getReturnType());
4903 DemoteStackSlot = DAG.getFrameIndex(DemoteStackIdx, TLI.getPointerTy());
4904 Entry.Node = DemoteStackSlot;
4905 Entry.Ty = StackSlotPtrType;
4906 Entry.isSExt = false;
4907 Entry.isZExt = false;
4908 Entry.isInReg = false;
4909 Entry.isSRet = true;
4910 Entry.isNest = false;
4911 Entry.isByVal = false;
4912 Entry.Alignment = Align;
4913 Args.push_back(Entry);
4914 RetTy = Type::getVoidTy(FTy->getContext());
4917 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
4919 const Value *V = *i;
4922 if (V->getType()->isEmptyTy())
4925 SDValue ArgNode = getValue(V);
4926 Entry.Node = ArgNode; Entry.Ty = V->getType();
4928 unsigned attrInd = i - CS.arg_begin() + 1;
4929 Entry.isSExt = CS.paramHasAttr(attrInd, Attribute::SExt);
4930 Entry.isZExt = CS.paramHasAttr(attrInd, Attribute::ZExt);
4931 Entry.isInReg = CS.paramHasAttr(attrInd, Attribute::InReg);
4932 Entry.isSRet = CS.paramHasAttr(attrInd, Attribute::StructRet);
4933 Entry.isNest = CS.paramHasAttr(attrInd, Attribute::Nest);
4934 Entry.isByVal = CS.paramHasAttr(attrInd, Attribute::ByVal);
4935 Entry.Alignment = CS.getParamAlignment(attrInd);
4936 Args.push_back(Entry);
4940 // Insert a label before the invoke call to mark the try range. This can be
4941 // used to detect deletion of the invoke via the MachineModuleInfo.
4942 BeginLabel = MMI.getContext().CreateTempSymbol();
4944 // For SjLj, keep track of which landing pads go with which invokes
4945 // so as to maintain the ordering of pads in the LSDA.
4946 unsigned CallSiteIndex = MMI.getCurrentCallSite();
4947 if (CallSiteIndex) {
4948 MMI.setCallSiteBeginLabel(BeginLabel, CallSiteIndex);
4949 // Now that the call site is handled, stop tracking it.
4950 MMI.setCurrentCallSite(0);
4953 // Both PendingLoads and PendingExports must be flushed here;
4954 // this call might not return.
4956 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getControlRoot(), BeginLabel));
4959 // Check if target-independent constraints permit a tail call here.
4960 // Target-dependent constraints are checked within TLI.LowerCallTo.
4962 !isInTailCallPosition(CS, CS.getAttributes().getRetAttributes(), TLI))
4965 // If there's a possibility that fast-isel has already selected some amount
4966 // of the current basic block, don't emit a tail call.
4967 if (isTailCall && EnableFastISel)
4970 std::pair<SDValue,SDValue> Result =
4971 TLI.LowerCallTo(getRoot(), RetTy,
4972 CS.paramHasAttr(0, Attribute::SExt),
4973 CS.paramHasAttr(0, Attribute::ZExt), FTy->isVarArg(),
4974 CS.paramHasAttr(0, Attribute::InReg), FTy->getNumParams(),
4975 CS.getCallingConv(),
4977 !CS.getInstruction()->use_empty(),
4978 Callee, Args, DAG, getCurDebugLoc());
4979 assert((isTailCall || Result.second.getNode()) &&
4980 "Non-null chain expected with non-tail call!");
4981 assert((Result.second.getNode() || !Result.first.getNode()) &&
4982 "Null value expected with tail call!");
4983 if (Result.first.getNode()) {
4984 setValue(CS.getInstruction(), Result.first);
4985 } else if (!CanLowerReturn && Result.second.getNode()) {
4986 // The instruction result is the result of loading from the
4987 // hidden sret parameter.
4988 SmallVector<EVT, 1> PVTs;
4989 const Type *PtrRetTy = PointerType::getUnqual(FTy->getReturnType());
4991 ComputeValueVTs(TLI, PtrRetTy, PVTs);
4992 assert(PVTs.size() == 1 && "Pointers should fit in one register");
4993 EVT PtrVT = PVTs[0];
4994 unsigned NumValues = Outs.size();
4995 SmallVector<SDValue, 4> Values(NumValues);
4996 SmallVector<SDValue, 4> Chains(NumValues);
4998 for (unsigned i = 0; i < NumValues; ++i) {
4999 SDValue Add = DAG.getNode(ISD::ADD, getCurDebugLoc(), PtrVT,
5001 DAG.getConstant(Offsets[i], PtrVT));
5002 SDValue L = DAG.getLoad(Outs[i].VT, getCurDebugLoc(), Result.second,
5004 MachinePointerInfo::getFixedStack(DemoteStackIdx, Offsets[i]),
5007 Chains[i] = L.getValue(1);
5010 SDValue Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(),
5011 MVT::Other, &Chains[0], NumValues);
5012 PendingLoads.push_back(Chain);
5014 // Collect the legal value parts into potentially illegal values
5015 // that correspond to the original function's return values.
5016 SmallVector<EVT, 4> RetTys;
5017 RetTy = FTy->getReturnType();
5018 ComputeValueVTs(TLI, RetTy, RetTys);
5019 ISD::NodeType AssertOp = ISD::DELETED_NODE;
5020 SmallVector<SDValue, 4> ReturnValues;
5021 unsigned CurReg = 0;
5022 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
5024 EVT RegisterVT = TLI.getRegisterType(RetTy->getContext(), VT);
5025 unsigned NumRegs = TLI.getNumRegisters(RetTy->getContext(), VT);
5027 SDValue ReturnValue =
5028 getCopyFromParts(DAG, getCurDebugLoc(), &Values[CurReg], NumRegs,
5029 RegisterVT, VT, AssertOp);
5030 ReturnValues.push_back(ReturnValue);
5034 setValue(CS.getInstruction(),
5035 DAG.getNode(ISD::MERGE_VALUES, getCurDebugLoc(),
5036 DAG.getVTList(&RetTys[0], RetTys.size()),
5037 &ReturnValues[0], ReturnValues.size()));
5040 // Assign order to nodes here. If the call does not produce a result, it won't
5041 // be mapped to a SDNode and visit() will not assign it an order number.
5042 if (!Result.second.getNode()) {
5043 // As a special case, a null chain means that a tail call has been emitted and
5044 // the DAG root is already updated.
5047 AssignOrderingToNode(DAG.getRoot().getNode());
5049 DAG.setRoot(Result.second);
5051 AssignOrderingToNode(Result.second.getNode());
5055 // Insert a label at the end of the invoke call to mark the try range. This
5056 // can be used to detect deletion of the invoke via the MachineModuleInfo.
5057 MCSymbol *EndLabel = MMI.getContext().CreateTempSymbol();
5058 DAG.setRoot(DAG.getEHLabel(getCurDebugLoc(), getRoot(), EndLabel));
5060 // Inform MachineModuleInfo of range.
5061 MMI.addInvoke(LandingPad, BeginLabel, EndLabel);
5065 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
5066 /// value is equal or not-equal to zero.
5067 static bool IsOnlyUsedInZeroEqualityComparison(const Value *V) {
5068 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
5070 if (const ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
5071 if (IC->isEquality())
5072 if (const Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
5073 if (C->isNullValue())
5075 // Unknown instruction.
5081 static SDValue getMemCmpLoad(const Value *PtrVal, MVT LoadVT,
5083 SelectionDAGBuilder &Builder) {
5085 // Check to see if this load can be trivially constant folded, e.g. if the
5086 // input is from a string literal.
5087 if (const Constant *LoadInput = dyn_cast<Constant>(PtrVal)) {
5088 // Cast pointer to the type we really want to load.
5089 LoadInput = ConstantExpr::getBitCast(const_cast<Constant *>(LoadInput),
5090 PointerType::getUnqual(LoadTy));
5092 if (const Constant *LoadCst =
5093 ConstantFoldLoadFromConstPtr(const_cast<Constant *>(LoadInput),
5095 return Builder.getValue(LoadCst);
5098 // Otherwise, we have to emit the load. If the pointer is to unfoldable but
5099 // still constant memory, the input chain can be the entry node.
5101 bool ConstantMemory = false;
5103 // Do not serialize (non-volatile) loads of constant memory with anything.
5104 if (Builder.AA->pointsToConstantMemory(PtrVal)) {
5105 Root = Builder.DAG.getEntryNode();
5106 ConstantMemory = true;
5108 // Do not serialize non-volatile loads against each other.
5109 Root = Builder.DAG.getRoot();
5112 SDValue Ptr = Builder.getValue(PtrVal);
5113 SDValue LoadVal = Builder.DAG.getLoad(LoadVT, Builder.getCurDebugLoc(), Root,
5114 Ptr, MachinePointerInfo(PtrVal),
5116 false /*nontemporal*/, 1 /* align=1 */);
5118 if (!ConstantMemory)
5119 Builder.PendingLoads.push_back(LoadVal.getValue(1));
5124 /// visitMemCmpCall - See if we can lower a call to memcmp in an optimized form.
5125 /// If so, return true and lower it, otherwise return false and it will be
5126 /// lowered like a normal call.
5127 bool SelectionDAGBuilder::visitMemCmpCall(const CallInst &I) {
5128 // Verify that the prototype makes sense. int memcmp(void*,void*,size_t)
5129 if (I.getNumArgOperands() != 3)
5132 const Value *LHS = I.getArgOperand(0), *RHS = I.getArgOperand(1);
5133 if (!LHS->getType()->isPointerTy() || !RHS->getType()->isPointerTy() ||
5134 !I.getArgOperand(2)->getType()->isIntegerTy() ||
5135 !I.getType()->isIntegerTy())
5138 const ConstantInt *Size = dyn_cast<ConstantInt>(I.getArgOperand(2));
5140 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS != *(short*)RHS) != 0
5141 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS != *(int*)RHS) != 0
5142 if (Size && IsOnlyUsedInZeroEqualityComparison(&I)) {
5143 bool ActuallyDoIt = true;
5146 switch (Size->getZExtValue()) {
5148 LoadVT = MVT::Other;
5150 ActuallyDoIt = false;
5154 LoadTy = Type::getInt16Ty(Size->getContext());
5158 LoadTy = Type::getInt32Ty(Size->getContext());
5162 LoadTy = Type::getInt64Ty(Size->getContext());
5166 LoadVT = MVT::v4i32;
5167 LoadTy = Type::getInt32Ty(Size->getContext());
5168 LoadTy = VectorType::get(LoadTy, 4);
5173 // This turns into unaligned loads. We only do this if the target natively
5174 // supports the MVT we'll be loading or if it is small enough (<= 4) that
5175 // we'll only produce a small number of byte loads.
5177 // Require that we can find a legal MVT, and only do this if the target
5178 // supports unaligned loads of that type. Expanding into byte loads would
5180 if (ActuallyDoIt && Size->getZExtValue() > 4) {
5181 // TODO: Handle 5 byte compare as 4-byte + 1 byte.
5182 // TODO: Handle 8 byte compare on x86-32 as two 32-bit loads.
5183 if (!TLI.isTypeLegal(LoadVT) ||!TLI.allowsUnalignedMemoryAccesses(LoadVT))
5184 ActuallyDoIt = false;
5188 SDValue LHSVal = getMemCmpLoad(LHS, LoadVT, LoadTy, *this);
5189 SDValue RHSVal = getMemCmpLoad(RHS, LoadVT, LoadTy, *this);
5191 SDValue Res = DAG.getSetCC(getCurDebugLoc(), MVT::i1, LHSVal, RHSVal,
5193 EVT CallVT = TLI.getValueType(I.getType(), true);
5194 setValue(&I, DAG.getZExtOrTrunc(Res, getCurDebugLoc(), CallVT));
5204 void SelectionDAGBuilder::visitCall(const CallInst &I) {
5205 // Handle inline assembly differently.
5206 if (isa<InlineAsm>(I.getCalledValue())) {
5211 // See if any floating point values are being passed to this function. This is
5212 // used to emit an undefined reference to fltused on Windows.
5213 const FunctionType *FT =
5214 cast<FunctionType>(I.getCalledValue()->getType()->getContainedType(0));
5215 MachineModuleInfo &MMI = DAG.getMachineFunction().getMMI();
5216 if (FT->isVarArg() &&
5217 !MMI.callsExternalVAFunctionWithFloatingPointArguments()) {
5218 for (unsigned i = 0, e = I.getNumArgOperands(); i != e; ++i) {
5219 const Type* T = I.getArgOperand(i)->getType();
5220 for (po_iterator<const Type*> i = po_begin(T), e = po_end(T);
5222 if (!i->isFloatingPointTy()) continue;
5223 MMI.setCallsExternalVAFunctionWithFloatingPointArguments(true);
5229 const char *RenameFn = 0;
5230 if (Function *F = I.getCalledFunction()) {
5231 if (F->isDeclaration()) {
5232 if (const TargetIntrinsicInfo *II = TM.getIntrinsicInfo()) {
5233 if (unsigned IID = II->getIntrinsicID(F)) {
5234 RenameFn = visitIntrinsicCall(I, IID);
5239 if (unsigned IID = F->getIntrinsicID()) {
5240 RenameFn = visitIntrinsicCall(I, IID);
5246 // Check for well-known libc/libm calls. If the function is internal, it
5247 // can't be a library call.
5248 if (!F->hasLocalLinkage() && F->hasName()) {
5249 StringRef Name = F->getName();
5250 if (Name == "copysign" || Name == "copysignf" || Name == "copysignl") {
5251 if (I.getNumArgOperands() == 2 && // Basic sanity checks.
5252 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5253 I.getType() == I.getArgOperand(0)->getType() &&
5254 I.getType() == I.getArgOperand(1)->getType()) {
5255 SDValue LHS = getValue(I.getArgOperand(0));
5256 SDValue RHS = getValue(I.getArgOperand(1));
5257 setValue(&I, DAG.getNode(ISD::FCOPYSIGN, getCurDebugLoc(),
5258 LHS.getValueType(), LHS, RHS));
5261 } else if (Name == "fabs" || Name == "fabsf" || Name == "fabsl") {
5262 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5263 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5264 I.getType() == I.getArgOperand(0)->getType()) {
5265 SDValue Tmp = getValue(I.getArgOperand(0));
5266 setValue(&I, DAG.getNode(ISD::FABS, getCurDebugLoc(),
5267 Tmp.getValueType(), Tmp));
5270 } else if (Name == "sin" || Name == "sinf" || Name == "sinl") {
5271 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5272 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5273 I.getType() == I.getArgOperand(0)->getType() &&
5274 I.onlyReadsMemory()) {
5275 SDValue Tmp = getValue(I.getArgOperand(0));
5276 setValue(&I, DAG.getNode(ISD::FSIN, getCurDebugLoc(),
5277 Tmp.getValueType(), Tmp));
5280 } else if (Name == "cos" || Name == "cosf" || Name == "cosl") {
5281 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5282 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5283 I.getType() == I.getArgOperand(0)->getType() &&
5284 I.onlyReadsMemory()) {
5285 SDValue Tmp = getValue(I.getArgOperand(0));
5286 setValue(&I, DAG.getNode(ISD::FCOS, getCurDebugLoc(),
5287 Tmp.getValueType(), Tmp));
5290 } else if (Name == "sqrt" || Name == "sqrtf" || Name == "sqrtl") {
5291 if (I.getNumArgOperands() == 1 && // Basic sanity checks.
5292 I.getArgOperand(0)->getType()->isFloatingPointTy() &&
5293 I.getType() == I.getArgOperand(0)->getType() &&
5294 I.onlyReadsMemory()) {
5295 SDValue Tmp = getValue(I.getArgOperand(0));
5296 setValue(&I, DAG.getNode(ISD::FSQRT, getCurDebugLoc(),
5297 Tmp.getValueType(), Tmp));
5300 } else if (Name == "memcmp") {
5301 if (visitMemCmpCall(I))
5309 Callee = getValue(I.getCalledValue());
5311 Callee = DAG.getExternalSymbol(RenameFn, TLI.getPointerTy());
5313 // Check if we can potentially perform a tail call. More detailed checking is
5314 // be done within LowerCallTo, after more information about the call is known.
5315 LowerCallTo(&I, Callee, I.isTailCall());
5320 /// AsmOperandInfo - This contains information for each constraint that we are
5322 class SDISelAsmOperandInfo : public TargetLowering::AsmOperandInfo {
5324 /// CallOperand - If this is the result output operand or a clobber
5325 /// this is null, otherwise it is the incoming operand to the CallInst.
5326 /// This gets modified as the asm is processed.
5327 SDValue CallOperand;
5329 /// AssignedRegs - If this is a register or register class operand, this
5330 /// contains the set of register corresponding to the operand.
5331 RegsForValue AssignedRegs;
5333 explicit SDISelAsmOperandInfo(const TargetLowering::AsmOperandInfo &info)
5334 : TargetLowering::AsmOperandInfo(info), CallOperand(0,0) {
5337 /// MarkAllocatedRegs - Once AssignedRegs is set, mark the assigned registers
5338 /// busy in OutputRegs/InputRegs.
5339 void MarkAllocatedRegs(bool isOutReg, bool isInReg,
5340 std::set<unsigned> &OutputRegs,
5341 std::set<unsigned> &InputRegs,
5342 const TargetRegisterInfo &TRI) const {
5344 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
5345 MarkRegAndAliases(AssignedRegs.Regs[i], OutputRegs, TRI);
5348 for (unsigned i = 0, e = AssignedRegs.Regs.size(); i != e; ++i)
5349 MarkRegAndAliases(AssignedRegs.Regs[i], InputRegs, TRI);
5353 /// getCallOperandValEVT - Return the EVT of the Value* that this operand
5354 /// corresponds to. If there is no Value* for this operand, it returns
5356 EVT getCallOperandValEVT(LLVMContext &Context,
5357 const TargetLowering &TLI,
5358 const TargetData *TD) const {
5359 if (CallOperandVal == 0) return MVT::Other;
5361 if (isa<BasicBlock>(CallOperandVal))
5362 return TLI.getPointerTy();
5364 const llvm::Type *OpTy = CallOperandVal->getType();
5366 // FIXME: code duplicated from TargetLowering::ParseConstraints().
5367 // If this is an indirect operand, the operand is a pointer to the
5370 const llvm::PointerType *PtrTy = dyn_cast<PointerType>(OpTy);
5372 report_fatal_error("Indirect operand for inline asm not a pointer!");
5373 OpTy = PtrTy->getElementType();
5376 // Look for vector wrapped in a struct. e.g. { <16 x i8> }.
5377 if (const StructType *STy = dyn_cast<StructType>(OpTy))
5378 if (STy->getNumElements() == 1)
5379 OpTy = STy->getElementType(0);
5381 // If OpTy is not a single value, it may be a struct/union that we
5382 // can tile with integers.
5383 if (!OpTy->isSingleValueType() && OpTy->isSized()) {
5384 unsigned BitSize = TD->getTypeSizeInBits(OpTy);
5393 OpTy = IntegerType::get(Context, BitSize);
5398 return TLI.getValueType(OpTy, true);
5402 /// MarkRegAndAliases - Mark the specified register and all aliases in the
5404 static void MarkRegAndAliases(unsigned Reg, std::set<unsigned> &Regs,
5405 const TargetRegisterInfo &TRI) {
5406 assert(TargetRegisterInfo::isPhysicalRegister(Reg) && "Isn't a physreg");
5408 if (const unsigned *Aliases = TRI.getAliasSet(Reg))
5409 for (; *Aliases; ++Aliases)
5410 Regs.insert(*Aliases);
5414 typedef SmallVector<SDISelAsmOperandInfo,16> SDISelAsmOperandInfoVector;
5416 } // end anonymous namespace
5418 /// isAllocatableRegister - If the specified register is safe to allocate,
5419 /// i.e. it isn't a stack pointer or some other special register, return the
5420 /// register class for the register. Otherwise, return null.
5421 static const TargetRegisterClass *
5422 isAllocatableRegister(unsigned Reg, MachineFunction &MF,
5423 const TargetLowering &TLI,
5424 const TargetRegisterInfo *TRI) {
5425 EVT FoundVT = MVT::Other;
5426 const TargetRegisterClass *FoundRC = 0;
5427 for (TargetRegisterInfo::regclass_iterator RCI = TRI->regclass_begin(),
5428 E = TRI->regclass_end(); RCI != E; ++RCI) {
5429 EVT ThisVT = MVT::Other;
5431 const TargetRegisterClass *RC = *RCI;
5432 // If none of the value types for this register class are valid, we
5433 // can't use it. For example, 64-bit reg classes on 32-bit targets.
5434 for (TargetRegisterClass::vt_iterator I = RC->vt_begin(), E = RC->vt_end();
5436 if (TLI.isTypeLegal(*I)) {
5437 // If we have already found this register in a different register class,
5438 // choose the one with the largest VT specified. For example, on
5439 // PowerPC, we favor f64 register classes over f32.
5440 if (FoundVT == MVT::Other || FoundVT.bitsLT(*I)) {
5447 if (ThisVT == MVT::Other) continue;
5449 // NOTE: This isn't ideal. In particular, this might allocate the
5450 // frame pointer in functions that need it (due to them not being taken
5451 // out of allocation, because a variable sized allocation hasn't been seen
5452 // yet). This is a slight code pessimization, but should still work.
5453 for (TargetRegisterClass::iterator I = RC->allocation_order_begin(MF),
5454 E = RC->allocation_order_end(MF); I != E; ++I)
5456 // We found a matching register class. Keep looking at others in case
5457 // we find one with larger registers that this physreg is also in.
5466 /// GetRegistersForValue - Assign registers (virtual or physical) for the
5467 /// specified operand. We prefer to assign virtual registers, to allow the
5468 /// register allocator to handle the assignment process. However, if the asm
5469 /// uses features that we can't model on machineinstrs, we have SDISel do the
5470 /// allocation. This produces generally horrible, but correct, code.
5472 /// OpInfo describes the operand.
5473 /// Input and OutputRegs are the set of already allocated physical registers.
5475 static void GetRegistersForValue(SelectionDAG &DAG,
5476 const TargetLowering &TLI,
5478 SDISelAsmOperandInfo &OpInfo,
5479 std::set<unsigned> &OutputRegs,
5480 std::set<unsigned> &InputRegs) {
5481 LLVMContext &Context = *DAG.getContext();
5483 // Compute whether this value requires an input register, an output register,
5485 bool isOutReg = false;
5486 bool isInReg = false;
5487 switch (OpInfo.Type) {
5488 case InlineAsm::isOutput:
5491 // If there is an input constraint that matches this, we need to reserve
5492 // the input register so no other inputs allocate to it.
5493 isInReg = OpInfo.hasMatchingInput();
5495 case InlineAsm::isInput:
5499 case InlineAsm::isClobber:
5506 MachineFunction &MF = DAG.getMachineFunction();
5507 SmallVector<unsigned, 4> Regs;
5509 // If this is a constraint for a single physreg, or a constraint for a
5510 // register class, find it.
5511 std::pair<unsigned, const TargetRegisterClass*> PhysReg =
5512 TLI.getRegForInlineAsmConstraint(OpInfo.ConstraintCode,
5513 OpInfo.ConstraintVT);
5515 unsigned NumRegs = 1;
5516 if (OpInfo.ConstraintVT != MVT::Other) {
5517 // If this is a FP input in an integer register (or visa versa) insert a bit
5518 // cast of the input value. More generally, handle any case where the input
5519 // value disagrees with the register class we plan to stick this in.
5520 if (OpInfo.Type == InlineAsm::isInput &&
5521 PhysReg.second && !PhysReg.second->hasType(OpInfo.ConstraintVT)) {
5522 // Try to convert to the first EVT that the reg class contains. If the
5523 // types are identical size, use a bitcast to convert (e.g. two differing
5525 EVT RegVT = *PhysReg.second->vt_begin();
5526 if (RegVT.getSizeInBits() == OpInfo.ConstraintVT.getSizeInBits()) {
5527 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
5528 RegVT, OpInfo.CallOperand);
5529 OpInfo.ConstraintVT = RegVT;
5530 } else if (RegVT.isInteger() && OpInfo.ConstraintVT.isFloatingPoint()) {
5531 // If the input is a FP value and we want it in FP registers, do a
5532 // bitcast to the corresponding integer type. This turns an f64 value
5533 // into i64, which can be passed with two i32 values on a 32-bit
5535 RegVT = EVT::getIntegerVT(Context,
5536 OpInfo.ConstraintVT.getSizeInBits());
5537 OpInfo.CallOperand = DAG.getNode(ISD::BITCAST, DL,
5538 RegVT, OpInfo.CallOperand);
5539 OpInfo.ConstraintVT = RegVT;
5543 NumRegs = TLI.getNumRegisters(Context, OpInfo.ConstraintVT);
5547 EVT ValueVT = OpInfo.ConstraintVT;
5549 // If this is a constraint for a specific physical register, like {r17},
5551 if (unsigned AssignedReg = PhysReg.first) {
5552 const TargetRegisterClass *RC = PhysReg.second;
5553 if (OpInfo.ConstraintVT == MVT::Other)
5554 ValueVT = *RC->vt_begin();
5556 // Get the actual register value type. This is important, because the user
5557 // may have asked for (e.g.) the AX register in i32 type. We need to
5558 // remember that AX is actually i16 to get the right extension.
5559 RegVT = *RC->vt_begin();
5561 // This is a explicit reference to a physical register.
5562 Regs.push_back(AssignedReg);
5564 // If this is an expanded reference, add the rest of the regs to Regs.
5566 TargetRegisterClass::iterator I = RC->begin();
5567 for (; *I != AssignedReg; ++I)
5568 assert(I != RC->end() && "Didn't find reg!");
5570 // Already added the first reg.
5572 for (; NumRegs; --NumRegs, ++I) {
5573 assert(I != RC->end() && "Ran out of registers to allocate!");
5578 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
5579 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5580 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5584 // Otherwise, if this was a reference to an LLVM register class, create vregs
5585 // for this reference.
5586 if (const TargetRegisterClass *RC = PhysReg.second) {
5587 RegVT = *RC->vt_begin();
5588 if (OpInfo.ConstraintVT == MVT::Other)
5591 // Create the appropriate number of virtual registers.
5592 MachineRegisterInfo &RegInfo = MF.getRegInfo();
5593 for (; NumRegs; --NumRegs)
5594 Regs.push_back(RegInfo.createVirtualRegister(RC));
5596 OpInfo.AssignedRegs = RegsForValue(Regs, RegVT, ValueVT);
5600 // This is a reference to a register class that doesn't directly correspond
5601 // to an LLVM register class. Allocate NumRegs consecutive, available,
5602 // registers from the class.
5603 std::vector<unsigned> RegClassRegs
5604 = TLI.getRegClassForInlineAsmConstraint(OpInfo.ConstraintCode,
5605 OpInfo.ConstraintVT);
5607 const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
5608 unsigned NumAllocated = 0;
5609 for (unsigned i = 0, e = RegClassRegs.size(); i != e; ++i) {
5610 unsigned Reg = RegClassRegs[i];
5611 // See if this register is available.
5612 if ((isOutReg && OutputRegs.count(Reg)) || // Already used.
5613 (isInReg && InputRegs.count(Reg))) { // Already used.
5614 // Make sure we find consecutive registers.
5619 // Check to see if this register is allocatable (i.e. don't give out the
5621 const TargetRegisterClass *RC = isAllocatableRegister(Reg, MF, TLI, TRI);
5622 if (!RC) { // Couldn't allocate this register.
5623 // Reset NumAllocated to make sure we return consecutive registers.
5628 // Okay, this register is good, we can use it.
5631 // If we allocated enough consecutive registers, succeed.
5632 if (NumAllocated == NumRegs) {
5633 unsigned RegStart = (i-NumAllocated)+1;
5634 unsigned RegEnd = i+1;
5635 // Mark all of the allocated registers used.
5636 for (unsigned i = RegStart; i != RegEnd; ++i)
5637 Regs.push_back(RegClassRegs[i]);
5639 OpInfo.AssignedRegs = RegsForValue(Regs, *RC->vt_begin(),
5640 OpInfo.ConstraintVT);
5641 OpInfo.MarkAllocatedRegs(isOutReg, isInReg, OutputRegs, InputRegs, *TRI);
5646 // Otherwise, we couldn't allocate enough registers for this.
5649 /// visitInlineAsm - Handle a call to an InlineAsm object.
5651 void SelectionDAGBuilder::visitInlineAsm(ImmutableCallSite CS) {
5652 const InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
5654 /// ConstraintOperands - Information about all of the constraints.
5655 SDISelAsmOperandInfoVector ConstraintOperands;
5657 std::set<unsigned> OutputRegs, InputRegs;
5659 TargetLowering::AsmOperandInfoVector
5660 TargetConstraints = TLI.ParseConstraints(CS);
5662 bool hasMemory = false;
5664 unsigned ArgNo = 0; // ArgNo - The argument of the CallInst.
5665 unsigned ResNo = 0; // ResNo - The result number of the next output.
5666 for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
5667 ConstraintOperands.push_back(SDISelAsmOperandInfo(TargetConstraints[i]));
5668 SDISelAsmOperandInfo &OpInfo = ConstraintOperands.back();
5670 EVT OpVT = MVT::Other;
5672 // Compute the value type for each operand.
5673 switch (OpInfo.Type) {
5674 case InlineAsm::isOutput:
5675 // Indirect outputs just consume an argument.
5676 if (OpInfo.isIndirect) {
5677 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
5681 // The return value of the call is this value. As such, there is no
5682 // corresponding argument.
5683 assert(!CS.getType()->isVoidTy() &&
5685 if (const StructType *STy = dyn_cast<StructType>(CS.getType())) {
5686 OpVT = TLI.getValueType(STy->getElementType(ResNo));
5688 assert(ResNo == 0 && "Asm only has one result!");
5689 OpVT = TLI.getValueType(CS.getType());
5693 case InlineAsm::isInput:
5694 OpInfo.CallOperandVal = const_cast<Value *>(CS.getArgument(ArgNo++));
5696 case InlineAsm::isClobber:
5701 // If this is an input or an indirect output, process the call argument.
5702 // BasicBlocks are labels, currently appearing only in asm's.
5703 if (OpInfo.CallOperandVal) {
5704 if (const BasicBlock *BB = dyn_cast<BasicBlock>(OpInfo.CallOperandVal)) {
5705 OpInfo.CallOperand = DAG.getBasicBlock(FuncInfo.MBBMap[BB]);
5707 OpInfo.CallOperand = getValue(OpInfo.CallOperandVal);
5710 OpVT = OpInfo.getCallOperandValEVT(*DAG.getContext(), TLI, TD);
5713 OpInfo.ConstraintVT = OpVT;
5715 // Indirect operand accesses access memory.
5716 if (OpInfo.isIndirect)
5719 for (unsigned j = 0, ee = OpInfo.Codes.size(); j != ee; ++j) {
5720 TargetLowering::ConstraintType
5721 CType = TLI.getConstraintType(OpInfo.Codes[j]);
5722 if (CType == TargetLowering::C_Memory) {
5730 SDValue Chain, Flag;
5732 // We won't need to flush pending loads if this asm doesn't touch
5733 // memory and is nonvolatile.
5734 if (hasMemory || IA->hasSideEffects())
5737 Chain = DAG.getRoot();
5739 // Second pass over the constraints: compute which constraint option to use
5740 // and assign registers to constraints that want a specific physreg.
5741 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5742 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5744 // If this is an output operand with a matching input operand, look up the
5745 // matching input. If their types mismatch, e.g. one is an integer, the
5746 // other is floating point, or their sizes are different, flag it as an
5748 if (OpInfo.hasMatchingInput()) {
5749 SDISelAsmOperandInfo &Input = ConstraintOperands[OpInfo.MatchingInput];
5751 if (OpInfo.ConstraintVT != Input.ConstraintVT) {
5752 if ((OpInfo.ConstraintVT.isInteger() !=
5753 Input.ConstraintVT.isInteger()) ||
5754 (OpInfo.ConstraintVT.getSizeInBits() !=
5755 Input.ConstraintVT.getSizeInBits())) {
5756 report_fatal_error("Unsupported asm: input constraint"
5757 " with a matching output constraint of"
5758 " incompatible type!");
5760 Input.ConstraintVT = OpInfo.ConstraintVT;
5764 // Compute the constraint code and ConstraintType to use.
5765 TLI.ComputeConstraintToUse(OpInfo, OpInfo.CallOperand, &DAG);
5767 // If this is a memory input, and if the operand is not indirect, do what we
5768 // need to to provide an address for the memory input.
5769 if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
5770 !OpInfo.isIndirect) {
5771 assert((OpInfo.isMultipleAlternative ||
5772 (OpInfo.Type == InlineAsm::isInput)) &&
5773 "Can only indirectify direct input operands!");
5775 // Memory operands really want the address of the value. If we don't have
5776 // an indirect input, put it in the constpool if we can, otherwise spill
5777 // it to a stack slot.
5778 // TODO: This isn't quite right. We need to handle these according to
5779 // the addressing mode that the constraint wants. Also, this may take
5780 // an additional register for the computation and we don't want that
5783 // If the operand is a float, integer, or vector constant, spill to a
5784 // constant pool entry to get its address.
5785 const Value *OpVal = OpInfo.CallOperandVal;
5786 if (isa<ConstantFP>(OpVal) || isa<ConstantInt>(OpVal) ||
5787 isa<ConstantVector>(OpVal)) {
5788 OpInfo.CallOperand = DAG.getConstantPool(cast<Constant>(OpVal),
5789 TLI.getPointerTy());
5791 // Otherwise, create a stack slot and emit a store to it before the
5793 const Type *Ty = OpVal->getType();
5794 uint64_t TySize = TLI.getTargetData()->getTypeAllocSize(Ty);
5795 unsigned Align = TLI.getTargetData()->getPrefTypeAlignment(Ty);
5796 MachineFunction &MF = DAG.getMachineFunction();
5797 int SSFI = MF.getFrameInfo()->CreateStackObject(TySize, Align, false);
5798 SDValue StackSlot = DAG.getFrameIndex(SSFI, TLI.getPointerTy());
5799 Chain = DAG.getStore(Chain, getCurDebugLoc(),
5800 OpInfo.CallOperand, StackSlot,
5801 MachinePointerInfo::getFixedStack(SSFI),
5803 OpInfo.CallOperand = StackSlot;
5806 // There is no longer a Value* corresponding to this operand.
5807 OpInfo.CallOperandVal = 0;
5809 // It is now an indirect operand.
5810 OpInfo.isIndirect = true;
5813 // If this constraint is for a specific register, allocate it before
5815 if (OpInfo.ConstraintType == TargetLowering::C_Register)
5816 GetRegistersForValue(DAG, TLI, getCurDebugLoc(), OpInfo, OutputRegs,
5820 // Second pass - Loop over all of the operands, assigning virtual or physregs
5821 // to register class operands.
5822 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5823 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5825 // C_Register operands have already been allocated, Other/Memory don't need
5827 if (OpInfo.ConstraintType == TargetLowering::C_RegisterClass)
5828 GetRegistersForValue(DAG, TLI, getCurDebugLoc(), OpInfo, OutputRegs,
5832 // AsmNodeOperands - The operands for the ISD::INLINEASM node.
5833 std::vector<SDValue> AsmNodeOperands;
5834 AsmNodeOperands.push_back(SDValue()); // reserve space for input chain
5835 AsmNodeOperands.push_back(
5836 DAG.getTargetExternalSymbol(IA->getAsmString().c_str(),
5837 TLI.getPointerTy()));
5839 // If we have a !srcloc metadata node associated with it, we want to attach
5840 // this to the ultimately generated inline asm machineinstr. To do this, we
5841 // pass in the third operand as this (potentially null) inline asm MDNode.
5842 const MDNode *SrcLoc = CS.getInstruction()->getMetadata("srcloc");
5843 AsmNodeOperands.push_back(DAG.getMDNode(SrcLoc));
5845 // Remember the HasSideEffect and AlignStack bits as operand 3.
5846 unsigned ExtraInfo = 0;
5847 if (IA->hasSideEffects())
5848 ExtraInfo |= InlineAsm::Extra_HasSideEffects;
5849 if (IA->isAlignStack())
5850 ExtraInfo |= InlineAsm::Extra_IsAlignStack;
5851 AsmNodeOperands.push_back(DAG.getTargetConstant(ExtraInfo,
5852 TLI.getPointerTy()));
5854 // Loop over all of the inputs, copying the operand values into the
5855 // appropriate registers and processing the output regs.
5856 RegsForValue RetValRegs;
5858 // IndirectStoresToEmit - The set of stores to emit after the inline asm node.
5859 std::vector<std::pair<RegsForValue, Value*> > IndirectStoresToEmit;
5861 for (unsigned i = 0, e = ConstraintOperands.size(); i != e; ++i) {
5862 SDISelAsmOperandInfo &OpInfo = ConstraintOperands[i];
5864 switch (OpInfo.Type) {
5865 case InlineAsm::isOutput: {
5866 if (OpInfo.ConstraintType != TargetLowering::C_RegisterClass &&
5867 OpInfo.ConstraintType != TargetLowering::C_Register) {
5868 // Memory output, or 'other' output (e.g. 'X' constraint).
5869 assert(OpInfo.isIndirect && "Memory output must be indirect operand");
5871 // Add information to the INLINEASM node to know about this output.
5872 unsigned OpFlags = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
5873 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlags,
5874 TLI.getPointerTy()));
5875 AsmNodeOperands.push_back(OpInfo.CallOperand);
5879 // Otherwise, this is a register or register class output.
5881 // Copy the output from the appropriate register. Find a register that
5883 if (OpInfo.AssignedRegs.Regs.empty())
5884 report_fatal_error("Couldn't allocate output reg for constraint '" +
5885 Twine(OpInfo.ConstraintCode) + "'!");
5887 // If this is an indirect operand, store through the pointer after the
5889 if (OpInfo.isIndirect) {
5890 IndirectStoresToEmit.push_back(std::make_pair(OpInfo.AssignedRegs,
5891 OpInfo.CallOperandVal));
5893 // This is the result value of the call.
5894 assert(!CS.getType()->isVoidTy() && "Bad inline asm!");
5895 // Concatenate this output onto the outputs list.
5896 RetValRegs.append(OpInfo.AssignedRegs);
5899 // Add information to the INLINEASM node to know that this register is
5901 OpInfo.AssignedRegs.AddInlineAsmOperands(OpInfo.isEarlyClobber ?
5902 InlineAsm::Kind_RegDefEarlyClobber :
5903 InlineAsm::Kind_RegDef,
5910 case InlineAsm::isInput: {
5911 SDValue InOperandVal = OpInfo.CallOperand;
5913 if (OpInfo.isMatchingInputConstraint()) { // Matching constraint?
5914 // If this is required to match an output register we have already set,
5915 // just use its register.
5916 unsigned OperandNo = OpInfo.getMatchedOperand();
5918 // Scan until we find the definition we already emitted of this operand.
5919 // When we find it, create a RegsForValue operand.
5920 unsigned CurOp = InlineAsm::Op_FirstOperand;
5921 for (; OperandNo; --OperandNo) {
5922 // Advance to the next operand.
5924 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5925 assert((InlineAsm::isRegDefKind(OpFlag) ||
5926 InlineAsm::isRegDefEarlyClobberKind(OpFlag) ||
5927 InlineAsm::isMemKind(OpFlag)) && "Skipped past definitions?");
5928 CurOp += InlineAsm::getNumOperandRegisters(OpFlag)+1;
5932 cast<ConstantSDNode>(AsmNodeOperands[CurOp])->getZExtValue();
5933 if (InlineAsm::isRegDefKind(OpFlag) ||
5934 InlineAsm::isRegDefEarlyClobberKind(OpFlag)) {
5935 // Add (OpFlag&0xffff)>>3 registers to MatchedRegs.
5936 if (OpInfo.isIndirect) {
5937 // This happens on gcc/testsuite/gcc.dg/pr8788-1.c
5938 LLVMContext &Ctx = *DAG.getContext();
5939 Ctx.emitError(CS.getInstruction(), "inline asm not supported yet:"
5940 " don't know how to handle tied "
5941 "indirect register inputs");
5944 RegsForValue MatchedRegs;
5945 MatchedRegs.ValueVTs.push_back(InOperandVal.getValueType());
5946 EVT RegVT = AsmNodeOperands[CurOp+1].getValueType();
5947 MatchedRegs.RegVTs.push_back(RegVT);
5948 MachineRegisterInfo &RegInfo = DAG.getMachineFunction().getRegInfo();
5949 for (unsigned i = 0, e = InlineAsm::getNumOperandRegisters(OpFlag);
5951 MatchedRegs.Regs.push_back
5952 (RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT)));
5954 // Use the produced MatchedRegs object to
5955 MatchedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
5957 MatchedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse,
5958 true, OpInfo.getMatchedOperand(),
5959 DAG, AsmNodeOperands);
5963 assert(InlineAsm::isMemKind(OpFlag) && "Unknown matching constraint!");
5964 assert(InlineAsm::getNumOperandRegisters(OpFlag) == 1 &&
5965 "Unexpected number of operands");
5966 // Add information to the INLINEASM node to know about this input.
5967 // See InlineAsm.h isUseOperandTiedToDef.
5968 OpFlag = InlineAsm::getFlagWordForMatchingOp(OpFlag,
5969 OpInfo.getMatchedOperand());
5970 AsmNodeOperands.push_back(DAG.getTargetConstant(OpFlag,
5971 TLI.getPointerTy()));
5972 AsmNodeOperands.push_back(AsmNodeOperands[CurOp+1]);
5976 // Treat indirect 'X' constraint as memory.
5977 if (OpInfo.ConstraintType == TargetLowering::C_Other &&
5979 OpInfo.ConstraintType = TargetLowering::C_Memory;
5981 if (OpInfo.ConstraintType == TargetLowering::C_Other) {
5982 std::vector<SDValue> Ops;
5983 TLI.LowerAsmOperandForConstraint(InOperandVal, OpInfo.ConstraintCode,
5986 report_fatal_error("Invalid operand for inline asm constraint '" +
5987 Twine(OpInfo.ConstraintCode) + "'!");
5989 // Add information to the INLINEASM node to know about this input.
5990 unsigned ResOpType =
5991 InlineAsm::getFlagWord(InlineAsm::Kind_Imm, Ops.size());
5992 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
5993 TLI.getPointerTy()));
5994 AsmNodeOperands.insert(AsmNodeOperands.end(), Ops.begin(), Ops.end());
5998 if (OpInfo.ConstraintType == TargetLowering::C_Memory) {
5999 assert(OpInfo.isIndirect && "Operand must be indirect to be a mem!");
6000 assert(InOperandVal.getValueType() == TLI.getPointerTy() &&
6001 "Memory operands expect pointer values");
6003 // Add information to the INLINEASM node to know about this input.
6004 unsigned ResOpType = InlineAsm::getFlagWord(InlineAsm::Kind_Mem, 1);
6005 AsmNodeOperands.push_back(DAG.getTargetConstant(ResOpType,
6006 TLI.getPointerTy()));
6007 AsmNodeOperands.push_back(InOperandVal);
6011 assert((OpInfo.ConstraintType == TargetLowering::C_RegisterClass ||
6012 OpInfo.ConstraintType == TargetLowering::C_Register) &&
6013 "Unknown constraint type!");
6014 assert(!OpInfo.isIndirect &&
6015 "Don't know how to handle indirect register inputs yet!");
6017 // Copy the input into the appropriate registers.
6018 if (OpInfo.AssignedRegs.Regs.empty() ||
6019 !OpInfo.AssignedRegs.areValueTypesLegal(TLI))
6020 report_fatal_error("Couldn't allocate input reg for constraint '" +
6021 Twine(OpInfo.ConstraintCode) + "'!");
6023 OpInfo.AssignedRegs.getCopyToRegs(InOperandVal, DAG, getCurDebugLoc(),
6026 OpInfo.AssignedRegs.AddInlineAsmOperands(InlineAsm::Kind_RegUse, false, 0,
6027 DAG, AsmNodeOperands);
6030 case InlineAsm::isClobber: {
6031 // Add the clobbered value to the operand list, so that the register
6032 // allocator is aware that the physreg got clobbered.
6033 if (!OpInfo.AssignedRegs.Regs.empty())
6034 OpInfo.AssignedRegs.AddInlineAsmOperands(
6035 InlineAsm::Kind_RegDefEarlyClobber,
6043 // Finish up input operands. Set the input chain and add the flag last.
6044 AsmNodeOperands[InlineAsm::Op_InputChain] = Chain;
6045 if (Flag.getNode()) AsmNodeOperands.push_back(Flag);
6047 Chain = DAG.getNode(ISD::INLINEASM, getCurDebugLoc(),
6048 DAG.getVTList(MVT::Other, MVT::Glue),
6049 &AsmNodeOperands[0], AsmNodeOperands.size());
6050 Flag = Chain.getValue(1);
6052 // If this asm returns a register value, copy the result from that register
6053 // and set it as the value of the call.
6054 if (!RetValRegs.Regs.empty()) {
6055 SDValue Val = RetValRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(),
6058 // FIXME: Why don't we do this for inline asms with MRVs?
6059 if (CS.getType()->isSingleValueType() && CS.getType()->isSized()) {
6060 EVT ResultType = TLI.getValueType(CS.getType());
6062 // If any of the results of the inline asm is a vector, it may have the
6063 // wrong width/num elts. This can happen for register classes that can
6064 // contain multiple different value types. The preg or vreg allocated may
6065 // not have the same VT as was expected. Convert it to the right type
6066 // with bit_convert.
6067 if (ResultType != Val.getValueType() && Val.getValueType().isVector()) {
6068 Val = DAG.getNode(ISD::BITCAST, getCurDebugLoc(),
6071 } else if (ResultType != Val.getValueType() &&
6072 ResultType.isInteger() && Val.getValueType().isInteger()) {
6073 // If a result value was tied to an input value, the computed result may
6074 // have a wider width than the expected result. Extract the relevant
6076 Val = DAG.getNode(ISD::TRUNCATE, getCurDebugLoc(), ResultType, Val);
6079 assert(ResultType == Val.getValueType() && "Asm result value mismatch!");
6082 setValue(CS.getInstruction(), Val);
6083 // Don't need to use this as a chain in this case.
6084 if (!IA->hasSideEffects() && !hasMemory && IndirectStoresToEmit.empty())
6088 std::vector<std::pair<SDValue, const Value *> > StoresToEmit;
6090 // Process indirect outputs, first output all of the flagged copies out of
6092 for (unsigned i = 0, e = IndirectStoresToEmit.size(); i != e; ++i) {
6093 RegsForValue &OutRegs = IndirectStoresToEmit[i].first;
6094 const Value *Ptr = IndirectStoresToEmit[i].second;
6095 SDValue OutVal = OutRegs.getCopyFromRegs(DAG, FuncInfo, getCurDebugLoc(),
6097 StoresToEmit.push_back(std::make_pair(OutVal, Ptr));
6100 // Emit the non-flagged stores from the physregs.
6101 SmallVector<SDValue, 8> OutChains;
6102 for (unsigned i = 0, e = StoresToEmit.size(); i != e; ++i) {
6103 SDValue Val = DAG.getStore(Chain, getCurDebugLoc(),
6104 StoresToEmit[i].first,
6105 getValue(StoresToEmit[i].second),
6106 MachinePointerInfo(StoresToEmit[i].second),
6108 OutChains.push_back(Val);
6111 if (!OutChains.empty())
6112 Chain = DAG.getNode(ISD::TokenFactor, getCurDebugLoc(), MVT::Other,
6113 &OutChains[0], OutChains.size());
6118 void SelectionDAGBuilder::visitVAStart(const CallInst &I) {
6119 DAG.setRoot(DAG.getNode(ISD::VASTART, getCurDebugLoc(),
6120 MVT::Other, getRoot(),
6121 getValue(I.getArgOperand(0)),
6122 DAG.getSrcValue(I.getArgOperand(0))));
6125 void SelectionDAGBuilder::visitVAArg(const VAArgInst &I) {
6126 const TargetData &TD = *TLI.getTargetData();
6127 SDValue V = DAG.getVAArg(TLI.getValueType(I.getType()), getCurDebugLoc(),
6128 getRoot(), getValue(I.getOperand(0)),
6129 DAG.getSrcValue(I.getOperand(0)),
6130 TD.getABITypeAlignment(I.getType()));
6132 DAG.setRoot(V.getValue(1));
6135 void SelectionDAGBuilder::visitVAEnd(const CallInst &I) {
6136 DAG.setRoot(DAG.getNode(ISD::VAEND, getCurDebugLoc(),
6137 MVT::Other, getRoot(),
6138 getValue(I.getArgOperand(0)),
6139 DAG.getSrcValue(I.getArgOperand(0))));
6142 void SelectionDAGBuilder::visitVACopy(const CallInst &I) {
6143 DAG.setRoot(DAG.getNode(ISD::VACOPY, getCurDebugLoc(),
6144 MVT::Other, getRoot(),
6145 getValue(I.getArgOperand(0)),
6146 getValue(I.getArgOperand(1)),
6147 DAG.getSrcValue(I.getArgOperand(0)),
6148 DAG.getSrcValue(I.getArgOperand(1))));
6151 /// TargetLowering::LowerCallTo - This is the default LowerCallTo
6152 /// implementation, which just calls LowerCall.
6153 /// FIXME: When all targets are
6154 /// migrated to using LowerCall, this hook should be integrated into SDISel.
6155 std::pair<SDValue, SDValue>
6156 TargetLowering::LowerCallTo(SDValue Chain, const Type *RetTy,
6157 bool RetSExt, bool RetZExt, bool isVarArg,
6158 bool isInreg, unsigned NumFixedArgs,
6159 CallingConv::ID CallConv, bool isTailCall,
6160 bool isReturnValueUsed,
6162 ArgListTy &Args, SelectionDAG &DAG,
6163 DebugLoc dl) const {
6164 // Handle all of the outgoing arguments.
6165 SmallVector<ISD::OutputArg, 32> Outs;
6166 SmallVector<SDValue, 32> OutVals;
6167 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
6168 SmallVector<EVT, 4> ValueVTs;
6169 ComputeValueVTs(*this, Args[i].Ty, ValueVTs);
6170 for (unsigned Value = 0, NumValues = ValueVTs.size();
6171 Value != NumValues; ++Value) {
6172 EVT VT = ValueVTs[Value];
6173 const Type *ArgTy = VT.getTypeForEVT(RetTy->getContext());
6174 SDValue Op = SDValue(Args[i].Node.getNode(),
6175 Args[i].Node.getResNo() + Value);
6176 ISD::ArgFlagsTy Flags;
6177 unsigned OriginalAlignment =
6178 getTargetData()->getABITypeAlignment(ArgTy);
6184 if (Args[i].isInReg)
6188 if (Args[i].isByVal) {
6190 const PointerType *Ty = cast<PointerType>(Args[i].Ty);
6191 const Type *ElementTy = Ty->getElementType();
6192 Flags.setByValSize(getTargetData()->getTypeAllocSize(ElementTy));
6193 // For ByVal, alignment should come from FE. BE will guess if this
6194 // info is not there but there are cases it cannot get right.
6195 unsigned FrameAlign;
6196 if (Args[i].Alignment)
6197 FrameAlign = Args[i].Alignment;
6199 FrameAlign = getByValTypeAlignment(ElementTy);
6200 Flags.setByValAlign(FrameAlign);
6204 Flags.setOrigAlign(OriginalAlignment);
6206 EVT PartVT = getRegisterType(RetTy->getContext(), VT);
6207 unsigned NumParts = getNumRegisters(RetTy->getContext(), VT);
6208 SmallVector<SDValue, 4> Parts(NumParts);
6209 ISD::NodeType ExtendKind = ISD::ANY_EXTEND;
6212 ExtendKind = ISD::SIGN_EXTEND;
6213 else if (Args[i].isZExt)
6214 ExtendKind = ISD::ZERO_EXTEND;
6216 getCopyToParts(DAG, dl, Op, &Parts[0], NumParts,
6217 PartVT, ExtendKind);
6219 for (unsigned j = 0; j != NumParts; ++j) {
6220 // if it isn't first piece, alignment must be 1
6221 ISD::OutputArg MyFlags(Flags, Parts[j].getValueType(),
6223 if (NumParts > 1 && j == 0)
6224 MyFlags.Flags.setSplit();
6226 MyFlags.Flags.setOrigAlign(1);
6228 Outs.push_back(MyFlags);
6229 OutVals.push_back(Parts[j]);
6234 // Handle the incoming return values from the call.
6235 SmallVector<ISD::InputArg, 32> Ins;
6236 SmallVector<EVT, 4> RetTys;
6237 ComputeValueVTs(*this, RetTy, RetTys);
6238 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6240 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
6241 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
6242 for (unsigned i = 0; i != NumRegs; ++i) {
6243 ISD::InputArg MyFlags;
6244 MyFlags.VT = RegisterVT.getSimpleVT();
6245 MyFlags.Used = isReturnValueUsed;
6247 MyFlags.Flags.setSExt();
6249 MyFlags.Flags.setZExt();
6251 MyFlags.Flags.setInReg();
6252 Ins.push_back(MyFlags);
6256 SmallVector<SDValue, 4> InVals;
6257 Chain = LowerCall(Chain, Callee, CallConv, isVarArg, isTailCall,
6258 Outs, OutVals, Ins, dl, DAG, InVals);
6260 // Verify that the target's LowerCall behaved as expected.
6261 assert(Chain.getNode() && Chain.getValueType() == MVT::Other &&
6262 "LowerCall didn't return a valid chain!");
6263 assert((!isTailCall || InVals.empty()) &&
6264 "LowerCall emitted a return value for a tail call!");
6265 assert((isTailCall || InVals.size() == Ins.size()) &&
6266 "LowerCall didn't emit the correct number of values!");
6268 // For a tail call, the return value is merely live-out and there aren't
6269 // any nodes in the DAG representing it. Return a special value to
6270 // indicate that a tail call has been emitted and no more Instructions
6271 // should be processed in the current block.
6274 return std::make_pair(SDValue(), SDValue());
6277 DEBUG(for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6278 assert(InVals[i].getNode() &&
6279 "LowerCall emitted a null value!");
6280 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
6281 "LowerCall emitted a value with the wrong type!");
6284 // Collect the legal value parts into potentially illegal values
6285 // that correspond to the original function's return values.
6286 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6288 AssertOp = ISD::AssertSext;
6290 AssertOp = ISD::AssertZext;
6291 SmallVector<SDValue, 4> ReturnValues;
6292 unsigned CurReg = 0;
6293 for (unsigned I = 0, E = RetTys.size(); I != E; ++I) {
6295 EVT RegisterVT = getRegisterType(RetTy->getContext(), VT);
6296 unsigned NumRegs = getNumRegisters(RetTy->getContext(), VT);
6298 ReturnValues.push_back(getCopyFromParts(DAG, dl, &InVals[CurReg],
6299 NumRegs, RegisterVT, VT,
6304 // For a function returning void, there is no return value. We can't create
6305 // such a node, so we just return a null return value in that case. In
6306 // that case, nothing will actually look at the value.
6307 if (ReturnValues.empty())
6308 return std::make_pair(SDValue(), Chain);
6310 SDValue Res = DAG.getNode(ISD::MERGE_VALUES, dl,
6311 DAG.getVTList(&RetTys[0], RetTys.size()),
6312 &ReturnValues[0], ReturnValues.size());
6313 return std::make_pair(Res, Chain);
6316 void TargetLowering::LowerOperationWrapper(SDNode *N,
6317 SmallVectorImpl<SDValue> &Results,
6318 SelectionDAG &DAG) const {
6319 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
6321 Results.push_back(Res);
6324 SDValue TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
6325 llvm_unreachable("LowerOperation not implemented for this target!");
6330 SelectionDAGBuilder::CopyValueToVirtualRegister(const Value *V, unsigned Reg) {
6331 SDValue Op = getNonRegisterValue(V);
6332 assert((Op.getOpcode() != ISD::CopyFromReg ||
6333 cast<RegisterSDNode>(Op.getOperand(1))->getReg() != Reg) &&
6334 "Copy from a reg to the same reg!");
6335 assert(!TargetRegisterInfo::isPhysicalRegister(Reg) && "Is a physreg");
6337 RegsForValue RFV(V->getContext(), TLI, Reg, V->getType());
6338 SDValue Chain = DAG.getEntryNode();
6339 RFV.getCopyToRegs(Op, DAG, getCurDebugLoc(), Chain, 0);
6340 PendingExports.push_back(Chain);
6343 #include "llvm/CodeGen/SelectionDAGISel.h"
6345 /// isOnlyUsedInEntryBlock - If the specified argument is only used in the
6346 /// entry block, return true. This includes arguments used by switches, since
6347 /// the switch may expand into multiple basic blocks.
6348 static bool isOnlyUsedInEntryBlock(const Argument *A) {
6349 // With FastISel active, we may be splitting blocks, so force creation
6350 // of virtual registers for all non-dead arguments.
6352 return A->use_empty();
6354 const BasicBlock *Entry = A->getParent()->begin();
6355 for (Value::const_use_iterator UI = A->use_begin(), E = A->use_end();
6357 const User *U = *UI;
6358 if (cast<Instruction>(U)->getParent() != Entry || isa<SwitchInst>(U))
6359 return false; // Use not in entry block.
6364 void SelectionDAGISel::LowerArguments(const BasicBlock *LLVMBB) {
6365 // If this is the entry block, emit arguments.
6366 const Function &F = *LLVMBB->getParent();
6367 SelectionDAG &DAG = SDB->DAG;
6368 DebugLoc dl = SDB->getCurDebugLoc();
6369 const TargetData *TD = TLI.getTargetData();
6370 SmallVector<ISD::InputArg, 16> Ins;
6372 // Check whether the function can return without sret-demotion.
6373 SmallVector<ISD::OutputArg, 4> Outs;
6374 GetReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
6377 if (!FuncInfo->CanLowerReturn) {
6378 // Put in an sret pointer parameter before all the other parameters.
6379 SmallVector<EVT, 1> ValueVTs;
6380 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6382 // NOTE: Assuming that a pointer will never break down to more than one VT
6384 ISD::ArgFlagsTy Flags;
6386 EVT RegisterVT = TLI.getRegisterType(*DAG.getContext(), ValueVTs[0]);
6387 ISD::InputArg RetArg(Flags, RegisterVT, true);
6388 Ins.push_back(RetArg);
6391 // Set up the incoming argument description vector.
6393 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
6394 I != E; ++I, ++Idx) {
6395 SmallVector<EVT, 4> ValueVTs;
6396 ComputeValueVTs(TLI, I->getType(), ValueVTs);
6397 bool isArgValueUsed = !I->use_empty();
6398 for (unsigned Value = 0, NumValues = ValueVTs.size();
6399 Value != NumValues; ++Value) {
6400 EVT VT = ValueVTs[Value];
6401 const Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
6402 ISD::ArgFlagsTy Flags;
6403 unsigned OriginalAlignment =
6404 TD->getABITypeAlignment(ArgTy);
6406 if (F.paramHasAttr(Idx, Attribute::ZExt))
6408 if (F.paramHasAttr(Idx, Attribute::SExt))
6410 if (F.paramHasAttr(Idx, Attribute::InReg))
6412 if (F.paramHasAttr(Idx, Attribute::StructRet))
6414 if (F.paramHasAttr(Idx, Attribute::ByVal)) {
6416 const PointerType *Ty = cast<PointerType>(I->getType());
6417 const Type *ElementTy = Ty->getElementType();
6418 Flags.setByValSize(TD->getTypeAllocSize(ElementTy));
6419 // For ByVal, alignment should be passed from FE. BE will guess if
6420 // this info is not there but there are cases it cannot get right.
6421 unsigned FrameAlign;
6422 if (F.getParamAlignment(Idx))
6423 FrameAlign = F.getParamAlignment(Idx);
6425 FrameAlign = TLI.getByValTypeAlignment(ElementTy);
6426 Flags.setByValAlign(FrameAlign);
6428 if (F.paramHasAttr(Idx, Attribute::Nest))
6430 Flags.setOrigAlign(OriginalAlignment);
6432 EVT RegisterVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6433 unsigned NumRegs = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6434 for (unsigned i = 0; i != NumRegs; ++i) {
6435 ISD::InputArg MyFlags(Flags, RegisterVT, isArgValueUsed);
6436 if (NumRegs > 1 && i == 0)
6437 MyFlags.Flags.setSplit();
6438 // if it isn't first piece, alignment must be 1
6440 MyFlags.Flags.setOrigAlign(1);
6441 Ins.push_back(MyFlags);
6446 // Call the target to set up the argument values.
6447 SmallVector<SDValue, 8> InVals;
6448 SDValue NewRoot = TLI.LowerFormalArguments(DAG.getRoot(), F.getCallingConv(),
6452 // Verify that the target's LowerFormalArguments behaved as expected.
6453 assert(NewRoot.getNode() && NewRoot.getValueType() == MVT::Other &&
6454 "LowerFormalArguments didn't return a valid chain!");
6455 assert(InVals.size() == Ins.size() &&
6456 "LowerFormalArguments didn't emit the correct number of values!");
6458 for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
6459 assert(InVals[i].getNode() &&
6460 "LowerFormalArguments emitted a null value!");
6461 assert(EVT(Ins[i].VT) == InVals[i].getValueType() &&
6462 "LowerFormalArguments emitted a value with the wrong type!");
6466 // Update the DAG with the new chain value resulting from argument lowering.
6467 DAG.setRoot(NewRoot);
6469 // Set up the argument values.
6472 if (!FuncInfo->CanLowerReturn) {
6473 // Create a virtual register for the sret pointer, and put in a copy
6474 // from the sret argument into it.
6475 SmallVector<EVT, 1> ValueVTs;
6476 ComputeValueVTs(TLI, PointerType::getUnqual(F.getReturnType()), ValueVTs);
6477 EVT VT = ValueVTs[0];
6478 EVT RegVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6479 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6480 SDValue ArgValue = getCopyFromParts(DAG, dl, &InVals[0], 1,
6481 RegVT, VT, AssertOp);
6483 MachineFunction& MF = SDB->DAG.getMachineFunction();
6484 MachineRegisterInfo& RegInfo = MF.getRegInfo();
6485 unsigned SRetReg = RegInfo.createVirtualRegister(TLI.getRegClassFor(RegVT));
6486 FuncInfo->DemoteRegister = SRetReg;
6487 NewRoot = SDB->DAG.getCopyToReg(NewRoot, SDB->getCurDebugLoc(),
6489 DAG.setRoot(NewRoot);
6491 // i indexes lowered arguments. Bump it past the hidden sret argument.
6492 // Idx indexes LLVM arguments. Don't touch it.
6496 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E;
6498 SmallVector<SDValue, 4> ArgValues;
6499 SmallVector<EVT, 4> ValueVTs;
6500 ComputeValueVTs(TLI, I->getType(), ValueVTs);
6501 unsigned NumValues = ValueVTs.size();
6503 // If this argument is unused then remember its value. It is used to generate
6504 // debugging information.
6505 if (I->use_empty() && NumValues)
6506 SDB->setUnusedArgValue(I, InVals[i]);
6508 for (unsigned Val = 0; Val != NumValues; ++Val) {
6509 EVT VT = ValueVTs[Val];
6510 EVT PartVT = TLI.getRegisterType(*CurDAG->getContext(), VT);
6511 unsigned NumParts = TLI.getNumRegisters(*CurDAG->getContext(), VT);
6513 if (!I->use_empty()) {
6514 ISD::NodeType AssertOp = ISD::DELETED_NODE;
6515 if (F.paramHasAttr(Idx, Attribute::SExt))
6516 AssertOp = ISD::AssertSext;
6517 else if (F.paramHasAttr(Idx, Attribute::ZExt))
6518 AssertOp = ISD::AssertZext;
6520 ArgValues.push_back(getCopyFromParts(DAG, dl, &InVals[i],
6521 NumParts, PartVT, VT,
6528 // We don't need to do anything else for unused arguments.
6529 if (ArgValues.empty())
6532 // Note down frame index for byval arguments.
6533 if (I->hasByValAttr())
6534 if (FrameIndexSDNode *FI =
6535 dyn_cast<FrameIndexSDNode>(ArgValues[0].getNode()))
6536 FuncInfo->setByValArgumentFrameIndex(I, FI->getIndex());
6538 SDValue Res = DAG.getMergeValues(&ArgValues[0], NumValues,
6539 SDB->getCurDebugLoc());
6540 SDB->setValue(I, Res);
6542 // If this argument is live outside of the entry block, insert a copy from
6543 // wherever we got it to the vreg that other BB's will reference it as.
6544 if (!EnableFastISel && Res.getOpcode() == ISD::CopyFromReg) {
6545 // If we can, though, try to skip creating an unnecessary vreg.
6546 // FIXME: This isn't very clean... it would be nice to make this more
6547 // general. It's also subtly incompatible with the hacks FastISel
6549 unsigned Reg = cast<RegisterSDNode>(Res.getOperand(1))->getReg();
6550 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
6551 FuncInfo->ValueMap[I] = Reg;
6555 if (!isOnlyUsedInEntryBlock(I)) {
6556 FuncInfo->InitializeRegForValue(I);
6557 SDB->CopyToExportRegsIfNeeded(I);
6561 assert(i == InVals.size() && "Argument register count mismatch!");
6563 // Finally, if the target has anything special to do, allow it to do so.
6564 // FIXME: this should insert code into the DAG!
6565 EmitFunctionEntryCode();
6568 /// Handle PHI nodes in successor blocks. Emit code into the SelectionDAG to
6569 /// ensure constants are generated when needed. Remember the virtual registers
6570 /// that need to be added to the Machine PHI nodes as input. We cannot just
6571 /// directly add them, because expansion might result in multiple MBB's for one
6572 /// BB. As such, the start of the BB might correspond to a different MBB than
6576 SelectionDAGBuilder::HandlePHINodesInSuccessorBlocks(const BasicBlock *LLVMBB) {
6577 const TerminatorInst *TI = LLVMBB->getTerminator();
6579 SmallPtrSet<MachineBasicBlock *, 4> SuccsHandled;
6581 // Check successor nodes' PHI nodes that expect a constant to be available
6583 for (unsigned succ = 0, e = TI->getNumSuccessors(); succ != e; ++succ) {
6584 const BasicBlock *SuccBB = TI->getSuccessor(succ);
6585 if (!isa<PHINode>(SuccBB->begin())) continue;
6586 MachineBasicBlock *SuccMBB = FuncInfo.MBBMap[SuccBB];
6588 // If this terminator has multiple identical successors (common for
6589 // switches), only handle each succ once.
6590 if (!SuccsHandled.insert(SuccMBB)) continue;
6592 MachineBasicBlock::iterator MBBI = SuccMBB->begin();
6594 // At this point we know that there is a 1-1 correspondence between LLVM PHI
6595 // nodes and Machine PHI nodes, but the incoming operands have not been
6597 for (BasicBlock::const_iterator I = SuccBB->begin();
6598 const PHINode *PN = dyn_cast<PHINode>(I); ++I) {
6599 // Ignore dead phi's.
6600 if (PN->use_empty()) continue;
6603 if (PN->getType()->isEmptyTy())
6607 const Value *PHIOp = PN->getIncomingValueForBlock(LLVMBB);
6609 if (const Constant *C = dyn_cast<Constant>(PHIOp)) {
6610 unsigned &RegOut = ConstantsOut[C];
6612 RegOut = FuncInfo.CreateRegs(C->getType());
6613 CopyValueToVirtualRegister(C, RegOut);
6617 DenseMap<const Value *, unsigned>::iterator I =
6618 FuncInfo.ValueMap.find(PHIOp);
6619 if (I != FuncInfo.ValueMap.end())
6622 assert(isa<AllocaInst>(PHIOp) &&
6623 FuncInfo.StaticAllocaMap.count(cast<AllocaInst>(PHIOp)) &&
6624 "Didn't codegen value into a register!??");
6625 Reg = FuncInfo.CreateRegs(PHIOp->getType());
6626 CopyValueToVirtualRegister(PHIOp, Reg);
6630 // Remember that this register needs to added to the machine PHI node as
6631 // the input for this MBB.
6632 SmallVector<EVT, 4> ValueVTs;
6633 ComputeValueVTs(TLI, PN->getType(), ValueVTs);
6634 for (unsigned vti = 0, vte = ValueVTs.size(); vti != vte; ++vti) {
6635 EVT VT = ValueVTs[vti];
6636 unsigned NumRegisters = TLI.getNumRegisters(*DAG.getContext(), VT);
6637 for (unsigned i = 0, e = NumRegisters; i != e; ++i)
6638 FuncInfo.PHINodesToUpdate.push_back(std::make_pair(MBBI++, Reg+i));
6639 Reg += NumRegisters;
6643 ConstantsOut.clear();